OSDN Git Service

Merge branch 'dev' into backup
[bytom/bytom.git] / asset / asset.go
1 package asset
2
3 import (
4         "context"
5         "encoding/json"
6         "strings"
7         "sync"
8
9         "github.com/golang/groupcache/lru"
10         dbm "github.com/tendermint/tmlibs/db"
11         "golang.org/x/crypto/sha3"
12
13         "github.com/bytom/blockchain/signers"
14         "github.com/bytom/common"
15         "github.com/bytom/consensus"
16         "github.com/bytom/crypto/ed25519"
17         "github.com/bytom/crypto/ed25519/chainkd"
18         chainjson "github.com/bytom/encoding/json"
19         "github.com/bytom/errors"
20         "github.com/bytom/protocol"
21         "github.com/bytom/protocol/bc"
22         "github.com/bytom/protocol/vm/vmutil"
23 )
24
25 // DefaultNativeAsset native BTM asset
26 var DefaultNativeAsset *Asset
27
28 const (
29         maxAssetCache = 1000
30 )
31
32 var (
33         assetIndexKey  = []byte("AssetIndex")
34         assetPrefix    = []byte("Asset:")
35         aliasPrefix    = []byte("AssetAlias:")
36         extAssetPrefix = []byte("EXA:")
37 )
38
39 func initNativeAsset() {
40         signer := &signers.Signer{Type: "internal"}
41         alias := consensus.BTMAlias
42
43         definitionBytes, _ := serializeAssetDef(consensus.BTMDefinitionMap)
44         DefaultNativeAsset = &Asset{
45                 Signer:            signer,
46                 AssetID:           *consensus.BTMAssetID,
47                 Alias:             &alias,
48                 VMVersion:         1,
49                 DefinitionMap:     consensus.BTMDefinitionMap,
50                 RawDefinitionByte: definitionBytes,
51         }
52 }
53
54 // AliasKey store asset alias prefix
55 func AliasKey(name string) []byte {
56         return append(aliasPrefix, []byte(name)...)
57 }
58
59 // AssetKey asset store prefix
60 func Key(id *bc.AssetID) []byte {
61         return append(assetPrefix, id.Bytes()...)
62 }
63
64 // ExtAssetKey return store external assets key
65 func ExtAssetKey(id *bc.AssetID) []byte {
66         return append(extAssetPrefix, id.Bytes()...)
67 }
68
69 // pre-define errors for supporting bytom errorFormatter
70 var (
71         ErrDuplicateAlias = errors.New("duplicate asset alias")
72         ErrDuplicateAsset = errors.New("duplicate asset id")
73         ErrSerializing    = errors.New("serializing asset definition")
74         ErrMarshalAsset   = errors.New("failed marshal asset")
75         ErrFindAsset      = errors.New("fail to find asset")
76         ErrInternalAsset  = errors.New("btm has been defined as the internal asset")
77         ErrNullAlias      = errors.New("null asset alias")
78 )
79
80 //NewRegistry create new registry
81 func NewRegistry(db dbm.DB, chain *protocol.Chain) *Registry {
82         initNativeAsset()
83         return &Registry{
84                 db:         db,
85                 chain:      chain,
86                 cache:      lru.New(maxAssetCache),
87                 aliasCache: lru.New(maxAssetCache),
88         }
89 }
90
91 // Registry tracks and stores all known assets on a blockchain.
92 type Registry struct {
93         db    dbm.DB
94         chain *protocol.Chain
95
96         cacheMu    sync.Mutex
97         cache      *lru.Cache
98         aliasCache *lru.Cache
99
100         assetIndexMu sync.Mutex
101         assetMu      sync.Mutex
102 }
103
104 //Asset describe asset on bytom chain
105 type Asset struct {
106         *signers.Signer
107         AssetID           bc.AssetID             `json:"id"`
108         Alias             *string                `json:"alias"`
109         VMVersion         uint64                 `json:"vm_version"`
110         IssuanceProgram   chainjson.HexBytes     `json:"issue_program"`
111         RawDefinitionByte chainjson.HexBytes     `json:"raw_definition_byte"`
112         DefinitionMap     map[string]interface{} `json:"definition"`
113 }
114
115 func (reg *Registry) getNextAssetIndex() uint64 {
116         reg.assetIndexMu.Lock()
117         defer reg.assetIndexMu.Unlock()
118
119         nextIndex := uint64(1)
120         if rawIndex := reg.db.Get(assetIndexKey); rawIndex != nil {
121                 nextIndex = common.BytesToUnit64(rawIndex) + 1
122         }
123
124         reg.db.Set(assetIndexKey, common.Unit64ToBytes(nextIndex))
125         return nextIndex
126 }
127
128 // Define defines a new Asset.
129 func (reg *Registry) Define(xpubs []chainkd.XPub, quorum int, definition map[string]interface{}, alias string) (*Asset, error) {
130         if len(xpubs) == 0 {
131                 return nil, errors.Wrap(signers.ErrNoXPubs)
132         }
133
134         normalizedAlias := strings.ToUpper(strings.TrimSpace(alias))
135         if normalizedAlias == "" {
136                 return nil, errors.Wrap(ErrNullAlias)
137         }
138
139         if normalizedAlias == consensus.BTMAlias {
140                 return nil, ErrInternalAsset
141         }
142
143         reg.assetMu.Lock()
144         defer reg.assetMu.Unlock()
145
146         if existed := reg.db.Get(AliasKey(normalizedAlias)); existed != nil {
147                 return nil, ErrDuplicateAlias
148         }
149
150         nextAssetIndex := reg.getNextAssetIndex()
151         assetSigner, err := signers.Create("asset", xpubs, quorum, nextAssetIndex)
152         if err != nil {
153                 return nil, err
154         }
155
156         rawDefinition, err := serializeAssetDef(definition)
157         if err != nil {
158                 return nil, ErrSerializing
159         }
160
161         path := signers.Path(assetSigner, signers.AssetKeySpace)
162         derivedXPubs := chainkd.DeriveXPubs(assetSigner.XPubs, path)
163         derivedPKs := chainkd.XPubKeys(derivedXPubs)
164         issuanceProgram, vmver, err := multisigIssuanceProgram(derivedPKs, assetSigner.Quorum)
165         if err != nil {
166                 return nil, err
167         }
168
169         defHash := bc.NewHash(sha3.Sum256(rawDefinition))
170         asset := &Asset{
171                 DefinitionMap:     definition,
172                 RawDefinitionByte: rawDefinition,
173                 VMVersion:         vmver,
174                 IssuanceProgram:   issuanceProgram,
175                 AssetID:           bc.ComputeAssetID(issuanceProgram, vmver, &defHash),
176                 Signer:            assetSigner,
177                 Alias:             &normalizedAlias,
178         }
179
180         if existAsset := reg.db.Get(Key(&asset.AssetID)); existAsset != nil {
181                 return nil, ErrDuplicateAsset
182         }
183
184         ass, err := json.Marshal(asset)
185         if err != nil {
186                 return nil, ErrMarshalAsset
187         }
188
189         storeBatch := reg.db.NewBatch()
190         storeBatch.Set(AliasKey(normalizedAlias), []byte(asset.AssetID.String()))
191         storeBatch.Set(Key(&asset.AssetID), ass)
192         storeBatch.Write()
193
194         return asset, nil
195 }
196
197 // FindByID retrieves an Asset record along with its signer, given an assetID.
198 func (reg *Registry) FindByID(ctx context.Context, id *bc.AssetID) (*Asset, error) {
199         reg.cacheMu.Lock()
200         cached, ok := reg.cache.Get(id.String())
201         reg.cacheMu.Unlock()
202         if ok {
203                 return cached.(*Asset), nil
204         }
205
206         bytes := reg.db.Get(Key(id))
207         if bytes == nil {
208                 return nil, ErrFindAsset
209         }
210
211         asset := &Asset{}
212         if err := json.Unmarshal(bytes, asset); err != nil {
213                 return nil, err
214         }
215
216         reg.cacheMu.Lock()
217         reg.cache.Add(id.String(), asset)
218         reg.cacheMu.Unlock()
219         return asset, nil
220 }
221
222 //GetIDByAlias return AssetID string and nil by asset alias,if err ,return "" and err
223 func (reg *Registry) GetIDByAlias(alias string) (string, error) {
224         rawID := reg.db.Get(AliasKey(alias))
225         if rawID == nil {
226                 return "", ErrFindAsset
227         }
228         return string(rawID), nil
229 }
230
231 // FindByAlias retrieves an Asset record along with its signer,
232 // given an asset alias.
233 func (reg *Registry) FindByAlias(ctx context.Context, alias string) (*Asset, error) {
234         reg.cacheMu.Lock()
235         cachedID, ok := reg.aliasCache.Get(alias)
236         reg.cacheMu.Unlock()
237         if ok {
238                 return reg.FindByID(ctx, cachedID.(*bc.AssetID))
239         }
240
241         rawID := reg.db.Get(AliasKey(alias))
242         if rawID == nil {
243                 return nil, errors.Wrapf(ErrFindAsset, "no such asset, alias: %s", alias)
244         }
245
246         assetID := &bc.AssetID{}
247         if err := assetID.UnmarshalText(rawID); err != nil {
248                 return nil, err
249         }
250
251         reg.cacheMu.Lock()
252         reg.aliasCache.Add(alias, assetID)
253         reg.cacheMu.Unlock()
254         return reg.FindByID(ctx, assetID)
255 }
256
257 //GetAliasByID return asset alias string by AssetID string
258 func (reg *Registry) GetAliasByID(id string) string {
259         //btm
260         if id == consensus.BTMAssetID.String() {
261                 return consensus.BTMAlias
262         }
263
264         assetID := &bc.AssetID{}
265         if err := assetID.UnmarshalText([]byte(id)); err != nil {
266                 return ""
267         }
268
269         asset, err := reg.FindByID(nil, assetID)
270         if err != nil {
271                 return ""
272         }
273
274         return *asset.Alias
275 }
276
277 // GetAsset get asset by assetID
278 func (reg *Registry) GetAsset(id *bc.AssetID) (*Asset, error) {
279         asset := &Asset{}
280
281         if id.String() == DefaultNativeAsset.AssetID.String() {
282                 return DefaultNativeAsset, nil
283         }
284
285         if interAsset := reg.db.Get(Key(id)); interAsset != nil {
286                 if err := json.Unmarshal(interAsset, asset); err != nil {
287                         return nil, err
288                 }
289                 return asset, nil
290         }
291
292         if extAsset := reg.db.Get(ExtAssetKey(id)); extAsset != nil {
293                 if err := json.Unmarshal(extAsset, asset); err != nil {
294                         return nil, err
295                 }
296                 return asset, nil
297         }
298
299         return nil, errors.WithDetailf(ErrFindAsset, "no such asset, assetID: %s", id)
300 }
301
302 // ListAssets returns the accounts in the db
303 func (reg *Registry) ListAssets() ([]*Asset, error) {
304         assets := []*Asset{DefaultNativeAsset}
305         assetIter := reg.db.IteratorPrefix(assetPrefix)
306         defer assetIter.Release()
307
308         for assetIter.Next() {
309                 asset := &Asset{}
310                 if err := json.Unmarshal(assetIter.Value(), asset); err != nil {
311                         return nil, err
312                 }
313                 assets = append(assets, asset)
314         }
315
316         return assets, nil
317 }
318
319 // serializeAssetDef produces a canonical byte representation of an asset
320 // definition. Currently, this is implemented using pretty-printed JSON.
321 // As is the standard for Go's map[string] serialization, object keys will
322 // appear in lexicographic order. Although this is mostly meant for machine
323 // consumption, the JSON is pretty-printed for easy reading.
324 func serializeAssetDef(def map[string]interface{}) ([]byte, error) {
325         if def == nil {
326                 def = make(map[string]interface{}, 0)
327         }
328         return json.MarshalIndent(def, "", "  ")
329 }
330
331 func multisigIssuanceProgram(pubkeys []ed25519.PublicKey, nrequired int) (program []byte, vmversion uint64, err error) {
332         issuanceProg, err := vmutil.P2SPMultiSigProgram(pubkeys, nrequired)
333         if err != nil {
334                 return nil, 0, err
335         }
336         builder := vmutil.NewBuilder()
337         builder.AddRawBytes(issuanceProg)
338         prog, err := builder.Build()
339         return prog, 1, err
340 }
341
342 //UpdateAssetAlias updates asset alias
343 func (reg *Registry) UpdateAssetAlias(id, newAlias string) error {
344         oldAlias := reg.GetAliasByID(id)
345         normalizedAlias := strings.ToUpper(strings.TrimSpace(newAlias))
346
347         if oldAlias == consensus.BTMAlias || newAlias == consensus.BTMAlias {
348                 return ErrInternalAsset
349         }
350
351         if oldAlias == "" || normalizedAlias == "" {
352                 return ErrNullAlias
353         }
354
355         if _, err := reg.GetIDByAlias(normalizedAlias); err == nil {
356                 return ErrDuplicateAlias
357         }
358
359         findAsset, err := reg.FindByAlias(nil, oldAlias)
360         if err != nil {
361                 return err
362         }
363
364         storeBatch := reg.db.NewBatch()
365         findAsset.Alias = &normalizedAlias
366         assetID := &findAsset.AssetID
367         rawAsset, err := json.Marshal(findAsset)
368         if err != nil {
369                 return err
370         }
371
372         storeBatch.Set(Key(assetID), rawAsset)
373         storeBatch.Set(AliasKey(newAlias), []byte(assetID.String()))
374         storeBatch.Delete(AliasKey(oldAlias))
375         storeBatch.Write()
376
377         reg.cacheMu.Lock()
378         reg.aliasCache.Add(newAlias, assetID)
379         reg.aliasCache.Remove(oldAlias)
380         reg.cacheMu.Unlock()
381
382         return nil
383 }