forked from hyperledger-labs/bdls-lab
-
Notifications
You must be signed in to change notification settings - Fork 2
/
consensus.go
1677 lines (1456 loc) · 48.4 KB
/
consensus.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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package bdls
import (
"bytes"
"container/list"
"crypto/ecdsa"
"crypto/elliptic"
"net"
"sort"
"time"
//"fmt"
"github.com/BDLS-bft/bdls/crypto/blake2b"
proto "github.com/gogo/protobuf/proto"
)
const (
// the current BDLS protocol version,
// version will be sent along with messages for protocol upgrading.
ProtocolVersion = 1
// DefaultConsensusLatency is the default propagation latency setting for
// consensus protocol, user can adjust consensus object's latency setting
// via Consensus.SetLatency()
DefaultConsensusLatency = 300 * time.Millisecond
// MaxConsensusLatency is the ceiling of latencies
MaxConsensusLatency = 10 * time.Second
)
type (
// State is the data to participant in consensus. This could be candidate
// blocks in blockchain systems
State []byte
// StateHash = H(State)
StateHash [blake2b.Size256]byte
)
// defaultHash is the system default hash function
func defaultHash(s State) StateHash { return blake2b.Sum256(s) }
type (
// consensusStage defines the status of consensus automata
consensusStage byte
)
// status definitions for consensus state machine
const (
// stages are strictly ordered, do not change!
stageRoundChanging consensusStage = iota
stageLock
stageCommit
stageLockRelease
)
type messageTuple struct {
StateHash StateHash // computed while adding
Message *Message // the decoded message
Signed *SignedProto // the encoded message with signature
}
// a sorter for messageTuple slice
type tupleSorter struct {
tuples []messageTuple
by func(t1, t2 *messageTuple) bool
}
// Len implements sort.Interface
func (s *tupleSorter) Len() int { return len(s.tuples) }
// Swap implements sort.Interface
func (s *tupleSorter) Swap(i, j int) { s.tuples[i], s.tuples[j] = s.tuples[j], s.tuples[i] }
// Less implements sort.Interface
func (s *tupleSorter) Less(i, j int) bool { return s.by(&s.tuples[i], &s.tuples[j]) }
// consensusRound maintains exchanging messages in a round.
type consensusRound struct {
c *Consensus // the consensus object belongs to
Stage consensusStage // indicates current status in consensus automata
RoundNumber uint64 // round number
LockedState State // leader's locked state
LockedStateHash StateHash // hash of the leaders's locked state
RoundChangeSent bool // mark if the <roundchange> message of this round has sent
CommitSent bool // mark if this round has sent commit message once
// NOTE: we MUST keep the original message, to re-marshal the message may
// result in different BITS LAYOUT, and different hash of course.
roundChanges []messageTuple // stores <roundchange> message tuples of this round
commits []messageTuple // stores <commit> message tuples of this round
// track current max proposed state in <roundchange>, we don't have to compute this for
// a non-leader participant, or if there're no more than 2t+1 messages for leader.
MaxProposedState State
MaxProposedCount int
}
// newConsensusRound creates a new round, and sets the round number
func newConsensusRound(round uint64, c *Consensus) *consensusRound {
r := new(consensusRound)
r.RoundNumber = round
r.c = c
return r
}
// AddRoundChange adds a <roundchange> message to this round, and
// checks to accept only one <roundchange> message from one participant,
// to prevent multiple proposals attack.
func (r *consensusRound) AddRoundChange(sp *SignedProto, m *Message) bool {
for k := range r.roundChanges {
if r.roundChanges[k].Signed.X == sp.X && r.roundChanges[k].Signed.Y == sp.Y {
return false
}
}
r.roundChanges = append(r.roundChanges, messageTuple{StateHash: r.c.stateHash(m.State), Message: m, Signed: sp})
return true
}
// FindRoundChange will try to find a <roundchange> from a given participant,
// and returns index, -1 if not found
func (r *consensusRound) FindRoundChange(X PubKeyAxis, Y PubKeyAxis) int {
for k := range r.roundChanges {
if r.roundChanges[k].Signed.X == X && r.roundChanges[k].Signed.Y == Y {
return k
}
}
return -1
}
// RemoveRoundChange removes the given <roundchange> message at idx
func (r *consensusRound) RemoveRoundChange(idx int) {
// swap to the end and shrink slice
n := len(r.roundChanges) - 1
r.roundChanges[idx], r.roundChanges[n] = r.roundChanges[n], r.roundChanges[idx]
r.roundChanges[n] = messageTuple{} // set to nil to avoid memory leak
r.roundChanges = r.roundChanges[:n]
}
// NumRoundChanges returns count of <roundchange> messages.
func (r *consensusRound) NumRoundChanges() int { return len(r.roundChanges) }
// SignedRoundChanges converts and returns []*SignedProto(as slice)
func (r *consensusRound) SignedRoundChanges() []*SignedProto {
proof := make([]*SignedProto, 0, len(r.roundChanges))
for k := range r.roundChanges {
proof = append(proof, r.roundChanges[k].Signed)
}
return proof
}
// RoundChangeStates returns all non-nil state in exchanging round change message as slice
func (r *consensusRound) RoundChangeStates() []State {
states := make([]State, 0, len(r.roundChanges))
for k := range r.roundChanges {
if r.roundChanges[k].Message.State != nil {
states = append(states, r.roundChanges[k].Message.State)
}
}
return states
}
// AddCommit adds decoded messages along with its original signed message unchanged,
// also, messages will be de-duplicated to prevent multiple proposals attack.
func (r *consensusRound) AddCommit(sp *SignedProto, m *Message) bool {
for k := range r.commits {
if r.commits[k].Signed.X == sp.X && r.commits[k].Signed.Y == sp.Y {
return false
}
}
r.commits = append(r.commits, messageTuple{StateHash: r.c.stateHash(m.State), Message: m, Signed: sp})
return true
}
// NumCommitted counts <commit> messages which points to what the leader has locked.
func (r *consensusRound) NumCommitted() int {
var count int
for k := range r.commits {
if r.commits[k].StateHash == r.LockedStateHash {
count++
}
}
return count
}
// SignedCommits converts and returns []*SignedProto
func (r *consensusRound) SignedCommits() []*SignedProto {
proof := make([]*SignedProto, 0, len(r.commits))
for k := range r.commits {
proof = append(proof, r.commits[k].Signed)
}
return proof
}
// GetMaxProposed finds the most agreed-on non-nil state, if these is any.
func (r *consensusRound) GetMaxProposed() (s State, count int) {
if len(r.roundChanges) == 0 {
return nil, 0
}
// sort by hash, to group identical hashes together
// O(n*logn)
sorter := tupleSorter{
tuples: r.roundChanges,
// sort by it's hash lexicographically
by: func(t1, t2 *messageTuple) bool {
return bytes.Compare(t1.StateHash[:], t2.StateHash[:]) < 0
},
}
sort.Sort(&sorter)
// find the maximum occurred hash
// O(n)
maxCount := 1
maxState := r.roundChanges[0]
curCount := 1
n := len(r.roundChanges)
for i := 1; i < n; i++ {
if r.roundChanges[i].StateHash == r.roundChanges[i-1].StateHash {
curCount++
} else {
if curCount > maxCount {
maxCount = curCount
maxState = r.roundChanges[i-1]
}
curCount = 1
}
}
// if the last hash is the maximum occurred
if curCount > maxCount {
maxCount = curCount
maxState = r.roundChanges[n-1]
}
return maxState.Message.State, maxCount
}
// Consensus implements a deterministic BDLS consensus protocol.
//
// It has no internal clocking or IO, and no parallel processing.
// The runtime behavior is predictable and deterministic.
// Users should write their own timing and IO function to feed in
// messages and ticks to trigger timeouts.
type Consensus struct {
latestState State // latest confirmed state of current height
latestHeight uint64 // latest confirmed height
latestRound uint64 // latest confirmed round
latestProof *SignedProto // latest <decide> message to prove the state
unconfirmed []State // data awaiting to be confirmed at next height
rounds list.List // all rounds at next height(consensus round in progress)
currentRound *consensusRound // current round which has collected >=2t+1 <roundchange>
// timeouts in different stage
rcTimeout time.Time // roundchange status timeout: Delta_0
lockTimeout time.Time // lock status timeout: Delta_1
commitTimeout time.Time // commit status timeout: Delta_2
lockReleaseTimeout time.Time // lock-release status timeout: Delta_3
// locked states, along with its signatures and hashes in tuple
locks []messageTuple
// the StateCompare function from config
stateCompare func(State, State) int
// the StateValidate function from config
stateValidate func(State) bool
// message in callback
messageValidator func(c *Consensus, m *Message, sp *SignedProto) bool
// message out callback
messageOutCallback func(m *Message, sp *SignedProto)
// public key to identity function
pubKeyToIdentity func(pubkey *ecdsa.PublicKey) Identity
// the StateHash function to identify a state
stateHash func(State) StateHash
// private key
privateKey *ecdsa.PrivateKey
// my publickey coodinate
identity Identity
// curve retrieved from private key
curve elliptic.Curve
// transmission delay
latency time.Duration
// all connected peers
peers []PeerInterface
// participants is the consensus group, current leader is r % quorum
participants []Identity
// count num of individual identities
numIdentities int //[YONGGE WANG' comments:] make sure this is synchronized with []Identity
// set to true to enable <commit> message unicast
enableCommitUnicast bool
// NOTE: fixed leader for testing purpose
fixedLeader *Identity
// broadcasting messages being sent to myself
loopback [][]byte
// the last message which caused round change
lastRoundChangeProof []*SignedProto
}
// NewConsensus creates a BDLS consensus object to participant in consensus procedure,
// the consensus object returned is data in memory without goroutines or other
// non-deterministic objects, and errors will be returned if there is problem, with
// the given config.
func NewConsensus(config *Config) (*Consensus, error) {
err := VerifyConfig(config)
if err != nil {
return nil, err
}
c := new(Consensus)
c.init(config)
return c, nil
}
// init consensus with config
func (c *Consensus) init(config *Config) {
// setting current state & height
c.latestHeight = config.CurrentHeight
c.participants = config.Participants
c.stateCompare = config.StateCompare
c.stateValidate = config.StateValidate
c.messageValidator = config.MessageValidator
c.messageOutCallback = config.MessageOutCallback
c.privateKey = config.PrivateKey
c.pubKeyToIdentity = config.PubKeyToIdentity
c.enableCommitUnicast = config.EnableCommitUnicast
// if config has not set hash function, use the default
if c.stateHash == nil {
c.stateHash = defaultHash
}
// if config has not set public key to identity function, use the default
if c.pubKeyToIdentity == nil {
c.pubKeyToIdentity = DefaultPubKeyToIdentity
}
c.identity = c.pubKeyToIdentity(&c.privateKey.PublicKey)
c.curve = c.privateKey.Curve
// initial default parameters settings
c.latency = DefaultConsensusLatency
// and initiated the first <roundchange> proposal
c.switchRound(0)
c.currentRound.Stage = stageRoundChanging
c.broadcastRoundChange()
// set rcTimeout to lockTimeout
c.rcTimeout = config.Epoch.Add(c.roundchangeDuration(0))
// count number of individual identites
ids := make(map[Identity]bool)
for _, id := range c.participants {
ids[id] = true
}
c.numIdentities = len(ids)
}
// calculates roundchangeDuration
func (c *Consensus) roundchangeDuration(round uint64) time.Duration {
d := 2 * c.latency * (1 << round)
if d > MaxConsensusLatency {
d = MaxConsensusLatency
}
return d
}
// calculates collectDuration
func (c *Consensus) collectDuration(round uint64) time.Duration {
d := 2 * c.latency * (1 << round)
if d > MaxConsensusLatency {
d = MaxConsensusLatency
}
return d
}
// calculates lockDuration
func (c *Consensus) lockDuration(round uint64) time.Duration {
d := 4 * c.latency * (1 << round)
if d > MaxConsensusLatency {
d = MaxConsensusLatency
}
return d
}
// calculates commitDuration
func (c *Consensus) commitDuration(round uint64) time.Duration {
d := 2 * c.latency * (1 << round)
if d > MaxConsensusLatency {
d = MaxConsensusLatency
}
return d
}
// calculates lockReleaseDuration
func (c *Consensus) lockReleaseDuration(round uint64) time.Duration {
d := 2 * c.latency * (1 << round)
if d > MaxConsensusLatency {
d = MaxConsensusLatency
}
return d
}
// maximalLocked finds the maximum locked data in this round,
// with regard to StateCompare function in config.
func (c *Consensus) maximalLocked() State {
if len(c.locks) > 0 {
maxState := c.locks[0].Message.State
for i := 1; i < len(c.locks); i++ {
if c.stateCompare(maxState, c.locks[i].Message.State) < 0 {
maxState = c.locks[i].Message.State
}
}
return maxState
}
return nil
}
// maximalUnconfirmed finds the maximal unconfirmed data with,
// regard to the StateCompare function in config.
func (c *Consensus) maximalUnconfirmed() State {
if len(c.unconfirmed) > 0 {
maxState := c.unconfirmed[0]
for i := 1; i < len(c.unconfirmed); i++ {
if c.stateCompare(maxState, c.unconfirmed[i]) < 0 {
maxState = c.unconfirmed[i]
}
}
return maxState
}
return nil
}
// verifyMessage verifies message signature against it's <r,s> & <x,y>,
// and also checks if the signer is a valid participant.
// returns it's decoded 'Message' object if signature has proved authentic.
// returns nil and error if message has not been correctly signed or from an unknown participant.
func (c *Consensus) verifyMessage(signed *SignedProto) (*Message, error) {
if signed == nil {
return nil, ErrMessageIsEmpty
}
// check signer's identity, all participants have proven
// public key
knownParticipants := false
coord := c.pubKeyToIdentity(signed.PublicKey(c.curve))
for k := range c.participants {
if coord == c.participants[k] {
knownParticipants = true
}
}
if !knownParticipants {
return nil, ErrMessageUnknownParticipant
}
/*
// public key validation
p := defaultCurve.Params().P
x := new(big.Int).SetBytes(signed.X[:])
y := new(big.Int).SetBytes(signed.Y[:])
if x.Cmp(p) >= 0 || y.Cmp(p) >= 0 {
return nil, ErrMessageSignature
}
if !defaultCurve.IsOnCurve(x, y) {
return nil, ErrMessageSignature
}
*/
// as public key is proven , we don't have to verify the public key
if !signed.Verify(c.curve) {
return nil, ErrMessageSignature
}
// decode message
m := new(Message)
err := proto.Unmarshal(signed.Message, m)
if err != nil {
return nil, err
}
return m, nil
}
// verify <roundchange> message
func (c *Consensus) verifyRoundChangeMessage(m *Message) error {
// check message height
if m.Height != c.latestHeight+1 {
return ErrRoundChangeHeightMismatch
}
// check round in protocol
if m.Round < c.currentRound.RoundNumber {
return ErrRoundChangeRoundLower
}
// state data validation for non-null <roundchange>
if m.State != nil {
if !c.stateValidate(m.State) {
return ErrRoundChangeStateValidation
}
}
return nil
}
// verifyLockMessage verifies proofs from <lock> messages,
// a lock message must contain at least 2t+1 individual <roundchange>
// messages on B'
func (c *Consensus) verifyLockMessage(m *Message, signed *SignedProto) error {
// check message height
if m.Height != c.latestHeight+1 {
return ErrLockHeightMismatch
}
// check round in protocol
if m.Round < c.currentRound.RoundNumber {
return ErrLockRoundLower
}
// a <lock> message from leader MUST include data along with the message
if m.State == nil {
return ErrLockEmptyState
}
// state data validation
if !c.stateValidate(m.State) {
return ErrLockStateValidation
}
// make sure this message has been signed by the leader
leaderKey := c.roundLeader(m.Round)
if c.pubKeyToIdentity(signed.PublicKey(c.curve)) != leaderKey {
return ErrLockNotSignedByLeader
}
// validate proofs enclosed in the message one by one
rcs := make(map[Identity]State)
for _, proof := range m.Proof {
// first we need to verify the signature,and identity of this proof
mProof, err := c.verifyMessage(proof)
if err != nil {
if err == ErrMessageUnknownParticipant {
return ErrLockProofUnknownParticipant
}
return err
}
// then we need to check the message type
if mProof.Type != MessageType_RoundChange {
return ErrLockProofTypeMismatch
}
// and we also need to check the height & round field,
// all <roundchange> messages must be in the same round as the lock message
if mProof.Height != m.Height {
return ErrLockProofHeightMismatch
}
if mProof.Round != m.Round {
return ErrLockProofRoundMismatch
}
// state data validation in proofs
if mProof.State != nil {
if !c.stateValidate(mProof.State) {
return ErrLockProofStateValidation
}
}
// use map to guarantee we will only accept at most 1 message from one
// individual participant
rcs[c.pubKeyToIdentity(proof.PublicKey(c.curve))] = mProof.State
}
// count individual proofs to B', which has already guaranteed to be the maximal one.
var numValidateProofs int
mHash := c.stateHash(m.State)
for _, v := range rcs {
if c.stateHash(v) == mHash { // B'
numValidateProofs++
}
}
// check if valid proofs count is less that 2*t+1
if numValidateProofs < 2*c.t()+1 {
return ErrLockProofInsufficient
}
return nil
}
// verifyLockReleaseMessage will verify LockRelease field in a <lock-release> messages,
// returns the embedded <lock> message if valid
func (c *Consensus) verifyLockReleaseMessage(signed *SignedProto) (*Message, error) {
// not in lock release status, omit this message
if c.currentRound.Stage != stageLockRelease {
return nil, ErrLockReleaseStatus
}
// verify and decode the embedded lock message
lockmsg, err := c.verifyMessage(signed)
if err != nil {
return nil, err
}
// recursively verify proofs in lock message
err = c.verifyLockMessage(lockmsg, signed)
if err != nil {
return nil, err
}
return lockmsg, nil
}
// verifySelectMessage verifies proofs from <select> message,
// <select> message MUST contain at least 2t+1 individual messages, but
// proofs from <select> message MUST NOT contain >= 2t+1 individual
// <roundchange> messages related to B' at the same time.
func (c *Consensus) verifySelectMessage(m *Message, signed *SignedProto) error {
// check message height
if m.Height != c.latestHeight+1 {
return ErrSelectHeightMismatch
}
// check round in protocol
if m.Round < c.currentRound.RoundNumber {
return ErrSelectRoundLower
}
// state data validation for non-null <select>
if m.State != nil {
if !c.stateValidate(m.State) {
return ErrSelectStateValidation
}
}
// make sure this message has been signed by the leader
leaderKey := c.roundLeader(m.Round)
if c.pubKeyToIdentity(signed.PublicKey(c.curve)) != leaderKey {
return ErrSelectNotSignedByLeader
}
rcs := make(map[Identity]State)
for _, proof := range m.Proof {
mProof, err := c.verifyMessage(proof)
if err != nil {
if err == ErrMessageUnknownParticipant {
return ErrSelectProofUnknownParticipant
}
return err
}
if mProof.Type != MessageType_RoundChange {
return ErrSelectProofTypeMismatch
}
if mProof.Height != m.Height {
return ErrSelectProofHeightMismatch
}
if mProof.Round != m.Round {
return ErrSelectProofRoundMismatch
}
// state data validation in proofs
if mProof.State != nil {
if !c.stateValidate(mProof.State) {
return ErrSelectProofStateValidation
}
}
// we also need to check the B'' selected by leader is the maximal one,
// if data has been proposed.
if mProof.State != nil && m.State != nil {
if c.stateCompare(m.State, mProof.State) < 0 {
return ErrSelectProofNotTheMaximal
}
}
// we also stores B'' == NULL for counting
rcs[c.pubKeyToIdentity(proof.PublicKey(c.curve))] = mProof.State
}
// check we have at least 2*t+1 proof
if len(rcs) < 2*c.t()+1 {
return ErrSelectProofInsufficient
}
// count maximum proofs with B' != NULL with identical data hash,
// to prevent leader cheating on select.
dataProposals := make(map[StateHash]int)
for _, data := range rcs {
if data != nil {
dataProposals[c.stateHash(data)]++
}
}
// if m.State == NULL, but there are non-NULL proofs,
// the leader may be cheating
if m.State == nil && len(dataProposals) > 0 {
return ErrSelectStateMismatch
}
// find the highest proposed B'(not NULL)
var maxProposed int
for _, count := range dataProposals {
if count > maxProposed {
maxProposed = count
}
}
// if these are more than 2*t+1 valid <roundchange> proofs to B',
// this also suggests that the leader may cheat.
if maxProposed >= 2*c.t()+1 {
return ErrSelectProofExceeded
}
return nil
}
// verifyCommitMessage will check if this message is acceptable to consensus
func (c *Consensus) verifyCommitMessage(m *Message) error {
// the leader has to be in COMMIT status to process this message
if c.currentRound.Stage != stageCommit {
return ErrCommitStatus
}
// a <commit> message from participants MUST includes data along with the message
if m.State == nil {
return ErrCommitEmptyState
}
// state data validation
if !c.stateValidate(m.State) {
return ErrCommitStateValidation
}
// check height
if m.Height != c.latestHeight+1 {
return ErrCommitHeightMismatch
}
// only accept commits to current round
if c.currentRound.RoundNumber != m.Round {
return ErrCommitRoundMismatch
}
// check state match
if c.stateHash(m.State) != c.currentRound.LockedStateHash {
return ErrCommitStateMismatch
}
return nil
}
// ValidateDecideMessage validates a <decide> message for non-participants,
// the consensus core must be correctly initialized to validate.
// the targetState is to compare the target state enclosed in decide message
func (c *Consensus) ValidateDecideMessage(bts []byte, targetState []byte) error {
signed, err := DecodeSignedMessage(bts)
if err != nil {
return err
}
return c.validateDecideMessage(signed, targetState)
}
// DecodeSignedMessage decodes a binary representation of signed consensus message.
func DecodeSignedMessage(bts []byte) (*SignedProto, error) {
signed := new(SignedProto)
err := proto.Unmarshal(bts, signed)
if err != nil {
return nil, err
}
return signed, nil
}
// DecodeMessage decodes a binary representation of consensus message.
func DecodeMessage(bts []byte) (*Message, error) {
msg := new(Message)
err := proto.Unmarshal(bts, msg)
if err != nil {
return nil, err
}
return msg, nil
}
// validateDecideMessage validates a decoded <decide> message for non-participants,
// the consensus core must be correctly initialized to validate.
func (c *Consensus) validateDecideMessage(signed *SignedProto, targetState []byte) error {
// check message version
if signed.Version != ProtocolVersion {
return ErrMessageVersion
}
// check message signature & qualifications
m, err := c.verifyMessage(signed)
if err != nil {
return err
}
// compare state
if !bytes.Equal(m.State, targetState) {
return ErrMismatchedTargetState
}
// verify decide message
if m.Type == MessageType_Decide {
err := c.verifyDecideMessage(m, signed)
if err != nil {
return err
}
return nil
}
return ErrMessageUnknownMessageType
}
// verifyDecideMessage verifies proofs from <decide> message, which MUST
// contain at least 2t+1 individual <commit> messages to B'.
func (c *Consensus) verifyDecideMessage(m *Message, signed *SignedProto) error {
// a <decide> message from leader MUST include data along with the message
if m.State == nil {
return ErrDecideEmptyState
}
// state data validation
if !c.stateValidate(m.State) {
return ErrDecideStateValidation
}
// check height
if m.Height <= c.latestHeight {
return ErrDecideHeightLower
}
// make sure this message has been signed by the leader
leaderKey := c.roundLeader(m.Round)
if c.pubKeyToIdentity(signed.PublicKey(c.curve)) != leaderKey {
return ErrDecideNotSignedByLeader
}
commits := make(map[Identity]State)
for _, proof := range m.Proof {
mProof, err := c.verifyMessage(proof)
if err != nil {
if err == ErrMessageUnknownParticipant {
return ErrDecideProofUnknownParticipant
}
return err
}
if mProof.Type != MessageType_Commit {
return ErrDecideProofTypeMismatch
}
if mProof.Height != m.Height {
return ErrDecideProofHeightMismatch
}
if mProof.Round != m.Round {
return ErrDecideProofRoundMismatch
}
if !c.stateValidate(mProof.State) {
return ErrDecideProofStateValidation
}
// state data validation in proofs
if mProof.State != nil {
if !c.stateValidate(mProof.State) {
return ErrSelectProofStateValidation
}
}
commits[c.pubKeyToIdentity(proof.PublicKey(c.curve))] = mProof.State
}
// count proofs to m.State
var numValidateProofs int
mHash := c.stateHash(m.State)
for _, v := range commits {
if c.stateHash(v) == mHash {
numValidateProofs++
}
}
// check to see if the message has at least 2*t+1 <commit> valid proofs,
// if not, the leader may cheat.
if numValidateProofs < 2*c.t()+1 {
return ErrDecideProofInsufficient
}
return nil
}
// broadcastRoundChange will broadcast <roundchange> messages on
// current round, taking the maximal B' from unconfirmed data.
func (c *Consensus) broadcastRoundChange() {
// if <roundchange> has sent in this round,
// then just ignore. But if we are in roundchanging state,
// we should send repeatedly, for boostrap process.
if c.currentRound.RoundChangeSent && c.currentRound.Stage != stageRoundChanging {
return
}
// first we need to check if there is any locked data,
// locked data must be sent if there is any.
data := c.maximalLocked()
if data == nil {
// if there's none locked data, we pick the maximum unconfirmed data to propose
data = c.maximalUnconfirmed()
// if still null, return
if data == nil {
return
}
}
var m Message
m.Type = MessageType_RoundChange
m.Height = c.latestHeight + 1
m.Round = c.currentRound.RoundNumber
m.State = data
c.broadcast(&m)
c.currentRound.RoundChangeSent = true
//log.Println("broadcast:<roundchange>")
}
// broadcastLock will broadcast <lock> messages on current round,
// the currentRound should have a chosen data in this round.
func (c *Consensus) broadcastLock() {
var m Message
m.Type = MessageType_Lock
m.Height = c.latestHeight + 1
m.Round = c.currentRound.RoundNumber
m.State = c.currentRound.LockedState
m.Proof = c.currentRound.SignedRoundChanges()
c.broadcast(&m)
//log.Println("broadcast:<lock>")
}
// broadcastLockRelease will broadcast <lock-release> messages,
func (c *Consensus) broadcastLockRelease(signed *SignedProto) {
var m Message
m.Type = MessageType_LockRelease
m.Height = c.latestHeight + 1
m.Round = c.currentRound.RoundNumber
m.LockRelease = signed
c.broadcast(&m)
//log.Println("broadcast:<lock-release>")
}
// broadcastSelect will broadcast a <select> message by the leader,
// from current round with <roundchange> proofs.
func (c *Consensus) broadcastSelect() {
var m Message
m.Type = MessageType_Select
m.Height = c.latestHeight + 1
m.Round = c.currentRound.RoundNumber
m.State = c.maximalUnconfirmed() // B' may be NULL
m.Proof = c.currentRound.SignedRoundChanges()
c.broadcast(&m)
//log.Println("broadcast:<select>", m.State)
}
// broadcastDecide will broadcast a <decide> message by the leader,
// from current round with <commit> proofs.
func (c *Consensus) broadcastDecide() *SignedProto {
var m Message
m.Type = MessageType_Decide
m.Height = c.latestHeight + 1
m.Round = c.currentRound.RoundNumber
m.State = c.currentRound.LockedState
m.Proof = c.currentRound.SignedCommits()
return c.broadcast(&m)
//log.Println("broadcast:<decide>")
}
// broadcastResync will broadcast a <resync> message by the leader,
// from current round with <roundchange> proofs.
func (c *Consensus) broadcastResync() {
if c.lastRoundChangeProof == nil {
return
}
var m Message
m.Type = MessageType_Resync
// we only care about <roundchange> messages in resync
m.Proof = c.lastRoundChangeProof
c.broadcast(&m)
//log.Println("broadcast:<resync>")
}