github.com/sixexorg/magnetic-ring@v0.0.0-20191119090307-31705a21e419/store/mainchain/extstorages/league_account_index.go (about)

     1  package extstorages
     2  
     3  import (
     4  	"encoding/binary"
     5  
     6  	"github.com/sixexorg/magnetic-ring/common"
     7  	"github.com/sixexorg/magnetic-ring/common/sink"
     8  	"github.com/sixexorg/magnetic-ring/errors"
     9  	"github.com/sixexorg/magnetic-ring/store/db"
    10  	mcom "github.com/sixexorg/magnetic-ring/store/mainchain/common"
    11  )
    12  
    13  //Redundancy of the leagues data
    14  type ExtAccIndexStore struct {
    15  	enableCache bool
    16  	dbDir       string
    17  	store       *db.LevelDBStore
    18  }
    19  
    20  func NewExtAccIndexStore(dbDir string, enableCache bool) (*ExtAccIndexStore, error) {
    21  	store, err := db.NewLevelDBStore(dbDir)
    22  	if err != nil {
    23  		return nil, err
    24  	}
    25  	el := new(ExtAccIndexStore)
    26  	el.enableCache = enableCache
    27  	el.dbDir = dbDir
    28  	el.store = store
    29  	return el, nil
    30  }
    31  
    32  func (this *ExtAccIndexStore) Save(height uint64, leagueId common.Address, addrs []common.Address, hashes common.HashArray) error {
    33  	key := this.getKey(height, leagueId)
    34  	cp, err := sink.AddressesToComplex(addrs)
    35  	if err != nil {
    36  		return err
    37  	}
    38  	cp2, err := sink.HashArrayToComplex(hashes)
    39  	if err != nil {
    40  		return err
    41  	}
    42  	sk := sink.NewZeroCopySink(nil)
    43  	sk.WriteComplex(cp)
    44  	sk.WriteComplex(cp2)
    45  	return this.store.Put(key, sk.Bytes())
    46  }
    47  func (this *ExtAccIndexStore) Get(height uint64, leagueId common.Address) ([]common.Address, common.HashArray, error) {
    48  	key := this.getKey(height, leagueId)
    49  	val, err := this.store.Get(key)
    50  	if err != nil {
    51  		if err == errors.ERR_DB_NOT_FOUND {
    52  			return []common.Address{}, common.HashArray{}, nil
    53  		}
    54  		return nil, nil, err
    55  	}
    56  	sk := sink.NewZeroCopySource(val)
    57  	cp, eof := sk.NextComplex()
    58  	if eof {
    59  		return nil, nil, errors.ERR_SINK_EOF
    60  	}
    61  	cp2, eof := sk.NextComplex()
    62  	if eof {
    63  		return nil, nil, errors.ERR_SINK_EOF
    64  	}
    65  	addrs, err := cp.ComplexToTxAddresses()
    66  	if err != nil {
    67  		return nil, nil, err
    68  	}
    69  	hashes, err := cp2.ComplexToHashArray()
    70  	if err != nil {
    71  		return nil, nil, err
    72  	}
    73  	return addrs, hashes, nil
    74  }
    75  
    76  func (tshi *ExtAccIndexStore) getKey(height uint64, leagueId common.Address) []byte {
    77  	buff := make([]byte, 1+8+common.AddrLength)
    78  	buff[0] = byte(mcom.EXT_LEAGUE_ACCOUNT_INDEX)
    79  	copy(buff[1:common.AddrLength+1], leagueId[:])
    80  	binary.LittleEndian.PutUint64(buff[1+common.AddrLength:], height)
    81  	return buff
    82  }