-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathepoch.go
1523 lines (1274 loc) · 44.1 KB
/
epoch.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
// Copyright (C) 2019-2025, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package simplex
import (
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"simplex/record"
"sync"
"sync/atomic"
"time"
"go.uber.org/zap"
)
const (
defaultMaxRoundWindow = 10
defaultMaxPendingBlocks = 20
DefaultMaxProposalWaitTime = 5 * time.Second
)
type Round struct {
num uint64
block Block
votes map[string]*Vote // NodeID --> vote
notarization *Notarization
finalizations map[string]*Finalization // NodeID --> vote
fCert *FinalizationCertificate
}
func NewRound(block Block) *Round {
return &Round{
num: block.BlockHeader().Round,
block: block,
votes: make(map[string]*Vote),
finalizations: make(map[string]*Finalization),
}
}
type EpochConfig struct {
MaxProposalWait time.Duration
QCDeserializer QCDeserializer
Logger Logger
ID NodeID
Signer Signer
Verifier SignatureVerifier
BlockDeserializer BlockDeserializer
SignatureAggregator SignatureAggregator
Comm Communication
Storage Storage
WAL WriteAheadLog
BlockBuilder BlockBuilder
Epoch uint64
StartTime time.Time
}
type Epoch struct {
EpochConfig
// Runtime
sched *scheduler
lock sync.Mutex
lastBlock Block // latest block commited
canReceiveMessages atomic.Bool
finishCtx context.Context
finishFn context.CancelFunc
nodes []NodeID
eligibleNodeIDs map[string]struct{}
quorumSize int
rounds map[uint64]*Round
futureMessages messagesFromNode
round uint64 // The current round we notarize
maxRoundWindow uint64
maxPendingBlocks int
monitor *Monitor
cancelWaitForBlockNotarization context.CancelFunc
}
func NewEpoch(conf EpochConfig) (*Epoch, error) {
e := &Epoch{
EpochConfig: conf,
}
return e, e.init()
}
// AdvanceTime hints the engine that the given amount of time has passed.
func (e *Epoch) AdvanceTime(t time.Time) {
e.monitor.AdvanceTime(t)
}
// HandleMessage notifies the engine about a reception of a message.
func (e *Epoch) HandleMessage(msg *Message, from NodeID) error {
e.lock.Lock()
defer e.lock.Unlock()
// Guard against receiving messages before we are ready to handle them.
if !e.canReceiveMessages.Load() {
e.Logger.Warn("Cannot receive a message")
return nil
}
if from.Equals(e.ID) {
e.Logger.Warn("Received message from self")
return nil
}
// Guard against receiving messages from unknown nodes
_, known := e.eligibleNodeIDs[string(from)]
if !known {
e.Logger.Warn("Received message from an unknown node", zap.Stringer("nodeID", from))
return nil
}
switch {
case msg.BlockMessage != nil:
return e.handleBlockMessage(msg.BlockMessage, from)
case msg.VoteMessage != nil:
return e.handleVoteMessage(msg.VoteMessage, from)
case msg.Notarization != nil:
return e.handleNotarizationMessage(msg.Notarization, from)
case msg.Finalization != nil:
return e.handleFinalizationMessage(msg.Finalization, from)
case msg.FinalizationCertificate != nil:
return e.handleFinalizationCertificateMessage(msg.FinalizationCertificate, from)
default:
e.Logger.Warn("Invalid message type", zap.Stringer("from", from))
return nil
}
}
func (e *Epoch) init() error {
e.sched = NewScheduler(e.Logger)
e.monitor = NewMonitor(e.StartTime, e.Logger)
e.cancelWaitForBlockNotarization = func() {}
e.finishCtx, e.finishFn = context.WithCancel(context.Background())
e.nodes = e.Comm.ListNodes()
e.quorumSize = Quorum(len(e.nodes))
e.rounds = make(map[uint64]*Round)
e.maxRoundWindow = defaultMaxRoundWindow
e.maxPendingBlocks = defaultMaxPendingBlocks
e.eligibleNodeIDs = make(map[string]struct{}, len(e.nodes))
e.futureMessages = make(messagesFromNode, len(e.nodes))
for _, node := range e.nodes {
e.futureMessages[string(node)] = make(map[uint64]*messagesForRound)
}
for _, node := range e.nodes {
e.eligibleNodeIDs[string(node)] = struct{}{}
}
err := e.loadLastBlock()
if err != nil {
return err
}
err = e.setMetadataFromStorage()
if err != nil {
return err
}
e.loadLastRound()
return nil
}
func (e *Epoch) Start() error {
// Only init receiving messages once you have initialized the data structures required for it.
defer func() {
e.canReceiveMessages.Store(true)
}()
return e.syncFromWal()
}
func (e *Epoch) syncBlockRecord(r []byte) error {
block, err := BlockFromRecord(e.BlockDeserializer, r)
if err != nil {
return err
}
b := e.storeProposal(block)
if !b {
return fmt.Errorf("failed to store block from WAL")
}
e.Logger.Info("Block Proposal Recovered From WAL", zap.Uint64("Round", block.BlockHeader().Round), zap.Bool("stored", b))
return nil
}
func (e *Epoch) syncNotarizationRecord(r []byte) error {
notarization, err := NotarizationFromRecord(r, e.QCDeserializer)
if err != nil {
return err
}
return e.storeNotarization(notarization)
}
func (e *Epoch) syncFinalizationRecord(r []byte) error {
fCert, err := FinalizationCertificateFromRecord(r, e.QCDeserializer)
if err != nil {
return err
}
round, ok := e.rounds[fCert.Finalization.Round]
if !ok {
return fmt.Errorf("round not found for finalization certificate")
}
round.fCert = &fCert
return nil
}
// resumeFromWal resumes the epoch from the records of the write ahead log.
func (e *Epoch) resumeFromWal(records [][]byte) error {
if len(records) == 0 {
return e.startRound()
}
lastRecord := records[len(records)-1]
recordType := binary.BigEndian.Uint16(lastRecord)
// set the round from the last before syncing from records
err := e.setMetadataFromRecords(records)
if err != nil {
return err
}
switch recordType {
case record.BlockRecordType:
block, err := BlockFromRecord(e.BlockDeserializer, lastRecord)
if err != nil {
return err
}
if e.ID.Equals(LeaderForRound(e.nodes, block.BlockHeader().Round)) {
vote, err := e.voteOnBlock(block)
if err != nil {
return err
}
proposal := &Message{
BlockMessage: &BlockMessage{
Block: block,
Vote: vote,
},
}
// broadcast only if we are the leader
e.Comm.Broadcast(proposal)
return e.handleVoteMessage(&vote, e.ID)
}
// no need to do anything, just return and handle vote messages for this block
return nil
case record.NotarizationRecordType:
notarization, err := NotarizationFromRecord(lastRecord, e.QCDeserializer)
if err != nil {
return err
}
lastMessage := Message{Notarization: ¬arization}
e.Comm.Broadcast(&lastMessage)
return e.doNotarized(notarization.Vote.Round)
case record.FinalizationRecordType:
fCert, err := FinalizationCertificateFromRecord(lastRecord, e.QCDeserializer)
if err != nil {
return err
}
err = e.persistFinalizationCertificate(fCert)
if err != nil {
return err
}
return e.startRound()
default:
return errors.New("unknown record type")
}
}
func (e *Epoch) setMetadataFromStorage() error {
// load from storage if no notarization records
block, err := RetrieveLastBlockFromStorage(e.Storage)
if err != nil {
return err
}
if block == nil {
return nil
}
e.round = block.BlockHeader().Round + 1
e.Epoch = block.BlockHeader().Epoch
return nil
}
func (e *Epoch) setMetadataFromRecords(records [][]byte) error {
// iterate through records to find the last notarization record
for i := len(records) - 1; i >= 0; i-- {
recordType := binary.BigEndian.Uint16(records[i])
if recordType == record.NotarizationRecordType {
notarization, err := NotarizationFromRecord(records[i], e.QCDeserializer)
if err != nil {
return err
}
e.round = notarization.Vote.Round + 1
e.Epoch = notarization.Vote.BlockHeader.Epoch
return nil
}
}
return nil
}
// syncFromWal initializes an epoch from the write ahead log.
func (e *Epoch) syncFromWal() error {
records, err := e.WAL.ReadAll()
if err != nil {
return err
}
for _, r := range records {
if len(r) < 2 {
return fmt.Errorf("malformed record")
}
recordType := binary.BigEndian.Uint16(r)
switch recordType {
case record.BlockRecordType:
err = e.syncBlockRecord(r)
case record.NotarizationRecordType:
err = e.syncNotarizationRecord(r)
case record.FinalizationRecordType:
err = e.syncFinalizationRecord(r)
default:
e.Logger.Error("undefined record type", zap.Uint16("type", recordType))
return fmt.Errorf("undefined record type: %d", recordType)
}
if err != nil {
return err
}
}
if err != nil {
return err
}
return e.resumeFromWal(records)
}
// loadLastBlock initializes the epoch with the lastBlock retrieved from storage.
func (e *Epoch) loadLastBlock() error {
block, err := RetrieveLastBlockFromStorage(e.Storage)
if err != nil {
return err
}
e.lastBlock = block
return nil
}
func (e *Epoch) loadLastRound() {
// Put the last block we committed in the rounds map.
if e.lastBlock != nil {
round := NewRound(e.lastBlock)
e.rounds[round.num] = round
}
}
func (e *Epoch) Stop() {
e.finishFn()
}
func (e *Epoch) handleFinalizationCertificateMessage(message *FinalizationCertificate, from NodeID) error {
e.Logger.Verbo("Received finalization certificate message",
zap.Stringer("from", from), zap.Uint64("round", message.Finalization.Round))
round, exists := e.rounds[message.Finalization.Round]
if !exists {
e.Logger.Debug("Received finalization certificate for a non existent round", zap.Int("round", int(message.Finalization.Round)))
return nil
}
if round.fCert != nil {
e.Logger.Debug("Received finalization for an already finalized round", zap.Uint64("round", message.Finalization.Round))
return nil
}
valid, err := e.isFinalizationCertificateValid(message)
if err != nil {
return err
}
if !valid {
e.Logger.Debug("Received an invalid finalization certificate",
zap.Int("round", int(message.Finalization.Round)),
zap.Stringer("NodeID", from))
return nil
}
round.fCert = message
return e.persistFinalizationCertificate(*message)
}
func (e *Epoch) isFinalizationCertificateValid(fCert *FinalizationCertificate) (bool, error) {
valid, err := e.validateFinalizationQC(fCert)
if err != nil {
return false, err
}
if !valid {
return false, nil
}
return true, nil
}
func (e *Epoch) validateFinalizationQC(fCert *FinalizationCertificate) (bool, error) {
if fCert.QC == nil {
return false, nil
}
// Check enough signers signed the finalization certificate
if e.quorumSize > len(fCert.QC.Signers()) {
e.Logger.Debug("ToBeSignedFinalization certificate signed by insufficient nodes",
zap.Int("count", len(fCert.QC.Signers())),
zap.Int("Quorum", e.quorumSize))
return false, nil
}
signedTwice := e.hasSomeNodeSignedTwice(fCert.QC.Signers())
if signedTwice {
return false, nil
}
if err := fCert.Verify(); err != nil {
return false, nil
}
return true, nil
}
func (e *Epoch) handleFinalizationMessage(message *Finalization, from NodeID) error {
finalization := message.Finalization
e.Logger.Verbo("Received finalization message",
zap.Stringer("from", from), zap.Uint64("round", finalization.Round))
// Only process a point to point finalizations.
// This is needed to prevent a malicious node from sending us a finalization of a different node for a future round.
// Since we only verify the finalization when it's due time, this will effectively block us from saving the real finalization
// from the real node for a future round.
if !from.Equals(message.Signature.Signer) {
e.Logger.Debug("Received a finalization signed by a different party than sent it", zap.Stringer("signer", message.Signature.Signer), zap.Stringer("sender", from))
return nil
}
// Have we already finalized this round?
round, exists := e.rounds[finalization.Round]
// If we have not received the proposal yet, we won't have a Round object in e.rounds,
// yet we may receive the corresponding finalization.
// This may happen if we're asynchronously verifying the proposal at the moment.
if !exists && e.round == finalization.Round {
e.Logger.Debug("Received a finalization for the current round",
zap.Uint64("round", finalization.Round), zap.Stringer("from", from))
e.storeFutureFinalization(message, from, finalization.Round)
return nil
}
// This finalization may correspond to a proposal from a future round, or to the proposal of the current round
// which we are still verifying.
if e.round < finalization.Round && finalization.Round-e.round < e.maxRoundWindow {
e.Logger.Debug("Got finalization for a future round", zap.Uint64("round", finalization.Round), zap.Uint64("my round", e.round))
e.storeFutureFinalization(message, from, finalization.Round)
return nil
}
// Finalization for a future round that is too far in the future
if !exists {
e.Logger.Debug("Received finalization for an unknown round", zap.Uint64("ourRound", e.round), zap.Uint64("round", finalization.Round))
return nil
}
if round.fCert != nil {
e.Logger.Debug("Received finalization for an already finalized round", zap.Uint64("round", finalization.Round))
return nil
}
if !e.isFinalizationValid(message.Signature.Value, finalization, from) {
return nil
}
round.finalizations[string(from)] = message
e.deleteFutureFinalization(from, finalization.Round)
return e.maybeCollectFinalizationCertificate(round)
}
func (e *Epoch) storeFutureFinalization(message *Finalization, from NodeID, round uint64) {
msgsForRound, exists := e.futureMessages[string(from)][round]
if !exists {
msgsForRound = &messagesForRound{}
e.futureMessages[string(from)][round] = msgsForRound
}
msgsForRound.finalization = message
}
func (e *Epoch) handleVoteMessage(message *Vote, from NodeID) error {
vote := message.Vote
e.Logger.Verbo("Received vote message",
zap.Stringer("from", from), zap.Uint64("round", vote.Round))
// Only process point to point votes.
// This is needed to prevent a malicious node from sending us a vote of a different node for a future round.
// Since we only verify the vote when it's due time, this will effectively block us from saving the real vote
// from the real node for a future round.
if !from.Equals(message.Signature.Signer) {
e.Logger.Debug("Received a vote signed by a different party than sent it",
zap.Stringer("signer", message.Signature.Signer), zap.Stringer("sender", from),
zap.Stringer("digest", vote.Digest))
return nil
}
// If we have not received the proposal yet, we won't have a Round object in e.rounds,
// yet we may receive the corresponding vote.
// This may happen if we're asynchronously verifying the proposal at the moment.
if _, exists := e.rounds[vote.Round]; !exists && e.round == vote.Round {
e.Logger.Debug("Received a vote for the current round",
zap.Uint64("round", vote.Round), zap.Stringer("from", from))
e.storeFutureVote(message, from, vote.Round)
return nil
}
// This vote may correspond to a proposal from a future round, or to the proposal of the current round
// which we are still verifying.
if e.round < vote.Round && vote.Round-e.round < e.maxRoundWindow {
e.Logger.Debug("Got vote from a future round",
zap.Uint64("round", vote.Round), zap.Uint64("my round", e.round), zap.Stringer("from", from))
e.storeFutureVote(message, from, vote.Round)
return nil
}
round, exists := e.rounds[vote.Round]
if !exists {
e.Logger.Debug("Received a vote for a non existent round",
zap.Uint64("round", vote.Round), zap.Uint64("our round", e.round))
return nil
}
if round.notarization != nil {
e.Logger.Debug("Round already notarized", zap.Uint64("round", vote.Round))
return nil
}
if !e.isVoteValid(vote) {
return nil
}
// Only verify the vote if we haven't verified it in the past.
signature := message.Signature
if _, exists := round.votes[string(signature.Signer)]; !exists {
if err := vote.Verify(signature.Value, e.Verifier, signature.Signer); err != nil {
e.Logger.Debug("ToBeSignedVote verification failed", zap.Stringer("NodeID", signature.Signer), zap.Error(err))
return nil
}
}
e.rounds[vote.Round].votes[string(signature.Signer)] = message
e.deleteFutureVote(from, vote.Round)
return e.maybeCollectNotarization()
}
func (e *Epoch) storeFutureVote(message *Vote, from NodeID, round uint64) {
msgsForRound, exists := e.futureMessages[string(from)][round]
if !exists {
msgsForRound = &messagesForRound{}
e.futureMessages[string(from)][round] = msgsForRound
}
msgsForRound.vote = message
}
func (e *Epoch) deleteFutureVote(from NodeID, round uint64) {
msgsForRound, exists := e.futureMessages[string(from)][round]
if !exists {
return
}
msgsForRound.vote = nil
}
func (e *Epoch) deleteFutureProposal(from NodeID, round uint64) {
msgsForRound, exists := e.futureMessages[string(from)][round]
if !exists {
return
}
msgsForRound.proposal = nil
}
func (e *Epoch) deleteFutureFinalization(from NodeID, round uint64) {
msgsForRound, exists := e.futureMessages[string(from)][round]
if !exists {
return
}
msgsForRound.finalization = nil
}
func (e *Epoch) isFinalizationValid(signature []byte, finalization ToBeSignedFinalization, from NodeID) bool {
if err := finalization.Verify(signature, e.Verifier, from); err != nil {
e.Logger.Debug("Received a finalization with an invalid signature", zap.Uint64("round", finalization.Round), zap.Error(err))
return false
}
return true
}
func (e *Epoch) isVoteValid(vote ToBeSignedVote) bool {
// Ignore votes for previous rounds
if vote.Round < e.round {
return false
}
// Ignore votes for rounds too far ahead
if vote.Round-e.round > e.maxRoundWindow {
e.Logger.Debug("Received a vote for a too advanced round",
zap.Uint64("round", vote.Round), zap.Uint64("my round", e.round))
return false
}
return true
}
func (e *Epoch) maybeCollectFinalizationCertificate(round *Round) error {
finalizationCount := len(round.finalizations)
if finalizationCount < e.quorumSize {
e.Logger.Verbo("Counting finalizations", zap.Uint64("round", e.round), zap.Int("votes", finalizationCount))
return nil
}
return e.assembleFinalizationCertificate(round)
}
func (e *Epoch) assembleFinalizationCertificate(round *Round) error {
// Divide finalizations into sets that agree on the same metadata
finalizationsByMD := make(map[string][]*Finalization)
for _, vote := range round.finalizations {
key := string(vote.Finalization.Bytes())
finalizationsByMD[key] = append(finalizationsByMD[key], vote)
}
var finalizations []*Finalization
for _, finalizationsWithTheSameDigest := range finalizationsByMD {
if len(finalizationsWithTheSameDigest) >= e.quorumSize {
finalizations = finalizationsWithTheSameDigest
break
}
}
if len(finalizations) == 0 {
e.Logger.Debug("Could not find enough finalizations for the same metadata")
return nil
}
fCert, err := NewFinalizationCertificate(e.Logger, e.SignatureAggregator, finalizations)
if err != nil {
return err
}
round.fCert = &fCert
return e.persistFinalizationCertificate(fCert)
}
func (e *Epoch) progressRoundsDueToCommit(round uint64) {
e.Logger.Debug("Progressing rounds due to commit", zap.Uint64("round", round))
for e.round < round {
e.increaseRound()
}
}
func (e *Epoch) persistFinalizationCertificate(fCert FinalizationCertificate) error {
// Check to see if we should commit this finalization to the storage as part of a block commit,
// or otherwise write it to the WAL in order to commit it later.
startRound := e.round
nextSeqToCommit := e.Storage.Height()
if fCert.Finalization.Seq == nextSeqToCommit {
for {
r := fCert.Finalization.Round
block := e.rounds[r].block
e.Storage.Index(block, fCert)
e.Logger.Info("Committed block",
zap.Uint64("round", fCert.Finalization.Round),
zap.Uint64("sequence", fCert.Finalization.Seq),
zap.Stringer("digest", fCert.Finalization.BlockHeader.Digest))
e.lastBlock = block
// We have commited because we have collected a finalization certificate.
// However, we may have not witnessed a notarization.
// Regardless of that, we can safely progress to the round succeeding the finalization.
e.progressRoundsDueToCommit(fCert.Finalization.Round + 1)
// If the round we're committing is too far in the past, don't keep it in the rounds cache.
if fCert.Finalization.Round+e.maxRoundWindow < e.round {
delete(e.rounds, fCert.Finalization.Round)
}
// Clean up the future messages - Remove all messages we may have stored for the round
// the finalization is about.
for _, messagesFromNode := range e.futureMessages {
delete(messagesFromNode, fCert.Finalization.Round)
}
// Check if we can commit the next round
r++
round, exists := e.rounds[r]
if !exists {
break
}
if round.fCert == nil {
break
}
fCert = *round.fCert
}
} else {
recordBytes := NewQuorumRecord(fCert.QC.Bytes(), fCert.Finalization.Bytes(), record.FinalizationRecordType)
if err := e.WAL.Append(recordBytes); err != nil {
e.Logger.Error("Failed to append finalization certificate record to WAL", zap.Error(err))
return err
}
e.Logger.Debug("Persisted finalization certificate to WAL",
zap.Uint64("round", fCert.Finalization.Round),
zap.Uint64("height", nextSeqToCommit),
zap.Int("size", len(recordBytes)),
zap.Stringer("digest", fCert.Finalization.BlockHeader.Digest))
}
finalizationCertificate := &Message{FinalizationCertificate: &fCert}
e.Comm.Broadcast(finalizationCertificate)
e.Logger.Debug("Broadcast finalization certificate",
zap.Uint64("round", fCert.Finalization.Round),
zap.Stringer("digest", fCert.Finalization.BlockHeader.Digest))
// If we have progressed to a new round while we committed blocks,
// start the new round.
if startRound < e.round {
return e.startRound()
}
return nil
}
func (e *Epoch) maybeCollectNotarization() error {
votesForCurrentRound := e.rounds[e.round].votes
voteCount := len(votesForCurrentRound)
if voteCount < e.quorumSize {
from := make([]NodeID, 0, voteCount)
for _, vote := range votesForCurrentRound {
from = append(from, vote.Signature.Signer)
}
e.Logger.Verbo("Counting votes", zap.Uint64("round", e.round),
zap.Int("votes", voteCount), zap.String("from", fmt.Sprintf("%s", from)))
return nil
}
// TODO: store votes before receiving the block
block := e.rounds[e.round].block
expectedDigest := block.BlockHeader().Digest
// Ensure we have enough votes for the same digest
var voteCountForOurDigest int
for _, vote := range votesForCurrentRound {
if bytes.Equal(expectedDigest[:], vote.Vote.Digest[:]) {
voteCountForOurDigest++
}
}
if voteCountForOurDigest < e.quorumSize {
e.Logger.Verbo("Counting votes for the digest we received from the leader",
zap.Uint64("round", e.round), zap.Int("votes", voteCount))
return nil
}
notarization, err := NewNotarization(e.Logger, e.SignatureAggregator, votesForCurrentRound, block.BlockHeader())
if err != nil {
return err
}
return e.persistNotarization(notarization)
}
func (e *Epoch) persistNotarization(notarization Notarization) error {
record := NewQuorumRecord(notarization.QC.Bytes(), notarization.Vote.Bytes(), record.NotarizationRecordType)
if err := e.WAL.Append(record); err != nil {
e.Logger.Error("Failed to append notarization record to WAL", zap.Error(err))
return err
}
e.Logger.Debug("Persisted notarization to WAL",
zap.Int("size", len(record)),
zap.Uint64("round", notarization.Vote.Round),
zap.Stringer("digest", notarization.Vote.BlockHeader.Digest))
err := e.storeNotarization(notarization)
if err != nil {
return err
}
// Notify a block has been notarized, in case we were waiting for it.
e.cancelWaitForBlockNotarization()
notarizationMessage := &Message{Notarization: ¬arization}
e.Comm.Broadcast(notarizationMessage)
e.Logger.Debug("Broadcast notarization",
zap.Uint64("round", notarization.Vote.Round),
zap.Stringer("digest", notarization.Vote.BlockHeader.Digest))
e.increaseRound()
return errors.Join(e.doNotarized(notarization.Vote.Round), e.maybeLoadFutureMessages(e.round))
}
func (e *Epoch) handleNotarizationMessage(message *Notarization, from NodeID) error {
vote := message.Vote
e.Logger.Verbo("Received notarization message",
zap.Stringer("from", from), zap.Uint64("round", vote.Round))
// Ignore votes for previous rounds
if vote.Round < e.round {
e.Logger.Debug("Received a notarization for an earlier round", zap.Uint64("round", vote.Round))
return nil
}
// Ignore votes for rounds too far ahead
if vote.Round-e.round > e.maxRoundWindow {
e.Logger.Debug("Received a notarization for a too advanced round",
zap.Uint64("round", vote.Round), zap.Uint64("my round", e.round),
zap.Stringer("NodeID", from))
return nil
}
// Have we already notarized in this round?
round, exists := e.rounds[vote.Round]
if !exists {
e.Logger.Debug("Received a notarization for a non existent round",
zap.Stringer("NodeID", from))
return nil
}
if round.notarization != nil {
e.Logger.Debug("Received a notarization for an already notarized round",
zap.Stringer("NodeID", from))
return nil
}
if !e.isVoteValid(vote) {
e.Logger.Debug("Notarization contains invalid vote",
zap.Stringer("NodeID", from))
return nil
}
if err := message.Verify(); err != nil {
e.Logger.Debug("Notarization quorum certificate is invalid",
zap.Stringer("NodeID", from), zap.Error(err))
return nil
}
return e.persistNotarization(*message)
}
func (e *Epoch) hasSomeNodeSignedTwice(nodeIDs []NodeID) bool {
seen := make(map[string]struct{}, len(nodeIDs))
for _, nodeID := range nodeIDs {
if _, alreadySeen := seen[string(nodeID)]; alreadySeen {
e.Logger.Warn("Observed a signature originating at least twice from the same node")
return true
}
seen[string(nodeID)] = struct{}{}
}
return false
}
func (e *Epoch) handleBlockMessage(message *BlockMessage, from NodeID) error {
block := message.Block
if block == nil {
e.Logger.Debug("Got empty block in a BlockMessage")
return nil
}
e.Logger.Verbo("Received block message",
zap.Stringer("from", from), zap.Uint64("round", block.BlockHeader().Round))
pendingBlocks := e.sched.Size()
if pendingBlocks > e.maxPendingBlocks {
e.Logger.Warn("Too many blocks being verified to ingest another one", zap.Int("pendingBlocks", pendingBlocks))
return nil
}
vote := message.Vote
from = vote.Signature.Signer
md := block.BlockHeader()
e.Logger.Debug("Handling block message", zap.Stringer("digest", md.Digest), zap.Uint64("round", md.Round))
// Don't bother processing blocks from the past
if e.round > md.Round {
return nil
}
// The block is for a too high round, we shouldn't handle it as
// we have only so much memory.
if md.Round-e.round >= e.maxRoundWindow {
e.Logger.Debug("Received a block message for a too high round",
zap.Uint64("round", md.Round), zap.Uint64("our round", e.round))
return nil
}
// Check that the node is a leader for the round corresponding to the block.
if !LeaderForRound(e.nodes, md.Round).Equals(from) {
// The block is associated with a round in which the sender is not the leader,
// it should not be sending us any block at all.
e.Logger.Debug("Got block from a block proposer that is not the leader of the round", zap.Stringer("NodeID", from), zap.Uint64("round", md.Round))
return nil
}
// Check if we have verified this message in the past:
alreadyVerified := e.wasBlockAlreadyVerified(from, md)
if !alreadyVerified {
// Ensure the block was voted on by its block producer:
// 1) Verify block digest corresponds to the digest voted on
if !bytes.Equal(vote.Vote.Digest[:], md.Digest[:]) {
e.Logger.Debug("ToBeSignedVote digest mismatches block digest", zap.Stringer("voteDigest", vote.Vote.Digest),
zap.Stringer("blockDigest", md.Digest))
return nil
}
// 2) Verify the vote is properly signed
if err := vote.Vote.Verify(vote.Signature.Value, e.Verifier, vote.Signature.Signer); err != nil {
e.Logger.Debug("ToBeSignedVote verification failed", zap.Stringer("NodeID", vote.Signature.Signer), zap.Error(err))
return nil
}
}
// If this is a message from a more advanced round,
// only store it if it is up to `maxRoundWindow` ahead.
// TODO: test this
if e.round < md.Round && md.Round-e.round < e.maxRoundWindow {
e.Logger.Debug("Got block of a future round", zap.Uint64("round", md.Round), zap.Uint64("my round", e.round))
msgsForRound, exists := e.futureMessages[string(from)][md.Round]
if !exists {
msgsForRound = &messagesForRound{}
e.futureMessages[string(from)][md.Round] = msgsForRound
}
// Has this node already sent us a proposal?
// If so, it cannot send it again.
if msgsForRound.proposal != nil {
e.Logger.Debug("Already received a proposal from this node for the round",
zap.Stringer("NodeID", from), zap.Uint64("round", md.Round))
return nil
}
msgsForRound.proposal = message
return nil
}
if !e.verifyProposalIsPartOfOurChain(block) {
e.Logger.Debug("Got invalid block in a BlockMessage")
return nil
}
defer e.deleteFutureProposal(from, md.Round)
// Create a task that will verify the block in the future, after its predecessors have also been verified.
task := e.createBlockVerificationTask(block, from, vote)
// isBlockReadyToBeScheduled checks if the block is known to us either from some previous round,
// or from storage. If so, then we have verified it in the past, since only verified blocks are saved in memory.
canBeImmediatelyVerified := e.isBlockReadyToBeScheduled(md.Seq, md.Prev)
// Schedule the block to be verified once its direct predecessor have been verified,
// or if it can be verified immediately.
e.Logger.Debug("Scheduling block verification", zap.Uint64("round", md.Round))
e.sched.Schedule(task, md.Prev, canBeImmediatelyVerified)
return nil
}
func (e *Epoch) createBlockVerificationTask(block Block, from NodeID, vote Vote) func() Digest {
return func() Digest {
md := block.BlockHeader()
e.Logger.Debug("Block verification started", zap.Uint64("round", md.Round))
start := time.Now()
defer func() {
elapsed := time.Since(start)
e.Logger.Debug("Block verification ended", zap.Uint64("round", md.Round), zap.Duration("elapsed", elapsed))
}()
if err := block.Verify(); err != nil {
e.Logger.Debug("Failed verifying block", zap.Error(err))