OSDN Git Service

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