github.com/iotexproject/iotex-core@v1.14.1-rc1/action/protocol/vote/probationlist.go (about) 1 // Copyright (c) 2020 IoTeX Foundation 2 // This source code is provided 'as is' and no warranties are given as to title or non-infringement, merchantability 3 // or fitness for purpose and, to the extent permitted by law, all liability for your use of the code is disclaimed. 4 // This source code is governed by Apache License 2.0 that can be found in the LICENSE file. 5 6 package vote 7 8 import ( 9 "sort" 10 11 "github.com/pkg/errors" 12 "google.golang.org/protobuf/proto" 13 14 "github.com/iotexproject/iotex-proto/golang/iotextypes" 15 ) 16 17 // ProbationList defines a map where key is candidate's name and value is the counter which counts the unproductivity during probation epoch. 18 type ProbationList struct { 19 ProbationInfo map[string]uint32 20 IntensityRate uint32 21 } 22 23 // NewProbationList returns a new probation list 24 func NewProbationList(intensity uint32) *ProbationList { 25 return &ProbationList{ 26 ProbationInfo: make(map[string]uint32), 27 IntensityRate: intensity, 28 } 29 } 30 31 // Serialize serializes map of ProbationList to bytes 32 func (pl *ProbationList) Serialize() ([]byte, error) { 33 return proto.Marshal(pl.Proto()) 34 } 35 36 // Proto converts the ProbationList to a protobuf message 37 func (pl *ProbationList) Proto() *iotextypes.ProbationCandidateList { 38 probationListPb := make([]*iotextypes.ProbationCandidateList_Info, 0, len(pl.ProbationInfo)) 39 names := make([]string, 0, len(pl.ProbationInfo)) 40 for name := range pl.ProbationInfo { 41 names = append(names, name) 42 } 43 sort.Strings(names) 44 for _, name := range names { 45 probationListPb = append(probationListPb, &iotextypes.ProbationCandidateList_Info{ 46 Address: name, 47 Count: pl.ProbationInfo[name], 48 }) 49 } 50 return &iotextypes.ProbationCandidateList{ 51 ProbationList: probationListPb, 52 IntensityRate: pl.IntensityRate, 53 } 54 } 55 56 // Deserialize deserializes bytes to delegate ProbationList 57 func (pl *ProbationList) Deserialize(buf []byte) error { 58 ProbationList := &iotextypes.ProbationCandidateList{} 59 if err := proto.Unmarshal(buf, ProbationList); err != nil { 60 return errors.Wrap(err, "failed to unmarshal probationList") 61 } 62 return pl.LoadProto(ProbationList) 63 } 64 65 // LoadProto loads ProbationList from proto 66 func (pl *ProbationList) LoadProto(probationListpb *iotextypes.ProbationCandidateList) error { 67 probationlistMap := make(map[string]uint32, 0) 68 candidates := probationListpb.ProbationList 69 for _, cand := range candidates { 70 probationlistMap[cand.Address] = cand.Count 71 } 72 pl.ProbationInfo = probationlistMap 73 pl.IntensityRate = probationListpb.IntensityRate 74 75 return nil 76 }