/
ibft.go
1297 lines (1069 loc) · 30.6 KB
/
ibft.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 core
import (
"context"
"errors"
"math"
"sync"
"time"
"github.com/shibinuclassic2024/shibc-bft/messages"
"github.com/shibinuclassic2024/shibc-bft/messages/proto"
"github.com/armon/go-metrics"
)
// Logger represents the logger behaviour
type Logger interface {
Info(msg string, args ...any)
Debug(msg string, args ...any)
Error(msg string, args ...any)
}
// Messages represents the message managing behaviour
type Messages interface {
// Messages modifiers //
AddMessage(message *proto.Message)
PruneByHeight(height uint64)
SignalEvent(messageType proto.MessageType, view *proto.View)
// Messages fetchers //
GetValidMessages(
view *proto.View,
messageType proto.MessageType,
isValid func(*proto.Message) bool,
) []*proto.Message
GetExtendedRCC(
height uint64,
isValidMessage func(message *proto.Message) bool,
isValidRCC func(round uint64, msgs []*proto.Message) bool,
) []*proto.Message
GetMostRoundChangeMessages(minRound, height uint64) []*proto.Message
// Messages subscription handlers //
Subscribe(details messages.SubscriptionDetails) *messages.Subscription
Unsubscribe(id messages.SubscriptionID)
}
const (
round0Timeout = 10 * time.Second
roundFactorBase = float64(2)
)
var (
errTimeoutExpired = errors.New("round timeout expired")
)
// IBFT represents a single instance of the IBFT state machine
type IBFT struct {
// log is the logger instance
log Logger
// state is the current IBFT node state
state *state
// messages is the message storage layer
messages Messages
// backend is the reference to the
// Backend implementation
backend Backend
// transport is the reference to the
// Transport implementation
transport Transport
// roundDone is the channel used for signalizing
// consensus finalization upon a certain sequence
roundDone chan struct{}
// roundExpired is the channel used for signalizing
// round changing events
roundExpired chan struct{}
// newProposal is the channel used for signalizing
// when new proposals for a view greater than the current
// one arrive
newProposal chan newProposalEvent
// roundCertificate is the channel used for signalizing
// when a valid RCC for a greater round than the current
// one is present
roundCertificate chan uint64
// User configured additional timeout for each round of consensus
additionalTimeout time.Duration
// baseRoundTimeout is the base round timeout for each round of consensus
baseRoundTimeout time.Duration
// wg is a simple barrier used for synchronizing
// state modification routines
wg sync.WaitGroup
// validatorManager keeps quorumSize and voting power information
validatorManager *ValidatorManager
}
// NewIBFT creates a new instance of the IBFT consensus protocol
func NewIBFT(
log Logger,
backend Backend,
transport Transport,
) *IBFT {
return &IBFT{
log: log,
backend: backend,
transport: transport,
messages: messages.NewMessages(),
roundDone: make(chan struct{}),
roundExpired: make(chan struct{}),
newProposal: make(chan newProposalEvent),
roundCertificate: make(chan uint64),
state: &state{
view: &proto.View{
Height: 0,
Round: 0,
},
seals: make([]*messages.CommittedSeal, 0),
roundStarted: false,
name: newRound,
},
baseRoundTimeout: round0Timeout,
validatorManager: NewValidatorManager(backend, log),
}
}
// SetMeasurementTime function set duration to gauge
func SetMeasurementTime(prefix string, startTime time.Time) {
metrics.SetGauge([]string{"go-ibft", prefix, "duration"}, float32(time.Since(startTime).Seconds()))
}
// startRoundTimer starts the exponential round timer, based on the
// passed in round number
func (i *IBFT) startRoundTimer(ctx context.Context, round uint64) {
defer i.wg.Done()
startTime := time.Now()
roundTimeout := getRoundTimeout(i.baseRoundTimeout, i.additionalTimeout, round)
// Create a new timer instance
timer := time.NewTimer(roundTimeout)
select {
case <-ctx.Done():
SetMeasurementTime("round", startTime)
// Stop signal received, stop the timer
timer.Stop()
case <-timer.C:
// Timer expired, alert the round change channel to move
// to the next round
i.signalRoundExpired(ctx)
}
}
// signalRoundExpired notifies the sequence routine (RunSequence) that it
// should move to a new round. The quit channel is used to abort this call
// if another routine has already signaled a round change request.
func (i *IBFT) signalRoundExpired(ctx context.Context) {
select {
case i.roundExpired <- struct{}{}:
case <-ctx.Done():
}
}
// signalRoundDone notifies the sequence routine (RunSequence) that the
// consensus sequence is finished
func (i *IBFT) signalRoundDone(ctx context.Context) {
select {
case i.roundDone <- struct{}{}:
case <-ctx.Done():
}
}
// signalNewRCC notifies the sequence routine (RunSequence) that
// a valid Round Change Certificate for a higher round appeared
func (i *IBFT) signalNewRCC(ctx context.Context, round uint64) {
select {
case i.roundCertificate <- round:
case <-ctx.Done():
}
}
type newProposalEvent struct {
proposalMessage *proto.Message
round uint64
}
// signalNewProposal notifies the sequence routine (RunSequence) that
// a valid proposal for a higher round appeared
func (i *IBFT) signalNewProposal(ctx context.Context, event newProposalEvent) {
select {
case i.newProposal <- event:
case <-ctx.Done():
}
}
// watchForFutureProposal listens for new proposal messages
// that are intended for higher rounds
func (i *IBFT) watchForFutureProposal(ctx context.Context) {
var (
view = i.state.getView()
height = view.Height
nextRound = view.Round + 1
sub = i.subscribe(
messages.SubscriptionDetails{
MessageType: proto.MessageType_PREPREPARE,
View: &proto.View{
Height: height,
Round: nextRound,
},
HasMinRound: true,
})
)
defer func() {
i.messages.Unsubscribe(sub.ID)
i.wg.Done()
}()
for {
select {
case <-ctx.Done():
return
case round := <-sub.SubCh:
proposal := i.handlePrePrepare(&proto.View{Height: height, Round: round})
if proposal == nil {
continue
}
// Extract the proposal
i.signalNewProposal(
ctx,
newProposalEvent{proposal, round},
)
return
}
}
}
// watchForRoundChangeCertificates is a routine that waits
// for future valid Round Change Certificates that could
// trigger a round hop
func (i *IBFT) watchForRoundChangeCertificates(ctx context.Context) {
defer i.wg.Done()
var (
view = i.state.getView()
height = view.Height
round = view.Round
sub = i.subscribe(messages.SubscriptionDetails{
MessageType: proto.MessageType_ROUND_CHANGE,
View: &proto.View{
Height: height,
Round: round + 1, // only for higher rounds
},
HasMinRound: true,
})
)
defer i.messages.Unsubscribe(sub.ID)
for {
select {
case <-ctx.Done():
return
case <-sub.SubCh:
rcc := i.handleRoundChangeMessage(
&proto.View{
Height: height,
Round: round,
},
)
if rcc == nil {
continue
}
newRound := rcc.RoundChangeMessages[0].View.Round
// we received a valid RCC for a higher round
i.signalNewRCC(ctx, newRound)
return
}
}
}
// RunSequence runs the IBFT sequence for the specified height
func (i *IBFT) RunSequence(ctx context.Context, h uint64) {
startTime := time.Now()
// Set the starting state data
i.state.reset(h)
if err := i.validatorManager.Init(h); err != nil {
i.log.Error("failed to run sequence - validator manager init", "height", h, "error", err)
return
}
// Prune messages for older heights
i.messages.PruneByHeight(h)
i.log.Info("sequence started", "height", h)
defer i.log.Info("sequence done", "height", h)
defer SetMeasurementTime("sequence", startTime)
for {
view := i.state.getView()
i.log.Info("round started", "round", view.Round)
currentRound := view.Round
ctxRound, cancelRound := context.WithCancel(ctx)
i.wg.Add(4)
// Start the round timer worker
go i.startRoundTimer(ctxRound, currentRound)
// Jump round on proposals from higher rounds
go i.watchForFutureProposal(ctxRound)
// Jump round on certificates
go i.watchForRoundChangeCertificates(ctxRound)
// Start the state machine worker
go i.startRound(ctxRound)
teardown := func() {
cancelRound()
i.wg.Wait()
}
select {
case ev := <-i.newProposal:
teardown()
i.log.Info("received future proposal", "round", ev.round)
i.moveToNewRound(ev.round)
i.acceptProposal(ev.proposalMessage)
i.state.setRoundStarted(true)
i.sendPrepareMessage(view)
case round := <-i.roundCertificate:
teardown()
i.log.Info("received future RCC", "round", round)
i.moveToNewRound(round)
case <-i.roundExpired:
teardown()
i.log.Info("round timeout expired", "round", currentRound)
newRound := currentRound + 1
i.moveToNewRound(newRound)
i.sendRoundChangeMessage(h, newRound)
case <-i.roundDone:
// The consensus cycle for the block height is finished.
// Stop all running worker threads
teardown()
return
case <-ctxRound.Done():
teardown()
i.log.Debug("sequence cancelled")
return
}
}
}
// startRound runs the state machine loop for the current round
func (i *IBFT) startRound(ctx context.Context) {
// Register this worker thread with the barrier
defer i.wg.Done()
i.state.newRound()
var (
id = i.backend.ID()
view = i.state.getView()
)
// Check if any block needs to be proposed
if i.backend.IsProposer(id, view.Height, view.Round) {
i.log.Info("we are the proposer")
proposalMessage := i.buildProposal(ctx, view)
if proposalMessage == nil {
i.log.Error("unable to build proposal")
return
}
i.acceptProposal(proposalMessage)
i.log.Debug("block proposal accepted")
i.sendPreprepareMessage(proposalMessage)
i.log.Debug("pre-prepare message multicasted")
}
i.runStates(ctx)
}
// waitForRCC waits for valid RCC for the specified height and round
func (i *IBFT) waitForRCC(
ctx context.Context,
height,
round uint64,
) *proto.RoundChangeCertificate {
var (
view = &proto.View{
Height: height,
Round: round,
}
sub = i.subscribe(
messages.SubscriptionDetails{
MessageType: proto.MessageType_ROUND_CHANGE,
View: view,
},
)
)
defer i.messages.Unsubscribe(sub.ID)
for {
select {
case <-ctx.Done():
return nil
case <-sub.SubCh:
rcc := i.handleRoundChangeMessage(view)
if rcc == nil {
continue
}
return rcc
}
}
}
// handleRoundChangeMessage validates the round change message
// and constructs a RCC if possible
func (i *IBFT) handleRoundChangeMessage(view *proto.View) *proto.RoundChangeCertificate {
var (
height = view.Height
hasAcceptedProposal = i.state.getProposal() != nil
)
isValidMsgFn := func(msg *proto.Message) bool {
proposal := messages.ExtractLastPreparedProposal(msg)
certificate := messages.ExtractLatestPC(msg)
// Check if the prepared certificate is valid
if !i.validPC(certificate, msg.View.Round, height) {
return false
}
// Make sure the certificate matches the proposal
return i.proposalMatchesCertificate(proposal, certificate)
}
isValidRCCFn := func(round uint64, msgs []*proto.Message) bool {
// In case of that ROUND-CHANGE message's round match validator's round
// Accept such messages only if the validator has not accepted a proposal at the round
if round == view.Round && hasAcceptedProposal {
return false
}
return i.hasQuorumByMsgType(msgs, proto.MessageType_ROUND_CHANGE)
}
extendedRCC := i.messages.GetExtendedRCC(
height,
isValidMsgFn,
isValidRCCFn,
)
if extendedRCC == nil {
return nil
}
return &proto.RoundChangeCertificate{
RoundChangeMessages: extendedRCC,
}
}
// proposalMatchesCertificate checks a prepared certificate
// against a proposal
func (i *IBFT) proposalMatchesCertificate(
proposal *proto.Proposal,
certificate *proto.PreparedCertificate,
) bool {
// Both the certificate and proposal need to be set
if proposal == nil && certificate == nil {
return true
}
// If the proposal is set, the certificate also must be set
if certificate == nil {
return false
}
hashesInCertificate := make([][]byte, 0)
// collect hash from pre-prepare message
proposalHash := messages.ExtractProposalHash(certificate.ProposalMessage)
hashesInCertificate = append(hashesInCertificate, proposalHash)
// collect hashes from prepare messages
for _, msg := range certificate.PrepareMessages {
proposalHash := messages.ExtractPrepareHash(msg)
hashesInCertificate = append(hashesInCertificate, proposalHash)
}
// verify all hashes match the proposal
for _, hash := range hashesInCertificate {
if !i.backend.IsValidProposalHash(proposal, hash) {
return false
}
}
return true
}
// runStates is the main loop which performs state transitions
func (i *IBFT) runStates(ctx context.Context) {
var timeout error
for {
switch i.state.getStateName() {
case newRound:
timeout = i.runNewRound(ctx)
case prepare:
timeout = i.runPrepare(ctx)
case commit:
timeout = i.runCommit(ctx)
case fin:
i.runFin()
// Block inserted without any errors,
// sequence is complete
i.signalRoundDone(ctx)
return
}
if timeout != nil {
// Timeout received
return
}
}
}
// runNewRound runs the New Round IBFT state
func (i *IBFT) runNewRound(ctx context.Context) error {
i.log.Debug("enter: new round state")
defer i.log.Debug("exit: new round state")
var (
// Grab the current view
view = i.state.getView()
// Subscribe for PREPREPARE messages
sub = i.subscribe(
messages.SubscriptionDetails{
MessageType: proto.MessageType_PREPREPARE,
View: view,
},
)
)
// The subscription is not needed anymore after
// this state is done executing
defer i.messages.Unsubscribe(sub.ID)
for {
select {
case <-ctx.Done():
// Stop signal received, exit
return errTimeoutExpired
case <-sub.SubCh:
// SubscriptionDetails conditions have been met,
// grab the proposal messages
proposalMessage := i.handlePrePrepare(view)
if proposalMessage == nil {
continue
}
// Multicast the PREPARE message
i.state.setProposalMessage(proposalMessage)
i.sendPrepareMessage(view)
i.log.Debug("prepare message multicasted")
// Move to the prepare state
i.state.changeState(prepare)
return nil
}
}
}
// validateProposalCommon does common validations for each proposal, no
// matter the round
func (i *IBFT) validateProposalCommon(msg *proto.Message, view *proto.View) bool {
var (
height = view.Height
round = view.Round
proposal = messages.ExtractProposal(msg)
proposalHash = messages.ExtractProposalHash(msg)
)
// round matches
if proposal.Round != view.Round {
return false
}
// is proposer
if !i.backend.IsProposer(msg.From, height, round) {
return false
}
// hash matches keccak(proposal)
if !i.backend.IsValidProposalHash(proposal, proposalHash) {
return false
}
// is valid proposal
return i.backend.IsValidProposal(proposal.GetRawProposal())
}
// validateProposal0 validates the proposal for round 0
func (i *IBFT) validateProposal0(msg *proto.Message, view *proto.View) bool {
var (
height = view.Height
round = view.Round
)
// proposal must be for round 0
if msg.View.Round != 0 {
return false
}
// Make sure common proposal validations pass
if !i.validateProposalCommon(msg, view) {
return false
}
// Make sure the current node is not the proposer for this round
if i.backend.IsProposer(i.backend.ID(), height, round) {
return false
}
return true
}
// validateProposal validates a proposal for round > 0
func (i *IBFT) validateProposal(msg *proto.Message, view *proto.View) bool {
var (
height = view.Height
round = view.Round
proposal = messages.ExtractProposal(msg)
rcc = messages.ExtractRoundChangeCertificate(msg)
)
// Make sure common proposal validations pass
if !i.validateProposalCommon(msg, view) {
return false
}
// Make sure there is a certificate
if rcc == nil {
return false
}
// Make sure all the messages have the unique sender
if !messages.HasUniqueSenders(rcc.RoundChangeMessages) {
return false
}
// Make sure there are Quorum RCC
if !i.hasQuorumByMsgType(rcc.RoundChangeMessages, proto.MessageType_ROUND_CHANGE) {
return false
}
// Make sure the current node is not the proposer for this round
if i.backend.IsProposer(i.backend.ID(), height, round) {
return false
}
// Make sure all messages in the RCC are valid Round Change messages
for _, rc := range rcc.RoundChangeMessages {
// Make sure the message is a Round Change message
if rc.Type != proto.MessageType_ROUND_CHANGE {
return false
}
// Height of the message matches height of the proposal
if rc.View.Height != height {
return false
}
// Round of the message matches round of the proposal
if rc.View.Round != round {
return false
}
// Sender of RCC is valid
if !i.backend.IsValidValidator(rc) {
return false
}
}
// Extract possible rounds and their corresponding
// block hashes
type roundHashTuple struct {
round uint64
hash []byte
}
roundsAndPreparedBlockHashes := make([]roundHashTuple, 0)
for _, rcMessage := range rcc.RoundChangeMessages {
cert := messages.ExtractLatestPC(rcMessage)
// Check if there is a certificate, and if it's a valid PC
if cert != nil && i.validPC(cert, msg.View.Round, height) {
hash := messages.ExtractProposalHash(cert.ProposalMessage)
roundsAndPreparedBlockHashes = append(roundsAndPreparedBlockHashes, roundHashTuple{
round: cert.ProposalMessage.View.Round,
hash: hash,
})
}
}
if len(roundsAndPreparedBlockHashes) == 0 {
return true
}
// Find the max round
var (
maxRound uint64
expectedHash []byte
)
for _, tuple := range roundsAndPreparedBlockHashes {
if tuple.round >= maxRound {
maxRound = tuple.round
expectedHash = tuple.hash
}
}
// Make sure hash of (EB, maxR) matches expected hash
return i.backend.IsValidProposalHash(
&proto.Proposal{
RawProposal: proposal.RawProposal,
Round: maxRound,
},
expectedHash,
)
}
// handlePrePrepare parses the received proposal and performs
// a transition to PREPARE state, if the proposal is valid
func (i *IBFT) handlePrePrepare(view *proto.View) *proto.Message {
isValidPrePrepare := func(message *proto.Message) bool {
if view.Round == 0 {
// proposal must be for round 0
return i.validateProposal0(message, view)
}
return i.validateProposal(message, view)
}
msgs := i.messages.GetValidMessages(
view,
proto.MessageType_PREPREPARE,
isValidPrePrepare,
)
if len(msgs) < 1 {
return nil
}
return msgs[0]
}
// runPrepare runs the Prepare IBFT state
func (i *IBFT) runPrepare(ctx context.Context) error {
i.log.Debug("enter: prepare state")
defer i.log.Debug("exit: prepare state")
var (
// Grab the current view
view = i.state.getView()
// Subscribe to PREPARE messages
sub = i.subscribe(
messages.SubscriptionDetails{
MessageType: proto.MessageType_PREPARE,
View: view,
},
)
)
// The subscription is not needed anymore after
// this state is done executing
defer i.messages.Unsubscribe(sub.ID)
for {
select {
case <-ctx.Done():
// Stop signal received, exit
return errTimeoutExpired
case <-sub.SubCh:
if !i.handlePrepare(view) {
// quorum of valid prepare messages not received, retry
continue
}
return nil
}
}
}
// handlePrepare parses available prepare messages and performs
// a transition to COMMIT state, if quorum was reached
func (i *IBFT) handlePrepare(view *proto.View) bool {
isValidPrepare := func(message *proto.Message) bool {
// Verify that the proposal hash is valid
return i.backend.IsValidProposalHash(
i.state.getProposal(),
messages.ExtractPrepareHash(message),
)
}
prepareMessages := i.messages.GetValidMessages(
view,
proto.MessageType_PREPARE,
isValidPrepare,
)
if !i.hasQuorumByMsgType(prepareMessages, proto.MessageType_PREPARE) {
// quorum not reached, keep polling
return false
}
// Multicast the COMMIT message
i.sendCommitMessage(view)
i.log.Debug("commit message multicasted")
i.state.finalizePrepare(
&proto.PreparedCertificate{
ProposalMessage: i.state.getProposalMessage(),
PrepareMessages: prepareMessages,
},
i.state.getProposal(),
)
return true
}
// runCommit runs the Commit IBFT state
func (i *IBFT) runCommit(ctx context.Context) error {
i.log.Debug("enter: commit state")
defer i.log.Debug("exit: commit state")
var (
// Grab the current view
view = i.state.getView()
// Subscribe to COMMIT messages
sub = i.subscribe(
messages.SubscriptionDetails{
MessageType: proto.MessageType_COMMIT,
View: view,
},
)
)
// The subscription is not needed anymore after
// this state is done executing
defer i.messages.Unsubscribe(sub.ID)
for {
select {
case <-ctx.Done():
// Stop signal received, exit
return errTimeoutExpired
case <-sub.SubCh:
if !i.handleCommit(view) {
// quorum not reached, retry
continue
}
return nil
}
}
}
// handleCommit parses available commit messages and performs
// a transition to FIN state, if quorum was reached
func (i *IBFT) handleCommit(view *proto.View) bool {
isValidCommit := func(message *proto.Message) bool {
var (
proposalHash = messages.ExtractCommitHash(message)
committedSeal = messages.ExtractCommittedSeal(message)
)
// Verify that the proposal hash is valid
if !i.backend.IsValidProposalHash(i.state.getProposal(), proposalHash) {
return false
}
// Verify that the committed seal is valid
return i.backend.IsValidCommittedSeal(proposalHash, committedSeal)
}
commitMessages := i.messages.GetValidMessages(view, proto.MessageType_COMMIT, isValidCommit)
if !i.hasQuorumByMsgType(commitMessages, proto.MessageType_COMMIT) {
// quorum not reached, keep polling
return false
}
commitSeals, err := messages.ExtractCommittedSeals(commitMessages)
if err != nil {
// safe check
i.log.Error("failed to extract committed seals from commit messages: %+v", err)
return false
}
// Set the committed seals
i.state.setCommittedSeals(commitSeals)
// Move to the fin state
i.state.changeState(fin)
return true
}
// runFin runs the fin state (block insertion)
func (i *IBFT) runFin() {
i.log.Debug("enter: fin state")
defer i.log.Debug("exit: fin state")
// Insert the block to the node's underlying
// blockchain layer
i.backend.InsertProposal(
&proto.Proposal{
RawProposal: i.state.getRawDataFromProposal(),
Round: i.state.getRound(),
},
i.state.getCommittedSeals(),
)
// Remove stale messages
i.messages.PruneByHeight(i.state.getHeight())
}
// moveToNewRound moves the state to the new round
func (i *IBFT) moveToNewRound(round uint64) {
i.state.setView(&proto.View{
Height: i.state.getHeight(),
Round: round,
})
i.state.setRoundStarted(false)
i.state.setProposalMessage(nil)
i.state.changeState(newRound)
}
func (i *IBFT) buildProposal(ctx context.Context, view *proto.View) *proto.Message {
var (
height = view.Height
round = view.Round
)
if round == 0 {
rawProposal := i.backend.BuildProposal(
&proto.View{