-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathepoch.go
2127 lines (1787 loc) · 66.5 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"
"slices"
"sync"
"sync/atomic"
"time"
"go.uber.org/zap"
)
var ErrAlreadyStarted = errors.New("epoch already started")
const (
DefaultMaxRoundWindow = 10
DefaultMaxPendingBlocks = 20
DefaultMaxProposalWaitTime = 5 * time.Second
)
type EmptyVoteSet struct {
timedOut bool
votes map[string]*EmptyVote
emptyNotarization *EmptyNotarization
}
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
ReplicationEnabled bool
}
type Epoch struct {
EpochConfig
// Runtime
sched *oneTimeBlockScheduler
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
emptyVotes map[uint64]*EmptyVoteSet
futureMessages messagesFromNode
round uint64 // The current round we notarize
maxRoundWindow uint64
maxPendingBlocks int
monitor *Monitor
haltedError error
cancelWaitForBlockNotarization context.CancelFunc
replicationState *ReplicationState
}
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 e.haltedError != nil {
return e.haltedError
}
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.EmptyVoteMessage != nil:
return e.handleEmptyVoteMessage(msg.EmptyVoteMessage, from)
case msg.Notarization != nil:
return e.handleNotarizationMessage(msg.Notarization, from)
case msg.EmptyNotarization != nil:
return e.handleEmptyNotarizationMessage(msg.EmptyNotarization)
case msg.Finalization != nil:
return e.handleFinalizationMessage(msg.Finalization, from)
case msg.FinalizationCertificate != nil:
return e.handleFinalizationCertificateMessage(msg.FinalizationCertificate, from)
case msg.ReplicationResponse != nil:
return e.handleReplicationResponse(msg.ReplicationResponse, from)
case msg.ReplicationRequest != nil:
e.HandleReplicationRequest(msg.ReplicationRequest, from)
return nil
default:
e.Logger.Warn("Invalid message type", zap.Stringer("from", from))
return nil
}
}
func (e *Epoch) init() error {
e.sched = newOneTimeBlockScheduler(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.emptyVotes = make(map[uint64]*EmptyVoteSet)
e.maxPendingBlocks = DefaultMaxPendingBlocks
e.eligibleNodeIDs = make(map[string]struct{}, len(e.nodes))
e.futureMessages = make(messagesFromNode, len(e.nodes))
e.replicationState = NewReplicationState(e.Logger, e.Comm, e.ID, e.maxRoundWindow, e.ReplicationEnabled)
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
}
return e.setMetadataFromStorage()
}
func (e *Epoch) Start() error {
if e.canReceiveMessages.Load() {
return ErrAlreadyStarted
}
// Only init receiving messages once you have initialized the data structures required for it.
defer func() {
e.canReceiveMessages.Store(true)
}()
return e.restoreFromWal()
}
func (e *Epoch) restoreBlockRecord(r []byte) error {
block, err := BlockFromRecord(e.BlockDeserializer, r)
if err != nil {
return err
}
e.rounds[block.BlockHeader().Round] = NewRound(block)
e.Logger.Info("Block Proposal Recovered From WAL", zap.Uint64("Round", block.BlockHeader().Round))
return nil
}
func (e *Epoch) restoreNotarizationRecord(r []byte) error {
notarization, err := NotarizationFromRecord(r, e.QCDeserializer)
if err != nil {
return err
}
round, exists := e.rounds[notarization.Vote.Round]
if !exists {
return fmt.Errorf("could not find round %d, its proposal was probably not persisted earlier", notarization.Vote.Round)
}
round.notarization = ¬arization
e.Logger.Info("Notarization Recovered From WAL", zap.Uint64("Round", notarization.Vote.Round))
return nil
}
func (e *Epoch) restoreEmptyNotarizationRecord(r []byte) error {
emptyNotarization, err := EmptyNotarizationFromRecord(r, e.QCDeserializer)
if err != nil {
return err
}
emptyVotes := e.getOrCreateEmptyVoteSetForRound(emptyNotarization.Vote.Round)
emptyVotes.emptyNotarization = &emptyNotarization
return nil
}
func (e *Epoch) restoreEmptyVoteRecord(r []byte) error {
vote, err := ParseEmptyVoteRecord(r)
if err != nil {
return err
}
emptyVotes := e.getOrCreateEmptyVoteSetForRound(vote.Round)
emptyVotes.timedOut = true
signature, err := vote.Sign(e.Signer)
if err != nil {
return err
}
emptyVote := &EmptyVote{
Signature: Signature{
Signer: e.ID,
Value: signature,
},
Vote: vote,
}
emptyVotes.votes[string(e.ID)] = emptyVote
return nil
}
func (e *Epoch) restoreFinalizationRecord(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")
}
e.Logger.Info("Finalization Certificate Recovered From WAL", zap.Uint64("Round", fCert.Finalization.Round))
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.EmptyVoteRecordType:
ev, err := ParseEmptyVoteRecord(lastRecord)
if err != nil {
return err
}
round, exists := e.emptyVotes[ev.Round]
if ! exists {
return fmt.Errorf("round %d not found for empty vote", ev.Round)
}
emptyVote, exists := round.votes[string(e.ID)]
if ! exists {
return fmt.Errorf("could not find my own vote for round %d", ev.Round)
}
lastMessage := Message{EmptyVoteMessage: emptyVote}
e.Comm.Broadcast(&lastMessage)
return nil
case record.EmptyNotarizationRecordType:
emptyNotarization, err := EmptyNotarizationFromRecord(lastRecord, e.QCDeserializer)
if err != nil {
return err
}
lastMessage := Message{EmptyNotarization: &emptyNotarization}
e.Comm.Broadcast(&lastMessage)
return e.startRound()
case record.FinalizationRecordType:
fCert, err := FinalizationCertificateFromRecord(lastRecord, e.QCDeserializer)
if err != nil {
return err
}
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))
return e.startRound()
default:
return fmt.Errorf("unknown record type (%d)", recordType)
}
}
func (e *Epoch) setMetadataFromStorage() error {
// load from storage if no notarization records
block, _, err := RetrieveLastIndexFromStorage(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 or empty block 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
}
if notarization.Vote.Round >= e.round {
e.round = notarization.Vote.Round + 1
e.Epoch = notarization.Vote.BlockHeader.Epoch
}
return nil
}
if recordType == record.EmptyNotarizationRecordType {
emptyNotarization, err := EmptyNotarizationFromRecord(records[i], e.QCDeserializer)
if err != nil {
return err
}
if emptyNotarization.Vote.Round >= e.round {
e.round = emptyNotarization.Vote.Round + 1
e.Epoch = emptyNotarization.Vote.Epoch
}
return nil
}
}
return nil
}
// restoreFromWal initializes an epoch from the write ahead log.
func (e *Epoch) restoreFromWal() 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.restoreBlockRecord(r)
case record.NotarizationRecordType:
err = e.restoreNotarizationRecord(r)
case record.FinalizationRecordType:
err = e.restoreFinalizationRecord(r)
case record.EmptyNotarizationRecordType:
err = e.restoreEmptyNotarizationRecord(r)
case record.EmptyVoteRecordType:
err = e.restoreEmptyVoteRecord(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 := RetrieveLastIndexFromStorage(e.Storage)
if err != nil {
return err
}
e.lastBlock = block
return nil
}
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), zap.Uint64("seq", message.Finalization.Seq))
nextSeqToCommit := e.Storage.Height()
// Ignore finalization certificates for sequences we have already committed
if nextSeqToCommit > message.Finalization.Seq {
return nil
}
valid := IsFinalizationCertificateValid(message, e.quorumSize, e.Logger)
if !valid {
e.Logger.Debug("Received an invalid finalization certificate",
zap.Int("round", int(message.Finalization.Round)),
zap.Stringer("NodeID", from))
return nil
}
round, exists := e.rounds[message.Finalization.Round]
if !exists {
e.handleFinalizationCertificateForPendingOrFutureRound(message, message.Finalization.Round, nextSeqToCommit)
return nil
}
if round.fCert != nil {
e.Logger.Debug("Received finalization for an already finalized round", zap.Uint64("round", message.Finalization.Round))
return nil
}
round.fCert = message
return e.persistFinalizationCertificate(*message)
}
func (e *Epoch) handleFinalizationCertificateForPendingOrFutureRound(message *FinalizationCertificate, round uint64, nextSeqToCommit uint64) {
if round == e.round {
// delay collecting future finalization certificate if we are verifying the proposal for that round
// and the fCert is for the current round
for _, msgs := range e.futureMessages {
msgForRound, exists := msgs[round]
if exists && msgForRound.proposal != nil {
msgForRound.finalizationCertificate = message
return
}
}
}
// TODO: delay requesting future fCerts and blocks, since blocks could be in transit
e.Logger.Debug("Received finalization certificate for a future round", zap.Uint64("round", round))
e.replicationState.collectFutureFinalizationCertificates(message, e.round, nextSeqToCommit)
}
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.isWithinMaxRoundWindow(finalization.Round) {
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) storeFutureNotarization(message *Notarization, from NodeID, round uint64) {
msgsForRound, exists := e.futureMessages[string(from)][round]
if !exists {
msgsForRound = &messagesForRound{}
e.futureMessages[string(from)][round] = msgsForRound
}
msgsForRound.notarization = message
}
func (e *Epoch) handleEmptyVoteMessage(message *EmptyVote, from NodeID) error {
vote := message.Vote
e.Logger.Verbo("Received empty vote message",
zap.Stringer("from", from), zap.Uint64("round", vote.Round))
// Only process point to point empty votes.
// A node will never need to forward to us someone else's vote.
if !from.Equals(message.Signature.Signer) {
e.Logger.Debug("Received an empty vote signed by a different party than sent it",
zap.Stringer("signer", message.Signature.Signer), zap.Stringer("sender", from))
return nil
}
if e.round > vote.Round {
e.Logger.Debug("Got vote from a past round",
zap.Uint64("round", vote.Round), zap.Uint64("my round", e.round), zap.Stringer("from", from))
return nil
}
// TODO: This empty vote may correspond to a future round, so... let future me implement it!
if e.round < vote.Round { //TODO: only handle it if it's within the max round window (&& vote.Round-e.round < e.maxRoundWindow)
e.Logger.Debug("Got empty vote from a future round",
zap.Uint64("round", vote.Round), zap.Uint64("my round", e.round), zap.Stringer("from", from))
//TODO: e.storeFutureEmptyVote(message, from, vote.Round)
return nil
}
// Else, this is an empty vote for current round
e.Logger.Debug("Received an empty vote for the current round",
zap.Uint64("round", vote.Round), zap.Stringer("from", from))
signature := message.Signature
if err := vote.Verify(signature.Value, e.Verifier, signature.Signer); err != nil {
e.Logger.Debug("ToBeSignedEmptyVote verification failed", zap.Stringer("NodeID", signature.Signer), zap.Error(err))
return nil
}
round := vote.Round
emptyVotes := e.getOrCreateEmptyVoteSetForRound(round)
emptyVotes.votes[string(from)] = message
return e.maybeAssembleEmptyNotarization()
}
func (e *Epoch) getOrCreateEmptyVoteSetForRound(round uint64) *EmptyVoteSet {
emptyVotes, exists := e.emptyVotes[round]
if !exists {
emptyVotes = &EmptyVoteSet{votes: make(map[string]*EmptyVote)}
e.emptyVotes[round] = emptyVotes
}
return emptyVotes
}
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), zap.Stringer("digest", vote.Digest))
// 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 !e.isVoteValid(vote) {
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.isWithinMaxRoundWindow(vote.Round) {
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
}
// 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) haveWeAlreadyTimedOutOnThisRound(round uint64) bool {
emptyVotes, exists := e.emptyVotes[round]
return exists && emptyVotes.timedOut
}
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) deleteFutureNotarization(from NodeID, round uint64) {
msgsForRound, exists := e.futureMessages[string(from)][round]
if !exists {
return
}
msgsForRound.notarization = 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 e.isRoundTooFarAhead(vote.Round) {
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 {
e.Logger.Debug("Received enough finalizations to finalize a block", zap.Uint64("round", fCert.Finalization.Round))
// 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 {
e.indexFinalizationCertificates(fCert.Finalization.Round)
} 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))
// we receive a finalization certificate for a future round
e.Logger.Debug("Received a finalization certificate for a future sequence", zap.Uint64("seq", fCert.Finalization.Seq), zap.Uint64("nextSeqToCommit", nextSeqToCommit))
e.replicationState.collectFutureFinalizationCertificates(&fCert, e.round, nextSeqToCommit)
}
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) indexFinalizationCertificates(startRound uint64) {
r := startRound
round, exists := e.rounds[r]
if !exists {
e.Logger.Debug("Round not found", zap.Uint64("round", r))
return
}
if round.fCert.Finalization.Seq != e.Storage.Height() {
e.Logger.Debug("Finalization certificate does not correspond to the next sequence to commit",
zap.Uint64("seq", round.fCert.Finalization.Seq), zap.Uint64("height", e.Storage.Height()))
return
}
for exists && round.fCert != nil {
fCert := *round.fCert
block := round.block
e.indexFinalizationCertificate(block, fCert)
// 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]
}
}
func (e *Epoch) indexFinalizationCertificate(block Block, fCert FinalizationCertificate) {
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)
}
func (e *Epoch) maybeAssembleEmptyNotarization() error {
emptyVotes, exists := e.emptyVotes[e.round]
// This should never happen, but done for sanity
if !exists {
return fmt.Errorf("could not find empty vote set for round %d", e.round)
}
// Check if we found a quorum of votes for the same metadata
quorumSize := e.quorumSize
popularEmptyVote, signatures, found := findMostPopularEmptyVote(emptyVotes.votes, quorumSize)
if !found {
e.Logger.Debug("Could not find empty vote with a quorum or more votes", zap.Uint64("round", e.round))
return nil
}
qc, err := e.SignatureAggregator.Aggregate(signatures)
if err != nil {
e.Logger.Error("Could not aggregate empty votes signatures", zap.Error(err), zap.Uint64("round", e.round))
return nil
}
emptyNotarization := &EmptyNotarization{QC: qc, Vote: popularEmptyVote}
// Persist the empty notarization and also broadcast it to everyone
return e.persistEmptyNotarization(emptyNotarization, true)
}
func findMostPopularEmptyVote(votes map[string]*EmptyVote, quorumSize int) (ToBeSignedEmptyVote, []Signature, bool) {
votesByBytes := make(map[string][]*EmptyVote)
for _, vote := range votes {
key := string(vote.Vote.Bytes())
votesByBytes[key] = append(votesByBytes[key], vote)
}
var popularEmptyVotes []*EmptyVote
for _, votes := range votesByBytes {
if len(votes) >= quorumSize {
popularEmptyVotes = votes
break
}
}
if len(popularEmptyVotes) == 0 {
return ToBeSignedEmptyVote{}, nil, false
}
sigs := make([]Signature, 0, len(popularEmptyVotes))
for _, vote := range popularEmptyVotes {
sigs = append(sigs, vote.Signature)
}
return popularEmptyVotes[0].Vote, sigs, true
}
func (e *Epoch) persistEmptyNotarization(emptyNotarization *EmptyNotarization, shouldBroadcast bool) error {
emptyNotarizationRecord := NewEmptyNotarizationRecord(emptyNotarization)
if err := e.WAL.Append(emptyNotarizationRecord); err != nil {
e.Logger.Error("Failed to append empty block record to WAL", zap.Error(err))
return err
}
e.Logger.Debug("Persisted empty block to WAL",
zap.Int("size", len(emptyNotarizationRecord)),
zap.Uint64("round", emptyNotarization.Vote.Round))
delete(e.emptyVotes, e.round)
if shouldBroadcast {
notarizationMessage := &Message{EmptyNotarization: emptyNotarization}
e.Comm.Broadcast(notarizationMessage)
e.Logger.Debug("Broadcast empty notarization",
zap.Uint64("round", emptyNotarization.Vote.Round))
}