github.com/sixexorg/magnetic-ring@v0.0.0-20191119090307-31705a21e419/store/orgchain/storages/account_root_store.go (about)

     1  package storages
     2  
     3  import (
     4  	"bytes"
     5  
     6  	"github.com/syndtr/goleveldb/leveldb/util"
     7  	"github.com/sixexorg/magnetic-ring/store/db"
     8  	"github.com/sixexorg/magnetic-ring/store/orgchain/states"
     9  )
    10  
    11  //prototype pattern
    12  type AccountRootStore struct {
    13  	dbDir string
    14  	store *db.LevelDBStore
    15  }
    16  
    17  func NewAccountRootStore(dbDir string) (*AccountRootStore, error) {
    18  	var err error
    19  	store, err := db.NewLevelDBStore(dbDir)
    20  	if err != nil {
    21  		return nil, err
    22  	}
    23  	accountRootStore := &AccountRootStore{
    24  		dbDir: dbDir,
    25  		store: store,
    26  	}
    27  	return accountRootStore, nil
    28  }
    29  
    30  //NewBatch start a commit batch
    31  func (this *AccountRootStore) NewBatch() {
    32  	this.store.NewBatch()
    33  }
    34  func (this *AccountRootStore) CommitTo() error {
    35  	return this.store.BatchCommit()
    36  }
    37  
    38  func (this *AccountRootStore) Get(height uint64) (*states.AccountStateRoot, error) {
    39  	key := states.GetAccountStateRootKey(height)
    40  	v, err := this.store.Get(key)
    41  	if err != nil {
    42  		return nil, err
    43  	}
    44  	ast := &states.AccountStateRoot{}
    45  	bu := bytes.NewBuffer(key)
    46  	bu.Write(v)
    47  	err = ast.Deserialize(bu)
    48  	if err != nil {
    49  		return nil, err
    50  	}
    51  	return ast, nil
    52  }
    53  
    54  func (this *AccountRootStore) GetRange(start, end uint64) ([]*states.AccountStateRoot, error) {
    55  	sh := states.GetAccountStateRootKey(start)
    56  	eh := states.GetAccountStateRootKey(end)
    57  	iter := this.store.NewSeniorIterator(&util.Range{Start: sh, Limit: eh})
    58  	asrs := make([]*states.AccountStateRoot, 0, end-start+1)
    59  	for iter.Next() {
    60  		asr := &states.AccountStateRoot{}
    61  		buff := bytes.NewBuffer(iter.Key())
    62  		buff.Write(iter.Value())
    63  		asr.Deserialize(buff)
    64  		asrs = append(asrs, asr)
    65  	}
    66  	iter.Release()
    67  	err := iter.Error()
    68  	if err != nil {
    69  		return nil, err
    70  	}
    71  	return asrs, nil
    72  }
    73  
    74  func (this *AccountRootStore) Save(entity *states.AccountStateRoot) error {
    75  	key := entity.GetKey()
    76  	buff := new(bytes.Buffer)
    77  	err := entity.Serialize(buff)
    78  	if err != nil {
    79  		return err
    80  	}
    81  	err = this.store.Put(key, buff.Bytes())
    82  	if err != nil {
    83  		return err
    84  	}
    85  	return nil
    86  }
    87  
    88  func (this *AccountRootStore) BatchRemove(heights []uint64) {
    89  	for _, v := range heights {
    90  		key := states.GetAccountStateRootKey(v)
    91  		this.store.BatchDelete(key)
    92  	}
    93  }