9 "github.com/golang/groupcache/lru"
10 dbm "github.com/tendermint/tmlibs/db"
11 "golang.org/x/crypto/sha3"
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"
25 // DefaultNativeAsset native BTM asset
26 var DefaultNativeAsset *Asset
33 assetIndexKey = []byte("AssetIndex")
34 assetPrefix = []byte("Asset:")
35 aliasPrefix = []byte("AssetAlias:")
36 extAssetPrefix = []byte("EXA:")
39 func initNativeAsset() {
40 signer := &signers.Signer{Type: "internal"}
41 alias := consensus.BTMAlias
43 definitionBytes, _ := serializeAssetDef(consensus.BTMDefinitionMap)
44 DefaultNativeAsset = &Asset{
46 AssetID: *consensus.BTMAssetID,
49 DefinitionMap: consensus.BTMDefinitionMap,
50 RawDefinitionByte: definitionBytes,
54 // AliasKey store asset alias prefix
55 func aliasKey(name string) []byte {
56 return append(aliasPrefix, []byte(name)...)
59 // Key store asset prefix
60 func Key(id *bc.AssetID) []byte {
61 return append(assetPrefix, id.Bytes()...)
64 // ExtAssetKey return store external assets key
65 func ExtAssetKey(id *bc.AssetID) []byte {
66 return append(extAssetPrefix, id.Bytes()...)
69 // pre-define errors for supporting bytom errorFormatter
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")
80 //NewRegistry create new registry
81 func NewRegistry(db dbm.DB, chain *protocol.Chain) *Registry {
86 cache: lru.New(maxAssetCache),
87 aliasCache: lru.New(maxAssetCache),
91 // Registry tracks and stores all known assets on a blockchain.
92 type Registry struct {
100 assetIndexMu sync.Mutex
104 //Asset describe asset on bytom chain
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"`
115 func (reg *Registry) getNextAssetIndex() uint64 {
116 reg.assetIndexMu.Lock()
117 defer reg.assetIndexMu.Unlock()
119 nextIndex := uint64(1)
120 if rawIndex := reg.db.Get(assetIndexKey); rawIndex != nil {
121 nextIndex = common.BytesToUnit64(rawIndex) + 1
124 reg.db.Set(assetIndexKey, common.Unit64ToBytes(nextIndex))
128 // Define defines a new Asset.
129 func (reg *Registry) Define(xpubs []chainkd.XPub, quorum int, definition map[string]interface{}, alias string) (*Asset, error) {
131 return nil, errors.Wrap(signers.ErrNoXPubs)
134 alias = strings.ToUpper(strings.TrimSpace(alias))
136 return nil, errors.Wrap(ErrNullAlias)
139 if alias == consensus.BTMAlias {
140 return nil, ErrInternalAsset
143 nextAssetIndex := reg.getNextAssetIndex()
144 assetSigner, err := signers.Create("asset", xpubs, quorum, nextAssetIndex)
149 rawDefinition, err := serializeAssetDef(definition)
151 return nil, ErrSerializing
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)
162 defHash := bc.NewHash(sha3.Sum256(rawDefinition))
164 DefinitionMap: definition,
165 RawDefinitionByte: rawDefinition,
167 IssuanceProgram: issuanceProgram,
168 AssetID: bc.ComputeAssetID(issuanceProgram, vmver, &defHash),
172 return a, reg.SaveAsset(a, alias)
175 // SaveAsset store asset
176 func (reg *Registry) SaveAsset(a *Asset, alias string) error {
178 defer reg.assetMu.Unlock()
180 aliasKey := aliasKey(alias)
181 if existed := reg.db.Get(aliasKey); existed != nil {
182 return ErrDuplicateAlias
185 assetKey := Key(&a.AssetID)
186 if existAsset := reg.db.Get(assetKey); existAsset != nil {
187 return ErrDuplicateAsset
190 rawAsset, err := json.Marshal(a)
192 return ErrMarshalAsset
195 storeBatch := reg.db.NewBatch()
196 storeBatch.Set(aliasKey, []byte(a.AssetID.String()))
197 storeBatch.Set(assetKey, rawAsset)
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) {
205 cached, ok := reg.cache.Get(id.String())
208 return cached.(*Asset), nil
211 bytes := reg.db.Get(Key(id))
213 return nil, ErrFindAsset
217 if err := json.Unmarshal(bytes, asset); err != nil {
222 reg.cache.Add(id.String(), asset)
227 // FindByAlias retrieves an Asset record along with its signer,
228 // given an asset alias.
229 func (reg *Registry) FindByAlias(alias string) (*Asset, error) {
231 cachedID, ok := reg.aliasCache.Get(alias)
234 return reg.FindByID(nil, cachedID.(*bc.AssetID))
237 rawID := reg.db.Get(aliasKey(alias))
239 return nil, errors.Wrapf(ErrFindAsset, "no such asset, alias: %s", alias)
242 assetID := &bc.AssetID{}
243 if err := assetID.UnmarshalText(rawID); err != nil {
248 reg.aliasCache.Add(alias, assetID)
250 return reg.FindByID(nil, assetID)
253 //GetAliasByID return asset alias string by AssetID string
254 func (reg *Registry) GetAliasByID(id string) string {
256 if id == consensus.BTMAssetID.String() {
257 return consensus.BTMAlias
260 assetID := &bc.AssetID{}
261 if err := assetID.UnmarshalText([]byte(id)); err != nil {
265 asset, err := reg.FindByID(nil, assetID)
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 {
280 if assetID.String() == DefaultNativeAsset.AssetID.String() {
281 return DefaultNativeAsset, nil
285 if interAsset := reg.db.Get(Key(&assetID)); interAsset != nil {
286 if err := json.Unmarshal(interAsset, asset); err != nil {
292 if extAsset := reg.db.Get(ExtAssetKey(&assetID)); extAsset != nil {
293 if err := json.Unmarshal(extAsset, asset); err != nil {
299 return nil, errors.WithDetailf(ErrFindAsset, "no such asset, assetID: %s", id)
302 // ListAssets returns the accounts in the db
303 func (reg *Registry) ListAssets(id string) ([]*Asset, error) {
304 assets := []*Asset{DefaultNativeAsset}
306 assetIDStr := strings.TrimSpace(id)
307 if assetIDStr == DefaultNativeAsset.AssetID.String() {
311 if assetIDStr != "" {
312 assetID := &bc.AssetID{}
313 if err := assetID.UnmarshalText([]byte(assetIDStr)); err != nil {
318 interAsset := reg.db.Get(Key(assetID))
319 if interAsset != nil {
320 if err := json.Unmarshal(interAsset, asset); err != nil {
323 return []*Asset{asset}, nil
326 return []*Asset{}, nil
329 assetIter := reg.db.IteratorPrefix(assetPrefix)
330 defer assetIter.Release()
332 for assetIter.Next() {
334 if err := json.Unmarshal(assetIter.Value(), asset); err != nil {
337 assets = append(assets, asset)
343 // serializeAssetDef produces a canonical byte representation of an asset
344 // definition. Currently, this is implemented using pretty-printed JSON.
345 // As is the standard for Go's map[string] serialization, object keys will
346 // appear in lexicographic order. Although this is mostly meant for machine
347 // consumption, the JSON is pretty-printed for easy reading.
348 func serializeAssetDef(def map[string]interface{}) ([]byte, error) {
350 def = make(map[string]interface{}, 0)
352 return json.MarshalIndent(def, "", " ")
355 func multisigIssuanceProgram(pubkeys []ed25519.PublicKey, nrequired int) (program []byte, vmversion uint64, err error) {
356 issuanceProg, err := vmutil.P2SPMultiSigProgram(pubkeys, nrequired)
360 builder := vmutil.NewBuilder()
361 builder.AddRawBytes(issuanceProg)
362 prog, err := builder.Build()
366 //UpdateAssetAlias updates asset alias
367 func (reg *Registry) UpdateAssetAlias(id, newAlias string) error {
368 oldAlias := reg.GetAliasByID(id)
369 newAlias = strings.ToUpper(strings.TrimSpace(newAlias))
371 if oldAlias == consensus.BTMAlias || newAlias == consensus.BTMAlias {
372 return ErrInternalAsset
375 if oldAlias == "" || newAlias == "" {
380 defer reg.assetMu.Unlock()
382 if _, err := reg.FindByAlias(newAlias); err == nil {
383 return ErrDuplicateAlias
386 findAsset, err := reg.FindByAlias(oldAlias)
391 storeBatch := reg.db.NewBatch()
392 findAsset.Alias = &newAlias
393 assetID := &findAsset.AssetID
394 rawAsset, err := json.Marshal(findAsset)
399 storeBatch.Set(Key(assetID), rawAsset)
400 storeBatch.Set(aliasKey(newAlias), []byte(assetID.String()))
401 storeBatch.Delete(aliasKey(oldAlias))
405 reg.aliasCache.Add(newAlias, assetID)
406 reg.aliasCache.Remove(oldAlias)