github.com/bytom/bytom@v1.1.2-0.20221014091027-bbcba3df6075/asset/image.go (about)

     1  package asset
     2  
     3  import (
     4  	"encoding/json"
     5  
     6  	log "github.com/sirupsen/logrus"
     7  
     8  	"github.com/bytom/bytom/common"
     9  )
    10  
    11  // Image is the struct for hold export asset data
    12  type Image struct {
    13  	Assets []*Asset `json:"assets"`
    14  }
    15  
    16  // Backup export all the asset info into image
    17  func (reg *Registry) Backup() (*Image, error) {
    18  	assetImage := &Image{
    19  		Assets: []*Asset{},
    20  	}
    21  
    22  	assetIter := reg.db.IteratorPrefix([]byte(assetPrefix))
    23  	defer assetIter.Release()
    24  	for assetIter.Next() {
    25  		asset := &Asset{}
    26  		if err := json.Unmarshal(assetIter.Value(), asset); err != nil {
    27  			return nil, err
    28  		}
    29  		assetImage.Assets = append(assetImage.Assets, asset)
    30  	}
    31  
    32  	return assetImage, nil
    33  }
    34  
    35  // Restore load the image data into asset manage
    36  func (reg *Registry) Restore(image *Image) error {
    37  	maxAssetIndex := uint64(0)
    38  	storeBatch := reg.db.NewBatch()
    39  	for _, asset := range image.Assets {
    40  		if existed := reg.db.Get(Key(&asset.AssetID)); existed != nil {
    41  			log.WithFields(log.Fields{"alias": asset.Alias, "id": asset.AssetID}).Warning("skip restore asset due to already existed")
    42  			continue
    43  		}
    44  		if existed := reg.db.Get(aliasKey(*asset.Alias)); existed != nil {
    45  			return ErrDuplicateAlias
    46  		}
    47  
    48  		rawAsset, err := json.Marshal(asset)
    49  		if err != nil {
    50  			return err
    51  		}
    52  
    53  		if asset.Signer.KeyIndex > maxAssetIndex {
    54  			maxAssetIndex = asset.Signer.KeyIndex
    55  		}
    56  		storeBatch.Set(aliasKey(*asset.Alias), []byte(asset.AssetID.String()))
    57  		storeBatch.Set(Key(&asset.AssetID), rawAsset)
    58  	}
    59  
    60  	if localIndex := reg.getNextAssetIndex(); localIndex < maxAssetIndex {
    61  		storeBatch.Set(assetIndexKey, common.Unit64ToBytes(maxAssetIndex))
    62  	}
    63  	storeBatch.Write()
    64  	return nil
    65  }