github.com/iotexproject/iotex-core@v1.14.1-rc1/action/protocol/staking/endorsement.go (about) 1 package staking 2 3 import ( 4 "math" 5 6 "github.com/pkg/errors" 7 "google.golang.org/protobuf/proto" 8 9 "github.com/iotexproject/iotex-core/action/protocol/staking/stakingpb" 10 ) 11 12 // EndorsementStatus 13 const ( 14 // EndorseExpired means the endorsement is expired 15 EndorseExpired = EndorsementStatus(iota) 16 // UnEndorsing means the endorser has submitted unendorsement, but it is not expired yet 17 UnEndorsing 18 // Endorsed means the endorsement is valid 19 Endorsed 20 ) 21 22 const ( 23 endorsementNotExpireHeight = math.MaxUint64 24 ) 25 26 type ( 27 // EndorsementStatus is a uint8 that represents the status of the endorsement 28 EndorsementStatus uint8 29 30 // Endorsement is a struct that contains the expire height of the Endorsement 31 Endorsement struct { 32 ExpireHeight uint64 33 } 34 ) 35 36 // String returns a human-readable string of the endorsement status 37 func (s EndorsementStatus) String() string { 38 switch s { 39 case EndorseExpired: 40 return "Expired" 41 case UnEndorsing: 42 return "UnEndorsing" 43 case Endorsed: 44 return "Endorsed" 45 default: 46 return "Unknown" 47 } 48 } 49 50 // Status returns the status of the endorsement 51 func (e *Endorsement) Status(height uint64) EndorsementStatus { 52 if e.ExpireHeight == endorsementNotExpireHeight { 53 return Endorsed 54 } 55 if height >= e.ExpireHeight { 56 return EndorseExpired 57 } 58 return UnEndorsing 59 } 60 61 // Serialize serializes endorsement to bytes 62 func (e *Endorsement) Serialize() ([]byte, error) { 63 pb, err := e.toProto() 64 if err != nil { 65 return nil, err 66 } 67 return proto.Marshal(pb) 68 } 69 70 // Deserialize deserializes bytes to endorsement 71 func (e *Endorsement) Deserialize(buf []byte) error { 72 pb := &stakingpb.Endorsement{} 73 if err := proto.Unmarshal(buf, pb); err != nil { 74 return errors.Wrap(err, "failed to unmarshal endorsement") 75 } 76 return e.fromProto(pb) 77 } 78 79 func (e *Endorsement) toProto() (*stakingpb.Endorsement, error) { 80 return &stakingpb.Endorsement{ 81 ExpireHeight: e.ExpireHeight, 82 }, nil 83 } 84 85 func (e *Endorsement) fromProto(pb *stakingpb.Endorsement) error { 86 e.ExpireHeight = pb.ExpireHeight 87 return nil 88 }