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 RawDefinitionByte chainjson.HexBytes `json:"raw_definition_byte"`
114 DefinitionMap map[string]interface{} `json:"definition"`
117 func (reg *Registry) getNextAssetIndex(xpubs []chainkd.XPub) (*uint64, error) {
118 reg.assetIndexMu.Lock()
119 defer reg.assetIndexMu.Unlock()
121 var nextIndex uint64 = 1
123 if rawIndex := reg.db.Get(indexKey(xpubs[0])); rawIndex != nil {
124 nextIndex = binary.LittleEndian.Uint64(rawIndex) + 1
127 buf := make([]byte, 8)
128 binary.LittleEndian.PutUint64(buf, nextIndex)
129 reg.db.Set(indexKey(xpubs[0]), buf)
131 return &nextIndex, nil
134 // Define defines a new Asset.
135 func (reg *Registry) Define(xpubs []chainkd.XPub, quorum int, definition map[string]interface{}, alias string) (*Asset, error) {
137 return nil, errors.Wrap(signers.ErrNoXPubs)
140 normalizedAlias := strings.ToUpper(strings.TrimSpace(alias))
141 if normalizedAlias == consensus.BTMAlias {
142 return nil, ErrInternalAsset
145 if existed := reg.db.Get(AliasKey(normalizedAlias)); existed != nil {
146 return nil, ErrDuplicateAlias
149 nextAssetIndex, err := reg.getNextAssetIndex(xpubs)
151 return nil, errors.Wrap(err, "get asset index error")
154 assetSigner, err := signers.Create("asset", xpubs, quorum, *nextAssetIndex)
159 rawDefinition, err := serializeAssetDef(definition)
161 return nil, ErrSerializing
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)
172 defHash := bc.NewHash(sha3.Sum256(rawDefinition))
174 DefinitionMap: definition,
175 RawDefinitionByte: rawDefinition,
177 IssuanceProgram: issuanceProgram,
178 AssetID: bc.ComputeAssetID(issuanceProgram, vmver, &defHash),
182 if existAsset := reg.db.Get(Key(&asset.AssetID)); existAsset != nil {
183 return nil, ErrDuplicateAsset
187 asset.Alias = &normalizedAlias
190 ass, err := json.Marshal(asset)
192 return nil, ErrMarshalAsset
195 storeBatch := reg.db.NewBatch()
196 storeBatch.Set(AliasKey(normalizedAlias), []byte(asset.AssetID.String()))
197 storeBatch.Set(Key(&asset.AssetID), ass)
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) {
206 cached, ok := reg.cache.Get(id.String())
209 return cached.(*Asset), nil
212 bytes := reg.db.Get(Key(id))
214 return nil, ErrFindAsset
218 if err := json.Unmarshal(bytes, asset); err != nil {
223 reg.cache.Add(id.String(), asset)
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))
232 return "", ErrFindAsset
234 return string(rawID), nil
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) {
241 cachedID, ok := reg.aliasCache.Get(alias)
244 return reg.FindByID(ctx, cachedID.(*bc.AssetID))
247 rawID := reg.db.Get(AliasKey(alias))
249 return nil, errors.Wrapf(ErrFindAsset, "no such asset, alias: %s", alias)
252 assetID := &bc.AssetID{}
253 if err := assetID.UnmarshalText(rawID); err != nil {
258 reg.aliasCache.Add(alias, assetID)
260 return reg.FindByID(ctx, assetID)
263 //GetAliasByID return asset alias string by AssetID string
264 func (reg *Registry) GetAliasByID(id string) string {
266 if id == consensus.BTMAssetID.String() {
267 return consensus.BTMAlias
270 assetID := &bc.AssetID{}
271 if err := assetID.UnmarshalText([]byte(id)); err != nil {
275 asset, err := reg.FindByID(nil, assetID)
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()
289 for assetIter.Next() {
291 if err := json.Unmarshal(assetIter.Value(), asset); err != nil {
294 assets = append(assets, asset)
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) {
309 return json.MarshalIndent(def, "", " ")
312 func multisigIssuanceProgram(pubkeys []ed25519.PublicKey, nrequired int) (program []byte, vmversion uint64, err error) {
313 issuanceProg, err := vmutil.P2SPMultiSigProgram(pubkeys, nrequired)
317 builder := vmutil.NewBuilder()
318 builder.AddRawBytes(issuanceProg)
319 prog, err := builder.Build()
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
329 if oldAlias == "" || newAlias == "" {
333 if _, err := reg.GetIDByAlias(newAlias); err == nil {
334 return ErrDuplicateAlias
337 findAsset, err := reg.FindByAlias(nil, oldAlias)
342 storeBatch := reg.db.NewBatch()
343 findAsset.Alias = &newAlias
344 assetID := &findAsset.AssetID
345 rawAsset, err := json.Marshal(findAsset)
350 storeBatch.Set(Key(assetID), rawAsset)
351 storeBatch.Set(AliasKey(newAlias), []byte(assetID.String()))
352 storeBatch.Delete(AliasKey(oldAlias))
356 reg.aliasCache.Add(newAlias, assetID)
357 reg.aliasCache.Remove(oldAlias)