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

     1  package states
     2  
     3  import (
     4  	"io"
     5  
     6  	"io/ioutil"
     7  
     8  	"sort"
     9  
    10  	"github.com/sixexorg/magnetic-ring/common"
    11  	"github.com/sixexorg/magnetic-ring/common/sink"
    12  	"github.com/sixexorg/magnetic-ring/errors"
    13  )
    14  
    15  //for leagueState memberRoot
    16  type LeagueMember struct {
    17  	LeagueId common.Address
    18  	Height   uint64
    19  	hash     common.Hash
    20  	Data     *LeagueAccount
    21  }
    22  
    23  type LeagueAccount struct {
    24  	Account common.Address
    25  	Status  LeagueAccountStatus
    26  }
    27  
    28  type LeagueMembers []*LeagueMember
    29  
    30  func (s LeagueMembers) Len() int           { return len(s) }
    31  func (s LeagueMembers) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
    32  func (s LeagueMembers) Less(i, j int) bool { return s[i].hash.String() < s[j].hash.String() }
    33  func (s LeagueMembers) GetHashRoot() common.Hash {
    34  	sort.Sort(s)
    35  	hashes := make([]common.Hash, 0, s.Len())
    36  	for _, v := range s {
    37  		hashes = append(hashes, v.Hash())
    38  	}
    39  	return common.ComputeMerkleRoot(hashes)
    40  }
    41  
    42  func (this *LeagueMember) Hash() common.Hash {
    43  	buff := this.Serialization()
    44  	hash, _ := common.ParseHashFromBytes(common.Sha256(buff))
    45  	this.hash = hash
    46  	return hash
    47  }
    48  func (this *LeagueMember) Serialization() []byte {
    49  	sk := sink.NewZeroCopySink(nil)
    50  	sk.WriteAddress(this.LeagueId)
    51  	sk.WriteAddress(this.Data.Account)
    52  	sk.WriteUint64(this.Height)
    53  	sk.WriteByte(byte(this.Data.Status))
    54  	return sk.Bytes()
    55  }
    56  func (this *LeagueMember) Deserialize(r io.Reader) error {
    57  	buff, err := ioutil.ReadAll(r)
    58  	if err != nil {
    59  		return err
    60  	}
    61  	var (
    62  		eof    bool
    63  		status byte
    64  	)
    65  	source := sink.NewZeroCopySource(buff)
    66  	_, eof = source.NextByte()
    67  	this.LeagueId, eof = source.NextAddress()
    68  	this.Data = &LeagueAccount{}
    69  	this.Data.Account, eof = source.NextAddress()
    70  	this.Height, eof = source.NextUint64()
    71  
    72  	status, eof = source.NextByte()
    73  	if eof {
    74  		return errors.ERR_TXRAW_EOF
    75  	}
    76  	this.Data.Status = LeagueAccountStatus(status)
    77  	return nil
    78  }