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 // DefaultNativeAsset native BTM asset
26 var DefaultNativeAsset *Asset
31 //AliasPrefix is asset alias prefix
33 //ExternalAssetPrefix is external definition assets prefix
34 ExternalAssetPrefix = "EXA"
35 indexPrefix = "ASSIDX:"
38 func initNativeAsset() {
39 signer := &signers.Signer{Type: "internal"}
40 alias := consensus.BTMAlias
42 definitionBytes, _ := serializeAssetDef(consensus.BTMDefinitionMap)
43 DefaultNativeAsset = &Asset{
45 AssetID: *consensus.BTMAssetID,
48 DefinitionMap: consensus.BTMDefinitionMap,
49 RawDefinitionByte: definitionBytes,
53 // AliasKey store asset alias prefix
54 func AliasKey(name string) []byte {
55 return []byte(AliasPrefix + name)
58 //Key asset store prefix
59 func Key(id *bc.AssetID) []byte {
61 return []byte(assetPrefix + name)
64 func indexKey(xpub chainkd.XPub) []byte {
65 return []byte(indexPrefix + xpub.String())
68 //CalcExtAssetKey return store external assets key
69 func CalcExtAssetKey(id *bc.AssetID) []byte {
71 return []byte(ExternalAssetPrefix + name)
74 // pre-define errors for supporting bytom errorFormatter
76 ErrDuplicateAlias = errors.New("duplicate asset alias")
77 ErrDuplicateAsset = errors.New("duplicate asset id")
78 ErrSerializing = errors.New("serializing asset definition")
79 ErrMarshalAsset = errors.New("failed marshal asset")
80 ErrFindAsset = errors.New("fail to find asset")
81 ErrInternalAsset = errors.New("btm has been defined as the internal asset")
82 ErrNullAlias = errors.New("null asset alias")
85 //NewRegistry create new registry
86 func NewRegistry(db dbm.DB, chain *protocol.Chain) *Registry {
91 cache: lru.New(maxAssetCache),
92 aliasCache: lru.New(maxAssetCache),
96 // Registry tracks and stores all known assets on a blockchain.
97 type Registry struct {
103 aliasCache *lru.Cache
105 assetIndexMu sync.Mutex
108 //Asset describe asset on bytom chain
111 AssetID bc.AssetID `json:"id"`
112 Alias *string `json:"alias"`
113 VMVersion uint64 `json:"vm_version"`
114 IssuanceProgram chainjson.HexBytes `json:"issue_program"`
115 RawDefinitionByte chainjson.HexBytes `json:"raw_definition_byte"`
116 DefinitionMap map[string]interface{} `json:"definition"`
119 func (reg *Registry) getNextAssetIndex(xpubs []chainkd.XPub) (*uint64, error) {
120 reg.assetIndexMu.Lock()
121 defer reg.assetIndexMu.Unlock()
123 var nextIndex uint64 = 1
125 if rawIndex := reg.db.Get(indexKey(xpubs[0])); rawIndex != nil {
126 nextIndex = binary.LittleEndian.Uint64(rawIndex) + 1
129 buf := make([]byte, 8)
130 binary.LittleEndian.PutUint64(buf, nextIndex)
131 reg.db.Set(indexKey(xpubs[0]), buf)
133 return &nextIndex, nil
136 // Define defines a new Asset.
137 func (reg *Registry) Define(xpubs []chainkd.XPub, quorum int, definition map[string]interface{}, alias string) (*Asset, error) {
139 return nil, errors.Wrap(signers.ErrNoXPubs)
142 normalizedAlias := strings.ToUpper(strings.TrimSpace(alias))
143 if normalizedAlias == consensus.BTMAlias {
144 return nil, ErrInternalAsset
147 if existed := reg.db.Get(AliasKey(normalizedAlias)); existed != nil {
148 return nil, ErrDuplicateAlias
151 nextAssetIndex, err := reg.getNextAssetIndex(xpubs)
153 return nil, errors.Wrap(err, "get asset index error")
156 assetSigner, err := signers.Create("asset", xpubs, quorum, *nextAssetIndex)
161 rawDefinition, err := serializeAssetDef(definition)
163 return nil, ErrSerializing
166 path := signers.Path(assetSigner, signers.AssetKeySpace)
167 derivedXPubs := chainkd.DeriveXPubs(assetSigner.XPubs, path)
168 derivedPKs := chainkd.XPubKeys(derivedXPubs)
169 issuanceProgram, vmver, err := multisigIssuanceProgram(derivedPKs, assetSigner.Quorum)
174 defHash := bc.NewHash(sha3.Sum256(rawDefinition))
176 DefinitionMap: definition,
177 RawDefinitionByte: rawDefinition,
179 IssuanceProgram: issuanceProgram,
180 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 // FindByID retrieves an Asset record along with its signer, given an assetID.
206 func (reg *Registry) FindByID(ctx context.Context, id *bc.AssetID) (*Asset, error) {
208 cached, ok := reg.cache.Get(id.String())
211 return cached.(*Asset), nil
214 bytes := reg.db.Get(Key(id))
216 return nil, ErrFindAsset
220 if err := json.Unmarshal(bytes, asset); err != nil {
225 reg.cache.Add(id.String(), asset)
230 //GetIDByAlias return AssetID string and nil by asset alias,if err ,return "" and err
231 func (reg *Registry) GetIDByAlias(alias string) (string, error) {
232 rawID := reg.db.Get(AliasKey(alias))
234 return "", ErrFindAsset
236 return string(rawID), nil
239 // FindByAlias retrieves an Asset record along with its signer,
240 // given an asset alias.
241 func (reg *Registry) FindByAlias(ctx context.Context, alias string) (*Asset, error) {
243 cachedID, ok := reg.aliasCache.Get(alias)
246 return reg.FindByID(ctx, cachedID.(*bc.AssetID))
249 rawID := reg.db.Get(AliasKey(alias))
251 return nil, errors.Wrapf(ErrFindAsset, "no such asset, alias: %s", alias)
254 assetID := &bc.AssetID{}
255 if err := assetID.UnmarshalText(rawID); err != nil {
260 reg.aliasCache.Add(alias, assetID)
262 return reg.FindByID(ctx, assetID)
265 //GetAliasByID return asset alias string by AssetID string
266 func (reg *Registry) GetAliasByID(id string) string {
268 if id == consensus.BTMAssetID.String() {
269 return consensus.BTMAlias
272 assetID := &bc.AssetID{}
273 if err := assetID.UnmarshalText([]byte(id)); err != nil {
277 asset, err := reg.FindByID(nil, assetID)
285 // ListAssets returns the accounts in the db
286 func (reg *Registry) ListAssets(id string) ([]*Asset, error) {
287 assets := []*Asset{DefaultNativeAsset}
288 assetIter := reg.db.IteratorPrefix([]byte(assetPrefix + id))
289 defer assetIter.Release()
291 for assetIter.Next() {
293 if err := json.Unmarshal(assetIter.Value(), asset); err != nil {
296 assets = append(assets, asset)
301 // serializeAssetDef produces a canonical byte representation of an asset
302 // definition. Currently, this is implemented using pretty-printed JSON.
303 // As is the standard for Go's map[string] serialization, object keys will
304 // appear in lexicographic order. Although this is mostly meant for machine
305 // consumption, the JSON is pretty-printed for easy reading.
306 func serializeAssetDef(def map[string]interface{}) ([]byte, error) {
308 def = make(map[string]interface{}, 0)
310 return json.MarshalIndent(def, "", " ")
313 func multisigIssuanceProgram(pubkeys []ed25519.PublicKey, nrequired int) (program []byte, vmversion uint64, err error) {
314 issuanceProg, err := vmutil.P2SPMultiSigProgram(pubkeys, nrequired)
318 builder := vmutil.NewBuilder()
319 builder.AddRawBytes(issuanceProg)
320 prog, err := builder.Build()
324 //UpdateAssetAlias updates oldAlias to newAlias
325 func (reg *Registry) UpdateAssetAlias(oldAlias, newAlias string) error {
326 if oldAlias == consensus.BTMAlias || newAlias == consensus.BTMAlias {
327 return ErrInternalAsset
330 if oldAlias == "" || newAlias == "" {
334 if _, err := reg.GetIDByAlias(newAlias); err == nil {
335 return ErrDuplicateAlias
338 findAsset, err := reg.FindByAlias(nil, oldAlias)
343 storeBatch := reg.db.NewBatch()
344 findAsset.Alias = &newAlias
345 assetID := &findAsset.AssetID
346 rawAsset, err := json.Marshal(findAsset)
351 storeBatch.Set(Key(assetID), rawAsset)
352 storeBatch.Set(AliasKey(newAlias), []byte(assetID.String()))
353 storeBatch.Delete(AliasKey(oldAlias))
357 reg.aliasCache.Add(newAlias, assetID)
358 reg.aliasCache.Remove(oldAlias)