10 "github.com/golang/groupcache/lru"
11 dbm "github.com/tendermint/tmlibs/db"
12 "golang.org/x/crypto/sha3"
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"
25 var DefaultNativeAsset *Asset
30 //AliasPrefix is asset alias prefix
32 //ExternalAssetPrefix is external definition assets prefix
33 ExternalAssetPrefix = "EXA"
34 indexPrefix = "ASSIDX:"
37 func initNativeAsset() {
38 signer := &signers.Signer{Type: "internal"}
39 alias := consensus.BTMAlias
41 definitionBytes, _ := serializeAssetDef(consensus.BTMDefinitionMap)
42 DefaultNativeAsset = &Asset{
44 AssetID: *consensus.BTMAssetID,
47 DefinitionMap: consensus.BTMDefinitionMap,
48 RawDefinitionByte: definitionBytes,
52 func AliasKey(name string) []byte {
53 return []byte(AliasPrefix + name)
56 //Key asset store prefix
57 func Key(id *bc.AssetID) []byte {
59 return []byte(assetPrefix + name)
62 func indexKey(xpub chainkd.XPub) []byte {
63 return []byte(indexPrefix + xpub.String())
66 //CalcExtAssetKey return store external assets key
67 func CalcExtAssetKey(id *bc.AssetID) []byte {
69 return []byte(ExternalAssetPrefix + name)
72 // pre-define errors for supporting bytom errorFormatter
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")
83 //NewRegistry create new registry
84 func NewRegistry(db dbm.DB, chain *protocol.Chain) *Registry {
89 cache: lru.New(maxAssetCache),
90 aliasCache: lru.New(maxAssetCache),
94 // Registry tracks and stores all known assets on a blockchain.
95 type Registry struct {
101 aliasCache *lru.Cache
103 assetIndexMu sync.Mutex
106 //Asset describe asset on bytom chain
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 Tags map[string]interface{} `json:"tags"`
114 RawDefinitionByte chainjson.HexBytes `json:"raw_definition_byte"`
115 DefinitionMap map[string]interface{} `json:"definition"`
118 func (reg *Registry) getNextAssetIndex(xpubs []chainkd.XPub) (*uint64, error) {
119 reg.assetIndexMu.Lock()
120 defer reg.assetIndexMu.Unlock()
122 var nextIndex uint64 = 1
124 if rawIndex := reg.db.Get(indexKey(xpubs[0])); rawIndex != nil {
125 nextIndex = binary.LittleEndian.Uint64(rawIndex) + 1
128 buf := make([]byte, 8)
129 binary.LittleEndian.PutUint64(buf, nextIndex)
130 reg.db.Set(indexKey(xpubs[0]), buf)
132 return &nextIndex, nil
135 // Define defines a new Asset.
136 func (reg *Registry) Define(xpubs []chainkd.XPub, quorum int, definition map[string]interface{}, alias string, tags map[string]interface{}) (*Asset, error) {
138 return nil, errors.Wrap(signers.ErrNoXPubs)
141 normalizedAlias := strings.ToUpper(strings.TrimSpace(alias))
142 if normalizedAlias == consensus.BTMAlias {
143 return nil, ErrInternalAsset
146 if existed := reg.db.Get(AliasKey(normalizedAlias)); existed != nil {
147 return nil, ErrDuplicateAlias
150 nextAssetIndex, err := reg.getNextAssetIndex(xpubs)
152 return nil, errors.Wrap(err, "get asset index error")
155 assetSigner, err := signers.Create("asset", xpubs, quorum, *nextAssetIndex)
160 rawDefinition, err := serializeAssetDef(definition)
162 return nil, ErrSerializing
165 path := signers.Path(assetSigner, signers.AssetKeySpace)
166 derivedXPubs := chainkd.DeriveXPubs(assetSigner.XPubs, path)
167 derivedPKs := chainkd.XPubKeys(derivedXPubs)
168 issuanceProgram, vmver, err := multisigIssuanceProgram(derivedPKs, assetSigner.Quorum)
173 defHash := bc.NewHash(sha3.Sum256(rawDefinition))
175 DefinitionMap: definition,
176 RawDefinitionByte: rawDefinition,
178 IssuanceProgram: issuanceProgram,
179 AssetID: bc.ComputeAssetID(issuanceProgram, vmver, &defHash),
184 if existAsset := reg.db.Get(Key(&asset.AssetID)); existAsset != nil {
185 return nil, ErrDuplicateAsset
189 asset.Alias = &normalizedAlias
192 ass, err := json.Marshal(asset)
194 return nil, ErrMarshalAsset
197 storeBatch := reg.db.NewBatch()
198 storeBatch.Set(AliasKey(normalizedAlias), []byte(asset.AssetID.String()))
199 storeBatch.Set(Key(&asset.AssetID), ass)
205 // UpdateTags modifies the tags of the specified asset. The asset may be
206 // identified either by id or alias, but not both.
207 func (reg *Registry) UpdateTags(ctx context.Context, assetInfo string, tags map[string]interface{}) (err error) {
209 if asset, err = reg.FindByAlias(ctx, assetInfo); err != nil {
210 assetID := &bc.AssetID{}
211 if err := assetID.UnmarshalText([]byte(assetInfo)); err != nil {
214 if asset, err = reg.FindByID(ctx, assetID); err != nil {
220 rawAsset, err := json.Marshal(asset)
222 return ErrMarshalAsset
225 reg.db.Set(Key(&asset.AssetID), rawAsset)
227 reg.cache.Add(asset.AssetID, asset)
232 // findByID retrieves an Asset record along with its signer, given an assetID.
233 func (reg *Registry) FindByID(ctx context.Context, id *bc.AssetID) (*Asset, error) {
235 cached, ok := reg.cache.Get(id.String())
238 return cached.(*Asset), nil
241 bytes := reg.db.Get(Key(id))
243 return nil, ErrFindAsset
247 if err := json.Unmarshal(bytes, asset); err != nil {
252 reg.cache.Add(id.String(), asset)
257 //GetIDByAlias return AssetID string and nil by asset alias,if err ,return "" and err
258 func (reg *Registry) GetIDByAlias(alias string) (string, error) {
259 rawID := reg.db.Get(AliasKey(alias))
261 return "", ErrFindAsset
263 return string(rawID), nil
266 // FindByAlias retrieves an Asset record along with its signer,
267 // given an asset alias.
268 func (reg *Registry) FindByAlias(ctx context.Context, alias string) (*Asset, error) {
270 cachedID, ok := reg.aliasCache.Get(alias)
273 return reg.FindByID(ctx, cachedID.(*bc.AssetID))
276 rawID := reg.db.Get(AliasKey(alias))
278 return nil, errors.Wrapf(ErrFindAsset, "no such asset, alias: %s", alias)
281 assetID := &bc.AssetID{}
282 if err := assetID.UnmarshalText(rawID); err != nil {
287 reg.aliasCache.Add(alias, assetID)
289 return reg.FindByID(ctx, assetID)
292 //GetAliasByID return asset alias string by AssetID string
293 func (reg *Registry) GetAliasByID(id string) string {
295 if id == consensus.BTMAssetID.String() {
296 return consensus.BTMAlias
299 assetID := &bc.AssetID{}
300 if err := assetID.UnmarshalText([]byte(id)); err != nil {
304 asset, err := reg.FindByID(nil, assetID)
312 // ListAssets returns the accounts in the db
313 func (reg *Registry) ListAssets(id string) ([]*Asset, error) {
314 assets := []*Asset{DefaultNativeAsset}
315 assetIter := reg.db.IteratorPrefix([]byte(assetPrefix + id))
316 defer assetIter.Release()
318 for assetIter.Next() {
320 if err := json.Unmarshal(assetIter.Value(), asset); err != nil {
323 assets = append(assets, asset)
328 // serializeAssetDef produces a canonical byte representation of an asset
329 // definition. Currently, this is implemented using pretty-printed JSON.
330 // As is the standard for Go's map[string] serialization, object keys will
331 // appear in lexicographic order. Although this is mostly meant for machine
332 // consumption, the JSON is pretty-printed for easy reading.
333 // The empty asset def is an empty byte slice.
334 func serializeAssetDef(def map[string]interface{}) ([]byte, error) {
338 return json.MarshalIndent(def, "", " ")
341 func multisigIssuanceProgram(pubkeys []ed25519.PublicKey, nrequired int) (program []byte, vmversion uint64, err error) {
342 issuanceProg, err := vmutil.P2SPMultiSigProgram(pubkeys, nrequired)
346 builder := vmutil.NewBuilder()
347 builder.AddRawBytes(issuanceProg)
348 prog, err := builder.Build()
352 //UpdateAssetAlias updates oldAlias to newAlias
353 func (reg *Registry) UpdateAssetAlias(oldAlias, newAlias string) error {
354 if oldAlias == consensus.BTMAlias || newAlias == consensus.BTMAlias {
355 return ErrInternalAsset
358 if oldAlias == "" || newAlias == "" {
362 if _, err := reg.GetIDByAlias(newAlias); err == nil {
363 return ErrDuplicateAlias
366 findAsset, err := reg.FindByAlias(nil, oldAlias)
371 storeBatch := reg.db.NewBatch()
372 findAsset.Alias = &newAlias
373 assetID := &findAsset.AssetID
374 rawAsset, err := json.Marshal(findAsset)
379 storeBatch.Set(Key(assetID), rawAsset)
380 storeBatch.Set(AliasKey(newAlias), []byte(assetID.String()))
381 storeBatch.Delete(AliasKey(oldAlias))
385 reg.aliasCache.Add(newAlias, assetID)
386 reg.aliasCache.Remove(oldAlias)