OSDN Git Service

b173c3019105f92f0b3ae4c8682d21437f1e1ff1
[bytom/bytom-spv.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 // Key store asset 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         alias = strings.ToUpper(strings.TrimSpace(alias))
135         if alias == "" {
136                 return nil, errors.Wrap(ErrNullAlias)
137         }
138
139         if alias == consensus.BTMAlias {
140                 return nil, ErrInternalAsset
141         }
142
143         nextAssetIndex := reg.getNextAssetIndex()
144         assetSigner, err := signers.Create("asset", xpubs, quorum, nextAssetIndex)
145         if err != nil {
146                 return nil, err
147         }
148
149         rawDefinition, err := serializeAssetDef(definition)
150         if err != nil {
151                 return nil, ErrSerializing
152         }
153
154         path := signers.Path(assetSigner, signers.AssetKeySpace)
155         derivedXPubs := chainkd.DeriveXPubs(assetSigner.XPubs, path)
156         derivedPKs := chainkd.XPubKeys(derivedXPubs)
157         issuanceProgram, vmver, err := multisigIssuanceProgram(derivedPKs, assetSigner.Quorum)
158         if err != nil {
159                 return nil, err
160         }
161
162         defHash := bc.NewHash(sha3.Sum256(rawDefinition))
163         a := &Asset{
164                 DefinitionMap:     definition,
165                 RawDefinitionByte: rawDefinition,
166                 VMVersion:         vmver,
167                 IssuanceProgram:   issuanceProgram,
168                 AssetID:           bc.ComputeAssetID(issuanceProgram, vmver, &defHash),
169                 Signer:            assetSigner,
170                 Alias:             &alias,
171         }
172         return a, reg.SaveAsset(a, alias)
173 }
174
175 // SaveAsset store asset
176 func (reg *Registry) SaveAsset(a *Asset, alias string) error {
177         reg.assetMu.Lock()
178         defer reg.assetMu.Unlock()
179
180         aliasKey := aliasKey(alias)
181         if existed := reg.db.Get(aliasKey); existed != nil {
182                 return ErrDuplicateAlias
183         }
184
185         assetKey := Key(&a.AssetID)
186         if existAsset := reg.db.Get(assetKey); existAsset != nil {
187                 return ErrDuplicateAsset
188         }
189
190         rawAsset, err := json.Marshal(a)
191         if err != nil {
192                 return ErrMarshalAsset
193         }
194
195         storeBatch := reg.db.NewBatch()
196         storeBatch.Set(aliasKey, []byte(a.AssetID.String()))
197         storeBatch.Set(assetKey, rawAsset)
198         storeBatch.Write()
199         return nil
200 }
201
202 // FindByID retrieves an Asset record along with its signer, given an assetID.
203 func (reg *Registry) FindByID(ctx context.Context, id *bc.AssetID) (*Asset, error) {
204         reg.cacheMu.Lock()
205         cached, ok := reg.cache.Get(id.String())
206         reg.cacheMu.Unlock()
207         if ok {
208                 return cached.(*Asset), nil
209         }
210
211         bytes := reg.db.Get(Key(id))
212         if bytes == nil {
213                 return nil, ErrFindAsset
214         }
215
216         asset := &Asset{}
217         if err := json.Unmarshal(bytes, asset); err != nil {
218                 return nil, err
219         }
220
221         reg.cacheMu.Lock()
222         reg.cache.Add(id.String(), asset)
223         reg.cacheMu.Unlock()
224         return asset, nil
225 }
226
227 // FindByAlias retrieves an Asset record along with its signer,
228 // given an asset alias.
229 func (reg *Registry) FindByAlias(alias string) (*Asset, error) {
230         reg.cacheMu.Lock()
231         cachedID, ok := reg.aliasCache.Get(alias)
232         reg.cacheMu.Unlock()
233         if ok {
234                 return reg.FindByID(nil, cachedID.(*bc.AssetID))
235         }
236
237         rawID := reg.db.Get(aliasKey(alias))
238         if rawID == nil {
239                 return nil, errors.Wrapf(ErrFindAsset, "no such asset, alias: %s", alias)
240         }
241
242         assetID := &bc.AssetID{}
243         if err := assetID.UnmarshalText(rawID); err != nil {
244                 return nil, err
245         }
246
247         reg.cacheMu.Lock()
248         reg.aliasCache.Add(alias, assetID)
249         reg.cacheMu.Unlock()
250         return reg.FindByID(nil, assetID)
251 }
252
253 //GetAliasByID return asset alias string by AssetID string
254 func (reg *Registry) GetAliasByID(id string) string {
255         //btm
256         if id == consensus.BTMAssetID.String() {
257                 return consensus.BTMAlias
258         }
259
260         assetID := &bc.AssetID{}
261         if err := assetID.UnmarshalText([]byte(id)); err != nil {
262                 return ""
263         }
264
265         asset, err := reg.FindByID(nil, assetID)
266         if err != nil {
267                 return ""
268         }
269
270         return *asset.Alias
271 }
272
273 // GetAsset get asset by assetID
274 func (reg *Registry) GetAsset(id string) (*Asset, error) {
275         var assetID bc.AssetID
276         if err := assetID.UnmarshalText([]byte(id)); err != nil {
277                 return nil, err
278         }
279
280         if assetID.String() == DefaultNativeAsset.AssetID.String() {
281                 return DefaultNativeAsset, nil
282         }
283
284         asset := &Asset{}
285         if interAsset := reg.db.Get(Key(&assetID)); 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(&assetID)); 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(id string) ([]*Asset, error) {
304         assets := []*Asset{DefaultNativeAsset}
305
306         assetID := &bc.AssetID{}
307         if err := assetID.UnmarshalText([]byte(id)); err != nil {
308                 return nil, err
309         }
310
311         assetIter := reg.db.IteratorPrefix(Key(assetID))
312         defer assetIter.Release()
313
314         for assetIter.Next() {
315                 asset := &Asset{}
316                 if err := json.Unmarshal(assetIter.Value(), asset); err != nil {
317                         return nil, err
318                 }
319                 assets = append(assets, asset)
320         }
321
322         return assets, nil
323 }
324
325 // serializeAssetDef produces a canonical byte representation of an asset
326 // definition. Currently, this is implemented using pretty-printed JSON.
327 // As is the standard for Go's map[string] serialization, object keys will
328 // appear in lexicographic order. Although this is mostly meant for machine
329 // consumption, the JSON is pretty-printed for easy reading.
330 func serializeAssetDef(def map[string]interface{}) ([]byte, error) {
331         if def == nil {
332                 def = make(map[string]interface{}, 0)
333         }
334         return json.MarshalIndent(def, "", "  ")
335 }
336
337 func multisigIssuanceProgram(pubkeys []ed25519.PublicKey, nrequired int) (program []byte, vmversion uint64, err error) {
338         issuanceProg, err := vmutil.P2SPMultiSigProgram(pubkeys, nrequired)
339         if err != nil {
340                 return nil, 0, err
341         }
342         builder := vmutil.NewBuilder()
343         builder.AddRawBytes(issuanceProg)
344         prog, err := builder.Build()
345         return prog, 1, err
346 }
347
348 //UpdateAssetAlias updates asset alias
349 func (reg *Registry) UpdateAssetAlias(id, newAlias string) error {
350         oldAlias := reg.GetAliasByID(id)
351         newAlias = strings.ToUpper(strings.TrimSpace(newAlias))
352
353         if oldAlias == consensus.BTMAlias || newAlias == consensus.BTMAlias {
354                 return ErrInternalAsset
355         }
356
357         if oldAlias == "" || newAlias == "" {
358                 return ErrNullAlias
359         }
360
361         reg.assetMu.Lock()
362         defer reg.assetMu.Unlock()
363
364         if _, err := reg.FindByAlias(newAlias); err == nil {
365                 return ErrDuplicateAlias
366         }
367
368         findAsset, err := reg.FindByAlias(oldAlias)
369         if err != nil {
370                 return err
371         }
372
373         storeBatch := reg.db.NewBatch()
374         findAsset.Alias = &newAlias
375         assetID := &findAsset.AssetID
376         rawAsset, err := json.Marshal(findAsset)
377         if err != nil {
378                 return err
379         }
380
381         storeBatch.Set(Key(assetID), rawAsset)
382         storeBatch.Set(aliasKey(newAlias), []byte(assetID.String()))
383         storeBatch.Delete(aliasKey(oldAlias))
384         storeBatch.Write()
385
386         reg.cacheMu.Lock()
387         reg.aliasCache.Add(newAlias, assetID)
388         reg.aliasCache.Remove(oldAlias)
389         reg.cacheMu.Unlock()
390
391         return nil
392 }