github.com/sixexorg/magnetic-ring@v0.0.0-20191119090307-31705a21e419/store/storelaw/vote_state_law.go (about) 1 package storelaw 2 3 import ( 4 "math/big" 5 6 "io" 7 8 "github.com/sixexorg/magnetic-ring/common" 9 "github.com/sixexorg/magnetic-ring/common/serialization" 10 "github.com/sixexorg/magnetic-ring/common/sink" 11 ) 12 13 //voteId is tx 14 type VoteState struct { 15 VoteId common.Hash 16 Height uint64 17 Agree *big.Int 18 Against *big.Int 19 Abstention *big.Int 20 } 21 type AccountVoted struct { 22 VoteId common.Hash 23 Height uint64 24 Accounts []common.Address 25 } 26 27 func (this *VoteState) AddAgree(num *big.Int) { 28 this.Agree.Add(this.Agree, num) 29 } 30 func (this *VoteState) AddAgainst(num *big.Int) { 31 this.Against.Add(this.Against, num) 32 } 33 func (this *VoteState) AddAbstention(num *big.Int) { 34 this.Abstention.Add(this.Abstention, num) 35 } 36 func (this *VoteState) GetVal() []byte { 37 sk := sink.NewZeroCopySink(nil) 38 c1, _ := sink.BigIntToComplex(this.Agree) 39 c2, _ := sink.BigIntToComplex(this.Against) 40 c3, _ := sink.BigIntToComplex(this.Abstention) 41 sk.WriteComplex(c1) 42 sk.WriteComplex(c2) 43 sk.WriteComplex(c3) 44 return sk.Bytes() 45 } 46 47 func (this *VoteState) Deserialize(r io.Reader) error { 48 byteArr, err := serialization.ReadBytes(r, common.HashLength) 49 if err != nil { 50 return err 51 } 52 this.VoteId, err = common.ParseHashFromBytes(byteArr) 53 if err != nil { 54 return err 55 } 56 this.Height, err = serialization.ReadUint64(r) 57 if err != nil { 58 return err 59 } 60 c1, err := serialization.ReadComplex(r) 61 if err != nil { 62 return err 63 } 64 this.Agree, err = c1.ComplexToBigInt() 65 if err != nil { 66 return err 67 } 68 c2, err := serialization.ReadComplex(r) 69 if err != nil { 70 return err 71 } 72 this.Against, err = c2.ComplexToBigInt() 73 if err != nil { 74 return err 75 } 76 77 c3, err := serialization.ReadComplex(r) 78 if err != nil { 79 return err 80 } 81 this.Abstention, err = c3.ComplexToBigInt() 82 if err != nil { 83 return err 84 } 85 return nil 86 } 87 88 //porportion:(0,100) 89 //1:pass,0:unfinished 90 func (this *VoteState) GetResult(total *big.Int, proportion int64) bool { 91 if proportion < 0 { 92 proportion = 0 93 } else if proportion > 100 { 94 proportion = 100 95 } 96 no := big.NewInt(0) 97 no = no.Add(this.Against, this.Abstention) 98 yes := big.NewInt(0).Set(this.Agree) 99 if yes.Cmp(no) == 1 { 100 //voteFor bigger 101 totalTmp := big.NewInt(0).Set(total) 102 totalTmp.Mul(totalTmp, big.NewInt(proportion)) 103 if totalTmp.Cmp(yes.Mul(yes, big.NewInt(100))) == -1 { 104 return true 105 } 106 } 107 return false 108 }