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

     1  package extstorages
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/binary"
     6  	"fmt"
     7  	"math/big"
     8  
     9  	"github.com/sixexorg/magnetic-ring/common"
    10  	"github.com/sixexorg/magnetic-ring/common/serialization"
    11  	"github.com/sixexorg/magnetic-ring/common/sink"
    12  	"github.com/sixexorg/magnetic-ring/store/db"
    13  	scom "github.com/sixexorg/magnetic-ring/store/mainchain/common"
    14  )
    15  
    16  type ExtUTStore struct {
    17  	dbDir string           //Store file path
    18  	store *db.LevelDBStore //Store handler
    19  }
    20  
    21  func NewExtUTStore(dbDir string) (*ExtUTStore, error) {
    22  	var err error
    23  	store, err := db.NewLevelDBStore(dbDir)
    24  	if err != nil {
    25  		return nil, err
    26  	}
    27  	utStore := &ExtUTStore{
    28  		dbDir: dbDir,
    29  		store: store,
    30  	}
    31  	return utStore, nil
    32  }
    33  
    34  func (this *ExtUTStore) GetUTByHeight(height uint64, leagueId common.Address) *big.Int {
    35  	key := this.getKey(height, leagueId)
    36  	iter := this.store.NewIterator(nil)
    37  	buff := bytes.NewBuffer(nil)
    38  	flag := true
    39  	if iter.Seek(key) {
    40  		if bytes.Compare(iter.Key(), key) == 0 {
    41  			buff.Write(iter.Value())
    42  			flag = false
    43  		}
    44  	}
    45  	if flag && iter.Prev() {
    46  		buff.Write(iter.Value())
    47  	}
    48  	iter.Release()
    49  	err := iter.Error()
    50  	if err != nil {
    51  		return big.NewInt(0)
    52  	}
    53  	cp, err := serialization.ReadComplex(buff)
    54  	if err != nil {
    55  		return big.NewInt(0)
    56  	}
    57  	bg, _ := cp.ComplexToBigInt()
    58  	return bg
    59  }
    60  func (this *ExtUTStore) Save(height uint64, leagueId common.Address, ut *big.Int) error {
    61  	fmt.Printf("⛔️leagueext ut save height:%d ut:%v\n", height, ut)
    62  	key := this.getKey(height, leagueId)
    63  	sk := sink.NewZeroCopySink(nil)
    64  	cp, _ := sink.BigIntToComplex(ut)
    65  	sk.WriteComplex(cp)
    66  	return this.store.Put(key, sk.Bytes())
    67  }
    68  
    69  func (this *ExtUTStore) getKey(height uint64, leagueId common.Address) []byte {
    70  	buff := make([]byte, 9+common.AddrLength)
    71  	buff[0] = byte(scom.EXT_UT)
    72  	copy(buff[1:common.AddrLength+1], leagueId[:])
    73  	binary.LittleEndian.PutUint64(buff[common.AddrLength+1:], height)
    74  	return buff
    75  }