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

     1  package states
     2  
     3  import (
     4  	"encoding/binary"
     5  	"io"
     6  	"io/ioutil"
     7  
     8  	"github.com/sixexorg/magnetic-ring/common"
     9  	"github.com/sixexorg/magnetic-ring/common/sink"
    10  	"github.com/sixexorg/magnetic-ring/errors"
    11  	mcom "github.com/sixexorg/magnetic-ring/store/orgchain/common"
    12  )
    13  
    14  type AccountStateRoot struct {
    15  	Height   uint64
    16  	Accounts []common.Address
    17  }
    18  
    19  func NewAccountStateRoot(height uint64, accounts []common.Address) *AccountStateRoot {
    20  	return &AccountStateRoot{
    21  		Height:   height,
    22  		Accounts: accounts,
    23  	}
    24  }
    25  func (this *AccountStateRoot) Serialize(w io.Writer) error {
    26  	sk := sink.NewZeroCopySink(nil)
    27  	cp, err := sink.AddressesToComplex(this.Accounts)
    28  	if err != nil {
    29  		return err
    30  	}
    31  	sk.WriteComplex(cp)
    32  	w.Write(sk.Bytes())
    33  	return nil
    34  }
    35  
    36  func (this *AccountStateRoot) Deserialize(r io.Reader) error {
    37  	buff, err := ioutil.ReadAll(r)
    38  	if err != nil {
    39  		return err
    40  	}
    41  	var eof bool
    42  	source := sink.NewZeroCopySource(buff)
    43  	_, eof = source.NextByte()
    44  	this.Height, eof = source.NextUint64()
    45  	cp, eof := source.NextComplex()
    46  	this.Accounts, err = cp.ComplexToTxAddresses()
    47  	if err != nil {
    48  		return err
    49  	}
    50  	if eof {
    51  		return errors.ERR_TXRAW_EOF
    52  	}
    53  	return nil
    54  }
    55  
    56  func (this *AccountStateRoot) GetKey() []byte {
    57  	return GetAccountStateRootKey(this.Height)
    58  }
    59  
    60  func GetAccountStateRootKey(height uint64) []byte {
    61  	buff := make([]byte, 1+8)
    62  	buff[0] = byte(mcom.ST_ACCOUNT_ROOT)
    63  	binary.LittleEndian.PutUint64(buff[1:], height)
    64  	return buff
    65  }