-
Notifications
You must be signed in to change notification settings - Fork 82
/
committee.go
488 lines (430 loc) · 11.7 KB
/
committee.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
package types
import (
"bytes"
"crypto/ecdsa"
"encoding/json"
"fmt"
"io"
"math/big"
"strings"
"sync/atomic"
"github.com/truechain/truechain-engineering-code/common"
"github.com/truechain/truechain-engineering-code/common/hexutil"
"github.com/truechain/truechain-engineering-code/crypto"
"github.com/truechain/truechain-engineering-code/log"
"github.com/truechain/truechain-engineering-code/rlp"
"golang.org/x/crypto/sha3"
)
const (
// CommitteeStart start pbft consensus
CommitteeStart = iota
// CommitteeStop stop pbft consensus
CommitteeStop
// CommitteeSwitchover switch pbft committee
CommitteeSwitchover
// CommitteeUpdate update committee members and backups
CommitteeUpdate
// CommitteeOver notify current pbft committee end fastBlock
CommitteeOver
StateUnusedFlag = 0xa0
StateUsedFlag = 0xa1
StateSwitchingFlag = 0xa2
StateRemovedFlag = 0xa3
StateAppendFlag = 0xa4
// health enter type
TypeFixed = 0xa1
TypeWorked = 0xa2
TypeBack = 0xa3
)
const (
//VoteAgreeAgainst vote sign with against
VoteAgreeAgainst = iota
//VoteAgree vote sign with agree
VoteAgree
Normal = iota
FetcherCall
DownloaderCall
SFetcherCall
SDownloaderCall
PeerSendCall
FetcherHeadCall
SFetcherHeadCall
DownloaderFetchCall
DownloaderPartCall
SDownloaderFetchCall
SDownloaderLoopCall
SDownloaderPartCall
)
//CommitteeMembers committee members
type CommitteeMembers []*CommitteeMember
type CommitteeMember struct {
Coinbase common.Address
CommitteeBase common.Address
Publickey []byte
Flag uint32
MType uint32
}
// ElectionCommittee defines election members result
type ElectionCommittee struct {
Members []*CommitteeMember
Backups []*CommitteeMember
}
func NewCommitteeMember(coinBase common.Address, publicKey []byte, flag, mType uint32) *CommitteeMember {
return &CommitteeMember{
Coinbase: coinBase,
Publickey: publicKey,
CommitteeBase: common.BytesToAddress(crypto.Keccak256(publicKey[1:])[12:]),
Flag: flag,
MType: mType,
}
}
func (c *CommitteeMember) Compared(d *CommitteeMember) bool {
if c.MType == d.MType && c.Coinbase == d.Coinbase && c.CommitteeBase == d.CommitteeBase && bytes.Equal(c.Publickey, d.Publickey) {
return true
}
return false
}
func (c *CommitteeMember) String() string {
return fmt.Sprintf("F:%d,T:%d,C:%s,P:%s,A:%s", c.Flag, c.MType, hexutil.Encode(c.Coinbase[:]),
hexutil.Encode(c.Publickey), hexutil.Encode(c.CommitteeBase[:]))
}
func (c *CommitteeMember) UnmarshalJSON(input []byte) error {
type committee struct {
Address common.Address `json:"address,omitempty"`
PubKey *hexutil.Bytes `json:"publickey,omitempty"`
Flag uint32 `json:"flag,omitempty"`
MType uint32 `json:"mType,omitempty"`
}
var dec committee
if err := json.Unmarshal(input, &dec); err != nil {
return err
}
c.Coinbase = dec.Address
c.Flag = dec.Flag
c.MType = dec.MType
if dec.PubKey != nil {
c.Publickey = *dec.PubKey
}
/*var err error
if dec.PubKey != nil {
_, err = crypto.UnmarshalPubkey(*dec.PubKey)
if err != nil {
return err
}
}*/
return nil
}
//CommitteeNode contains main info of committee node
type CommitteeNode struct {
IP string
Port uint32
Port2 uint32
Coinbase common.Address
Publickey []byte
}
//
type TransportCommitteeNode struct {
IP string
Port uint32
Port2 uint32
EXT []byte
}
func (tcn *TransportCommitteeNode) ConvertTransportToCommitteeNode(pubKey *ecdsa.PublicKey) *CommitteeNode {
return &CommitteeNode{
IP: tcn.IP,
Port: tcn.Port,
Port2: tcn.Port2,
Publickey: crypto.FromECDSAPub(pubKey),
}
}
func (cn *CommitteeNode) ConvertCommitteeNodeToTransport() *TransportCommitteeNode {
return &TransportCommitteeNode{
IP: cn.IP,
Port: cn.Port,
Port2: cn.Port2,
}
}
func (c *CommitteeNode) String() string {
return fmt.Sprintf("NodeInfo:{IP:%s,P1:%v,P2:%v,Coinbase:%s,P:%s}", c.IP, c.Port, c.Port2,
hexutil.Encode(c.Coinbase[:]), hexutil.Encode(c.Publickey))
}
type PbftSigns []*PbftSign
//go:generate gencodec -type PbftSign -field-override pbftSignMarshaling -out gen_pbftSign_json.go
type PbftSign struct {
FastHeight *big.Int
FastHash common.Hash // fastblock hash
Result uint32 // 0--against,1--agree
Sign []byte // sign for fastblock height + hash + result
// caches
size atomic.Value
}
// field type overrides for gencodec
type pbftSignMarshaling struct {
FastHeight *hexutil.Big
Sign hexutil.Bytes
}
// "external" PbftSign encoding. used for etrue protocol, etc.
type extPbftSign struct {
FastHeight *big.Int
FastHash common.Hash // fastblock hash
Result uint32 // 0--against,1--agree
Sign []byte //sign msg
}
// DecodeRLP decodes the truechain
func (c *PbftSign) DecodeRLP(s *rlp.Stream) error {
var ep extPbftSign
_, size, _ := s.Kind()
if err := s.Decode(&ep); err != nil {
return err
}
c.FastHeight, c.FastHash, c.Result, c.Sign = ep.FastHeight, ep.FastHash, ep.Result, ep.Sign
c.size.Store(common.StorageSize(rlp.ListSize(size)))
return nil
}
// EncodeRLP serializes b into the truechain RLP block format.
func (p *PbftSign) EncodeRLP(w io.Writer) error {
return rlp.Encode(w, extPbftSign{
FastHeight: p.FastHeight,
FastHash: p.FastHash,
Result: p.Result,
Sign: p.Sign,
})
}
type PbftAgentProxy interface {
FetchFastBlock(committeeId *big.Int, infos []*CommitteeMember) (*Block, error)
VerifyFastBlock(*Block, bool) (*PbftSign, error)
BroadcastConsensus(block *Block) error
GetCurrentHeight() *big.Int
GetSeedMember() []*CommitteeMember
GetFastLastProposer() common.Address
}
type PbftServerProxy interface {
PutCommittee(committeeInfo *CommitteeInfo) error
UpdateCommittee(info *CommitteeInfo) error
PutNodes(id *big.Int, nodes []*CommitteeNode) error
Notify(id *big.Int, action int) error
SetCommitteeStop(committeeId *big.Int, stop uint64) error
GetCommitteeStatus(committeeID *big.Int) map[string]interface{}
IsLeader(committeeID *big.Int) bool
}
// Hash returns the block hash of the PbftSign, which is simply the keccak256 hash of its
// RLP encoding.
func (h *PbftSign) Hash() common.Hash {
return rlpHash(h)
}
//HashWithNoSign returns the hash which PbftSign without sign
func (h *PbftSign) HashWithNoSign() common.Hash {
return rlpHash([]interface{}{
h.FastHeight,
h.FastHash,
h.Result,
})
}
type CommitteeInfo struct {
Id *big.Int
StartHeight *big.Int
EndHeight *big.Int
Members []*CommitteeMember
BackMembers []*CommitteeMember
}
func CopyCommitteeInfo(committeeInfo *CommitteeInfo) *CommitteeInfo {
committeeInfo_copy := *committeeInfo
return &committeeInfo_copy
}
func (c *CommitteeInfo) GetAllMembers() []*CommitteeMember {
var members []*CommitteeMember
members = append(members, c.Members...)
members = append(members, c.BackMembers...)
return members
}
func (c *CommitteeInfo) String() string {
if c.Members != nil {
memStrings := make([]string, len(c.Members))
backMemStrings := make([]string, len(c.BackMembers))
for i, m := range c.Members {
if m == nil {
memStrings[i] = "nil-Member"
} else {
memStrings[i] = m.String()
}
}
for i, m := range c.BackMembers {
if m == nil {
backMemStrings[i] = "nil-Member"
} else {
backMemStrings[i] = m.String()
}
}
return fmt.Sprintf("CommitteeInfo{ID:%s,SH:%s,EH:%s,M:{%s},BM:{%s}}", c.Id, c.StartHeight, c.EndHeight,
strings.Join(memStrings, "\n "), strings.Join(backMemStrings, "\n "))
}
return fmt.Sprintf("CommitteeInfo{ID:%s,SH:%s,EH:%s}", c.Id, c.StartHeight, c.EndHeight)
}
//EncryptCommitteeNode represent a committee member encrypt info
// which encrypt committeeNode with member Publickey
type EncryptCommitteeNode []byte
type Sign []byte
//EncryptNodeMessage all information of the committee
type EncryptNodeMessage struct {
CreatedAt *big.Int
CommitteeID *big.Int
Nodes []EncryptCommitteeNode
Sign //sign msg
// caches
hash atomic.Value
size atomic.Value
}
// "external" EncryptNode encoding. used for etrue protocol, etc.
type extEncryptNode struct {
CreatedAt *big.Int
CommitteeID *big.Int
Nodes []EncryptCommitteeNode
Sign //sign msg
}
// DecodeRLP decodes the truechain
func (c *EncryptNodeMessage) DecodeRLP(s *rlp.Stream) error {
var ee extEncryptNode
_, size, _ := s.Kind()
if err := s.Decode(&ee); err != nil {
return err
}
c.CreatedAt, c.CommitteeID, c.Nodes, c.Sign = ee.CreatedAt, ee.CommitteeID, ee.Nodes, ee.Sign
c.size.Store(common.StorageSize(rlp.ListSize(size)))
return nil
}
// EncodeRLP serializes b into the truechain RLP block format.
func (c *EncryptNodeMessage) EncodeRLP(w io.Writer) error {
return rlp.Encode(w, extEncryptNode{
CreatedAt: c.CreatedAt,
CommitteeID: c.CommitteeID,
Nodes: c.Nodes,
Sign: c.Sign,
})
}
func (c *EncryptNodeMessage) String(str string) {
log.Info(str, "reatedAt", c.CreatedAt.Uint64(), "CommitteeID", c.CommitteeID)
}
func (c *EncryptNodeMessage) HashWithoutSign() common.Hash {
return RlpHash([]interface{}{
c.CreatedAt,
c.Nodes,
c.CommitteeID,
})
}
func (c *EncryptNodeMessage) Hash() common.Hash {
if hash := c.hash.Load(); hash != nil {
return hash.(common.Hash)
}
v := RlpHash(c)
c.hash.Store(v)
return v
}
type CommitteeNodeTag struct {
CommitteeID *big.Int
PubKey []byte
}
func (c *CommitteeNodeTag) Hash() common.Hash {
return RlpHash([]interface{}{
c.CommitteeID,
c.PubKey,
})
}
func RlpHash(x interface{}) (h common.Hash) {
hw := sha3.NewLegacyKeccak256()
if e := rlp.Encode(hw, x); e != nil {
log.Warn("RlpHash", "error", e.Error())
}
hw.Sum(h[:0])
return h
}
func (c *EncryptNodeMessage) Size() common.StorageSize {
if size := c.size.Load(); size != nil {
return size.(common.StorageSize)
}
wc := writeCounter(0)
rlp.Encode(&wc, c)
c.size.Store(common.StorageSize(wc))
return common.StorageSize(wc)
}
// SwitchEnter is the enter inserted in block when committee member changed
type SwitchEnter struct {
CommitteeBase common.Address
Flag uint32
}
// Hash return SwitchInfos hash bytes
func (s *SwitchInfos) Hash() common.Hash {
return rlpHash(s)
}
func (s *SwitchEnter) String() string {
if s == nil {
return "switchEnter-nil"
}
return fmt.Sprintf("p:%s,s:%d", hexutil.Encode(s.CommitteeBase.Bytes()), s.Flag)
}
func (s *SwitchEnter) Equal(other *SwitchEnter) bool {
if s == nil && other == nil {
return true
}
if s == nil || other == nil {
return false
}
return bytes.Equal(s.CommitteeBase.Bytes(), other.CommitteeBase.Bytes()) && s.Flag == other.Flag
}
type SwitchEnters []*SwitchEnter
// Equal will equal not require item index
func (s SwitchEnters) Equal(other SwitchEnters) bool {
if s == nil && other == nil {
return true
}
if s == nil || other == nil {
return false
}
if len(s) != len(other) {
return false
}
for _, v1 := range s {
equal := false
for _, v2 := range other {
if v1.Equal(v2) {
equal = true
}
}
if !equal {
return false
}
}
return true
}
// SwitchInfos is the infos inserted in block when committee member changed
type SwitchInfos struct {
CID *big.Int
Members []*CommitteeMember
BackMembers []*CommitteeMember
Vals []*SwitchEnter
}
func (s *SwitchInfos) String() string {
if s == nil {
return "switchInfo-nil"
}
memStrings := make([]string, len(s.Vals))
for i, m := range s.Vals {
if m == nil {
memStrings[i] = "nil-Member"
} else {
memStrings[i] = m.String()
}
}
return fmt.Sprintf("SwitchInfos{CID:%d,Vals:{%s}}", s.CID, strings.Join(memStrings, "\n "))
}
func (s *SwitchInfos) ToHash() common.Hash {
return rlpHash(s)
}
func (s *SwitchInfos) Equal(other *SwitchInfos) bool {
if s == nil && other == nil {
return true
}
if s == nil || other == nil {
return false
}
return s.CID == other.CID && SwitchEnters(s.Vals).Equal(SwitchEnters(other.Vals))
}