This repository has been archived by the owner on Jul 30, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
/
candidate.go
91 lines (82 loc) · 2.18 KB
/
candidate.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package dposstate
import (
"fmt"
"github.com/gogo/protobuf/proto"
"github.com/medibloc/go-medibloc/common"
dpospb "github.com/medibloc/go-medibloc/consensus/dpos/pb"
"github.com/medibloc/go-medibloc/util"
"github.com/medibloc/go-medibloc/util/byteutils"
)
// Candidate is struct for save candidate state
type Candidate struct {
ID []byte // candidate id = txHash
Addr common.Address
Collateral *util.Uint128 // candidate collateral
VotePower *util.Uint128 // sum of voters' staking
URL string
Timestamp int64
}
func (c *Candidate) fromProto(pbCandidate *dpospb.Candidate) error {
var err error
c.ID = pbCandidate.Id
if err := c.Addr.FromBytes(pbCandidate.Addr); err != nil {
return err
}
c.Collateral, err = util.NewUint128FromFixedSizeByteSlice(pbCandidate.Collateral)
if err != nil {
return err
}
c.VotePower, err = util.NewUint128FromFixedSizeByteSlice(pbCandidate.VotePower)
if err != nil {
return err
}
c.URL = pbCandidate.Url
c.Timestamp = pbCandidate.Timestamp
return nil
}
// FromBytes set Candidate struct from bytes
func (c *Candidate) FromBytes(bytes []byte) error {
pbCandidate := new(dpospb.Candidate)
if err := proto.Unmarshal(bytes, pbCandidate); err != nil {
return err
}
return c.fromProto(pbCandidate)
}
func (c *Candidate) toProto() (*dpospb.Candidate, error) {
collateral, err := c.Collateral.ToFixedSizeByteSlice()
if err != nil {
return nil, err
}
votePower, err := c.VotePower.ToFixedSizeByteSlice()
if err != nil {
return nil, err
}
return &dpospb.Candidate{
Id: c.ID,
TxHash: c.ID,
Addr: c.Addr.Bytes(),
Collateral: collateral,
VotePower: votePower,
Url: c.URL,
Timestamp: c.Timestamp,
}, nil
}
// ToBytes marshal Candidate struct to bytes
func (c *Candidate) ToBytes() ([]byte, error) {
pbCandidate, err := c.toProto()
if err != nil {
return nil, err
}
return proto.Marshal(pbCandidate)
}
// String returns string representation of candidate
func (c *Candidate) String() string {
return fmt.Sprintf(`{ID:%v, addr:%v, collateral:%v, votePower:%v, url:%v, timestamp:%v}`,
byteutils.Bytes2Hex(c.ID),
c.Addr.Hex(),
c.Collateral,
c.VotePower,
c.URL,
c.Timestamp,
)
}