forked from casper-network/casper-node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzug.rs
More file actions
2774 lines (2600 loc) · 110 KB
/
zug.rs
File metadata and controls
2774 lines (2600 loc) · 110 KB
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
//! # The Zug consensus protocol.
//!
//! This protocol requires that at most _f_ out of _n > 3 f_ validators (by weight) are faulty. It
//! also assumes that there is an upper bound for the network delay: how long a message sent by a
//! correct validator can take before it is delivered.
//!
//! Under these conditions all correct nodes will reach agreement on a chain of _finalized_ blocks.
//!
//! A _quorum_ is a set of validators whose total weight is greater than _(n + f) / 2_. Thus any two
//! quorums always have a correct validator in common. Since _(n + f) / 2 < n - f_, the correct
//! validators constitute a quorum.
//!
//!
//! ## How it Works
//!
//! In every round the designated leader can sign a `Proposal` message to suggest a block. The
//! proposal also points to an earlier round in which the parent block was proposed.
//!
//! Each validator then signs an `Echo` message with the proposal's hash. Correct validators only
//! sign one `Echo` per round, so at most one proposal can get `Echo`s signed by a quorum. If there
//! is a quorum and some other conditions are met (see below), the proposal is _accepted_. The next
//! round's leader can now make a proposal that uses this one as a parent.
//!
//! Each validator that observes the proposal to be accepted in time signs a `Vote(true)` message.
//! If they time out waiting they sign `Vote(false)` instead. If a quorum signs `true`, the round is
//! _committed_ and the proposal and all its ancestors are finalized. If a quorum signs `false`, the
//! round is _skippable_: The next round's leader can now make a proposal with a parent from an
//! earlier round. Correct validators only sign either `true` or `false`, so a round can be either
//! committed or skippable but not both.
//!
//! If there is no accepted proposal all correct validators will eventually vote `false`, so the
//! round becomes skippable. This is what makes the protocol _live_: The next leader will eventually
//! be allowed to make a proposal, because either there is an accepted proposal that can be the
//! parent, or the round will eventually be skippable and an earlier round's proposal can be used as
//! a parent. If the timeout is long enough correct proposers' blocks will usually get finalized.
//!
//! For a proposal to be _accepted_, the parent proposal needs to also be accepted, and all rounds
//! between the parent and the current round must be skippable. This is what makes the protocol
//! _safe_: If two rounds are committed, their proposals must be ancestors of each other,
//! because they are not skippable. Thus no two conflicting blocks can become finalized.
//!
//! Of course there is also a first block: Whenever _all_ earlier rounds are skippable (in
//! particular in the first round) the leader may propose a block with no parent.
//!
//!
//! ## Syncing the State
//!
//! Every new signed message is optimistically sent directly to all peers. We want to guarantee that
//! it is eventually seen by all validators, even if they are not fully connected. This is
//! achieved via a pull-based randomized gossip mechanism:
//!
//! A `SyncRequest` message containing information about a random part of the local protocol state
//! is periodically sent to a random peer. The peer compares that to its local state, and responds
//! with all signed messages that it has and the other is missing.
pub(crate) mod config;
#[cfg(test)]
mod des_testing;
mod fault;
mod message;
mod params;
mod participation;
mod proposal;
mod round;
#[cfg(test)]
mod tests;
use std::{
any::Any,
cmp::Reverse,
collections::{btree_map, BTreeMap, HashMap, HashSet},
fmt::Debug,
iter,
path::PathBuf,
};
use datasize::DataSize;
use either::Either;
use itertools::Itertools;
use rand::{seq::IteratorRandom, Rng};
use tracing::{debug, error, event, info, trace, warn, Level};
use casper_types::{Chainspec, TimeDiff, Timestamp, U512};
use crate::{
components::consensus::{
config::Config,
consensus_protocol::{
BlockContext, ConsensusProtocol, FinalizedBlock, ProposedBlock, ProtocolOutcome,
ProtocolOutcomes, TerminalBlockData,
},
era_supervisor::SerializedMessage,
protocols,
traits::{ConsensusValueT, Context},
utils::{
wal::{ReadWal, WalEntry, WriteWal},
ValidatorIndex, ValidatorMap, Validators, Weight,
},
ActionId, LeaderSequence, TimerId,
},
types::NodeId,
utils, NodeRng,
};
use fault::Fault;
use message::{Content, SignedMessage, SyncResponse};
use params::Params;
use participation::{Participation, ParticipationStatus};
use proposal::{HashedProposal, Proposal};
use round::Round;
use serde::{Deserialize, Serialize};
pub(crate) use message::{Message, SyncRequest};
/// The timer for syncing with a random peer.
const TIMER_ID_SYNC_PEER: TimerId = TimerId(0);
/// The timer for calling `update`.
const TIMER_ID_UPDATE: TimerId = TimerId(1);
/// The timer for logging inactive validators.
const TIMER_ID_LOG_PARTICIPATION: TimerId = TimerId(2);
/// The maximum number of future rounds we instantiate if we get messages from rounds that we
/// haven't started yet.
const MAX_FUTURE_ROUNDS: u32 = 7200; // Don't drop messages in 2-hour eras with 1-second rounds.
/// Identifies a single [`Round`] in the protocol.
pub(crate) type RoundId = u32;
type ProposalsAwaitingParent = HashSet<(RoundId, NodeId)>;
type ProposalsAwaitingValidation<C> = HashSet<(RoundId, HashedProposal<C>, NodeId)>;
/// An entry in the Write-Ahead Log, storing a message we had added to our protocol state.
#[derive(Deserialize, Serialize, Debug, PartialEq)]
#[serde(bound(
serialize = "C::Hash: Serialize",
deserialize = "C::Hash: Deserialize<'de>",
))]
pub(crate) enum ZugWalEntry<C: Context> {
/// A signed echo or vote.
SignedMessage(SignedMessage<C>),
/// A proposal.
Proposal(Proposal<C>, RoundId),
/// Evidence of a validator double-signing.
Evidence(SignedMessage<C>, Content<C>, C::Signature),
}
impl<C: Context> WalEntry for ZugWalEntry<C> {}
/// Contains the portion of the state required for an active validator to participate in the
/// protocol.
#[derive(DataSize)]
pub(crate) struct ActiveValidator<C>
where
C: Context,
{
idx: ValidatorIndex,
secret: C::ValidatorSecret,
}
impl<C: Context> Debug for ActiveValidator<C> {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("ActiveValidator")
.field("idx", &self.idx)
.field("secret", &"<REDACTED>")
.finish()
}
}
struct FaultySender(NodeId);
/// Contains the state required for the protocol.
#[derive(Debug, DataSize)]
pub(crate) struct Zug<C>
where
C: Context,
{
/// Contains numerical parameters for the protocol
params: Params<C>,
/// The timeout for the current round's proposal, in milliseconds
proposal_timeout_millis: f64,
/// The validators in this instantiation of the protocol
validators: Validators<C::ValidatorId>,
/// If we are a validator ourselves, we must know which index we
/// are in the [`Validators`] and have a private key for consensus.
active_validator: Option<ActiveValidator<C>>,
/// When an era has already completed, sometimes we still need to keep
/// it around to provide evidence for equivocation in previous eras.
evidence_only: bool,
/// Proposals which have not yet had their parent accepted, by parent round ID.
proposals_waiting_for_parent:
HashMap<RoundId, HashMap<HashedProposal<C>, ProposalsAwaitingParent>>,
/// Incoming blocks we can't add yet because we are waiting for validation.
proposals_waiting_for_validation: HashMap<ProposedBlock<C>, ProposalsAwaitingValidation<C>>,
/// If we requested a new block from the block proposer component this contains the proposal's
/// round ID and the parent's round ID, if there is a parent.
pending_proposal: Option<(BlockContext<C>, RoundId, Option<RoundId>)>,
leader_sequence: LeaderSequence,
/// The [`Round`]s of this protocol which we've instantiated.
rounds: BTreeMap<RoundId, Round<C>>,
/// List of faulty validators and their type of fault.
faults: HashMap<ValidatorIndex, Fault<C>>,
/// The configuration for the protocol
config: config::Config,
/// This is a signed message for every validator we have received a signature from.
active: ValidatorMap<Option<SignedMessage<C>>>,
/// The lowest round ID of a block that could still be finalized in the future.
first_non_finalized_round_id: RoundId,
/// The lowest round that needs to be considered in `upgrade`.
maybe_dirty_round_id: Option<RoundId>,
/// The lowest non-skippable round without an accepted value.
current_round: RoundId,
/// The time when the current round started.
current_round_start: Timestamp,
/// Whether anything was recently added to the protocol state.
progress_detected: bool,
/// Whether or not the protocol is currently paused
paused: bool,
/// The next update we have set a timer for. This helps deduplicate redundant calls to
/// `update`.
next_scheduled_update: Timestamp,
/// The write-ahead log to prevent honest nodes from double-signing upon restart.
write_wal: Option<WriteWal<ZugWalEntry<C>>>,
/// A map of random IDs -> tipmestamp of when it has been created, allowing to
/// verify that a response has been asked for.
sent_sync_requests: registered_sync::RegisteredSync,
}
impl<C: Context + 'static> Zug<C> {
fn new_with_params(
validators: Validators<C::ValidatorId>,
params: Params<C>,
config: &config::Config,
prev_cp: Option<&dyn ConsensusProtocol<C>>,
seed: u64,
) -> Zug<C> {
let weights = protocols::common::validator_weights::<C>(&validators);
let active: ValidatorMap<_> = weights.iter().map(|_| None).collect();
// Use the estimate from the previous era as the proposal timeout. Start with one minimum
// timeout times the grace period factor: This is what we would settle on if proposals
// always got accepted exactly after one minimum timeout.
let proposal_timeout_millis = prev_cp
.and_then(|cp| cp.as_any().downcast_ref::<Zug<C>>())
.map(|zug| zug.proposal_timeout_millis)
.unwrap_or_else(|| {
config.proposal_timeout.millis() as f64
* (config.proposal_grace_period as f64 / 100.0 + 1.0)
});
let mut can_propose: ValidatorMap<bool> = weights.iter().map(|_| true).collect();
for vidx in validators.iter_cannot_propose_idx() {
can_propose[vidx] = false;
}
let faults: HashMap<_, _> = validators
.iter_banned_idx()
.map(|idx| (idx, Fault::Banned))
.collect();
let leader_sequence = LeaderSequence::new(seed, &weights, can_propose);
info!(
instance_id = %params.instance_id(),
era_start_time = %params.start_timestamp(),
%proposal_timeout_millis,
"initializing Zug instance",
);
Zug {
leader_sequence,
proposals_waiting_for_parent: HashMap::new(),
proposals_waiting_for_validation: HashMap::new(),
rounds: BTreeMap::new(),
first_non_finalized_round_id: 0,
maybe_dirty_round_id: None,
current_round: 0,
current_round_start: Timestamp::MAX,
evidence_only: false,
faults,
active,
config: config.clone(),
params,
proposal_timeout_millis,
validators,
active_validator: None,
pending_proposal: None,
progress_detected: false,
paused: false,
next_scheduled_update: Timestamp::MAX,
write_wal: None,
sent_sync_requests: Default::default(),
}
}
/// Creates a new [`Zug`] instance.
#[allow(clippy::too_many_arguments)]
fn new(
instance_id: C::InstanceId,
validator_stakes: BTreeMap<C::ValidatorId, U512>,
faulty: &HashSet<C::ValidatorId>,
inactive: &HashSet<C::ValidatorId>,
chainspec: &Chainspec,
config: &Config,
prev_cp: Option<&dyn ConsensusProtocol<C>>,
era_start_time: Timestamp,
seed: u64,
) -> Zug<C> {
let validators = protocols::common::validators::<C>(faulty, inactive, validator_stakes);
let core_config = &chainspec.core_config;
let params = Params::new(
instance_id,
core_config.minimum_block_time,
era_start_time,
core_config.minimum_era_height,
era_start_time.saturating_add(core_config.era_duration),
protocols::common::ftt::<C>(core_config.finality_threshold_fraction, &validators),
);
Zug::new_with_params(validators, params, &config.zug, prev_cp, seed)
}
/// Creates a new boxed [`Zug`] instance.
#[allow(clippy::too_many_arguments)]
pub(crate) fn new_boxed(
instance_id: C::InstanceId,
validator_stakes: BTreeMap<C::ValidatorId, U512>,
faulty: &HashSet<C::ValidatorId>,
inactive: &HashSet<C::ValidatorId>,
chainspec: &Chainspec,
config: &Config,
prev_cp: Option<&dyn ConsensusProtocol<C>>,
era_start_time: Timestamp,
seed: u64,
now: Timestamp,
wal_file: PathBuf,
) -> (Box<dyn ConsensusProtocol<C>>, ProtocolOutcomes<C>) {
let mut zug = Self::new(
instance_id,
validator_stakes,
faulty,
inactive,
chainspec,
config,
prev_cp,
era_start_time,
seed,
);
let outcomes = zug.open_wal(wal_file, now);
(Box::new(zug), outcomes)
}
/// Returns our validator index (if we are an active validator).
fn our_idx(&self) -> Option<u32> {
self.active_validator.as_ref().map(|av| av.idx.0)
}
/// Prints a log statement listing the inactive and faulty validators.
fn log_participation(&self) {
let mut inactive_w: u64 = 0;
let mut faulty_w: u64 = 0;
let total_w = self.validators.total_weight().0;
let mut inactive_validators = Vec::new();
let mut faulty_validators = Vec::new();
for (idx, v_id) in self.validators.enumerate_ids() {
if let Some(status) = ParticipationStatus::for_index(idx, self) {
match status {
ParticipationStatus::Equivocated
| ParticipationStatus::EquivocatedInOtherEra => {
faulty_w = faulty_w.saturating_add(self.validators.weight(idx).0);
faulty_validators.push((idx, v_id.clone(), status));
}
ParticipationStatus::Inactive | ParticipationStatus::LastSeenInRound(_) => {
inactive_w = inactive_w.saturating_add(self.validators.weight(idx).0);
inactive_validators.push((idx, v_id.clone(), status));
}
}
}
}
inactive_validators.sort_by_key(|(idx, _, status)| (Reverse(*status), *idx));
faulty_validators.sort_by_key(|(idx, _, status)| (Reverse(*status), *idx));
let inactive_w_100 = u128::from(inactive_w).saturating_mul(100);
let faulty_w_100 = u128::from(faulty_w).saturating_mul(100);
let participation = Participation::<C> {
instance_id: *self.instance_id(),
inactive_stake_percent: utils::div_round(inactive_w_100, u128::from(total_w)) as u8,
faulty_stake_percent: utils::div_round(faulty_w_100, u128::from(total_w)) as u8,
inactive_validators,
faulty_validators,
};
info!(
our_idx = self.our_idx(),
?participation,
"validator participation"
);
}
/// Returns whether the switch block has already been finalized.
fn finalized_switch_block(&self) -> bool {
if let Some(round_id) = self.first_non_finalized_round_id.checked_sub(1) {
self.accepted_switch_block(round_id) || self.accepted_dummy_proposal(round_id)
} else {
false
}
}
/// Returns whether a block was accepted that, if finalized, would be the last one.
fn accepted_switch_block(&self, round_id: RoundId) -> bool {
match self.round(round_id).and_then(Round::accepted_proposal) {
None => false,
Some((height, proposal)) => {
proposal.maybe_block().is_some() // not a dummy proposal
&& height.saturating_add(1) >= self.params.end_height() // reached era height
&& proposal.timestamp() >= self.params.end_timestamp() // minimum era duration
}
}
}
/// Returns whether a proposal without a block was accepted, i.e. whether some ancestor of the
/// accepted proposal is a switch block.
fn accepted_dummy_proposal(&self, round_id: RoundId) -> bool {
match self.round(round_id).and_then(Round::accepted_proposal) {
None => false,
Some((_, proposal)) => proposal.maybe_block().is_none(),
}
}
/// Returns whether the validator has already sent an `Echo` in this round.
fn has_echoed(&self, round_id: RoundId, validator_idx: ValidatorIndex) -> bool {
self.round(round_id)
.is_some_and(|round| round.has_echoed(validator_idx))
}
/// Returns whether the validator has already cast a `true` or `false` vote.
fn has_voted(&self, round_id: RoundId, validator_idx: ValidatorIndex) -> bool {
self.round(round_id)
.is_some_and(|round| round.has_voted(validator_idx))
}
/// Request the latest state from a random peer.
fn handle_sync_peer_timer(&mut self, now: Timestamp, rng: &mut NodeRng) -> ProtocolOutcomes<C> {
if self.evidence_only || self.finalized_switch_block() {
return vec![]; // Era has ended. No further progress is expected.
}
trace!(
our_idx = self.our_idx(),
instance_id = ?self.instance_id(),
"syncing with random peer",
);
// Inform a peer about our protocol state and schedule the next request.
let first_validator_idx = ValidatorIndex(rng.gen_range(0..self.validators.len() as u32));
let round_id = (self.first_non_finalized_round_id..=self.current_round)
.choose(rng)
.unwrap_or(self.current_round);
let payload = self.create_sync_request(rng, first_validator_idx, round_id);
let mut outcomes = vec![ProtocolOutcome::CreatedRequestToRandomValidator(
SerializedMessage::from_message(&payload),
)];
// Periodically sync the state with a random peer.
if let Some(interval) = self.config.sync_state_interval {
outcomes.push(ProtocolOutcome::ScheduleTimer(
now.saturating_add(interval),
TIMER_ID_SYNC_PEER,
));
}
outcomes
}
/// Prints a log message if the message is a proposal.
fn log_proposal(&self, proposal: &HashedProposal<C>, round_id: RoundId, msg: &str) {
let creator_index = self.leader(round_id);
let creator = if let Some(creator) = self.validators.id(creator_index) {
creator
} else {
error!(
our_idx = self.our_idx(),
?creator_index,
?round_id,
"{}: invalid creator",
msg
);
return;
};
info!(
our_idx = self.our_idx(),
hash = %proposal.hash(),
%creator,
creator_index = creator_index.0,
round_id,
timestamp = %proposal.timestamp(),
"{}", msg,
);
}
/// Creates a `SyncRequest` message to inform a peer about our view of the given round, so that
/// the peer can send us any data we are missing.
///
/// If there are more than 128 validators, the information only covers echoes and votes of
/// validators with index in `first_validator_idx..=(first_validator_idx + 127)`.
fn create_sync_request(
&mut self,
rng: &mut NodeRng,
first_validator_idx: ValidatorIndex,
round_id: RoundId,
) -> SyncRequest<C> {
let faulty = self.validator_bit_field(first_validator_idx, self.faults.keys().cloned());
let active = self.validator_bit_field(first_validator_idx, self.active.keys_some());
let round = match self.round(round_id) {
Some(round) => round,
None => {
return SyncRequest::new_empty_round(
round_id,
first_validator_idx,
faulty,
active,
*self.instance_id(),
self.sent_sync_requests.create_and_register_new_id(rng),
);
}
};
let true_votes =
self.validator_bit_field(first_validator_idx, round.votes(true).keys_some());
let false_votes =
self.validator_bit_field(first_validator_idx, round.votes(false).keys_some());
// We only request information about the proposal with the most echoes, by weight.
// TODO: If there's no quorum, should we prefer the one for which we have the leader's echo?
let proposal_hash = round.quorum_echoes().or_else(|| {
round
.echoes()
.iter()
.max_by_key(|(_, echo_map)| self.sum_weights(echo_map.keys()))
.map(|(hash, _)| *hash)
});
let has_proposal = round.proposal().map(HashedProposal::hash) == proposal_hash.as_ref();
let mut echoes = 0;
if let Some(echo_map) = proposal_hash.and_then(|hash| round.echoes().get(&hash)) {
echoes = self.validator_bit_field(first_validator_idx, echo_map.keys().cloned());
}
// We create a new ID that the responder will use to show it's allowed to do so:
let sync_id = self.sent_sync_requests.create_and_register_new_id(rng);
SyncRequest {
round_id,
proposal_hash,
has_proposal,
first_validator_idx,
echoes,
true_votes,
false_votes,
active,
faulty,
instance_id: *self.instance_id(),
sync_id,
}
}
/// Returns a bit field where each bit stands for a validator: the least significant one for
/// `first_idx` and the most significant one for `fist_idx + 127`, wrapping around at the total
/// number of validators. The bits of the validators in `index_iter` that fall into that
/// range are set to `1`, the others are `0`.
fn validator_bit_field(
&self,
ValidatorIndex(first_idx): ValidatorIndex,
index_iter: impl Iterator<Item = ValidatorIndex>,
) -> u128 {
let validator_count = self.validators.len() as u32;
if first_idx >= validator_count {
return 0;
}
let mut bit_field: u128 = 0;
for ValidatorIndex(v_idx) in index_iter {
// The validator's bit is v_idx - first_idx, but we wrap around.
let idx = match v_idx.overflowing_sub(first_idx) {
(idx, false) => idx,
// An underflow occurred. Add validator_count to wrap back around.
(idx, true) => idx.wrapping_add(validator_count),
};
if idx < u128::BITS {
bit_field |= 1_u128.wrapping_shl(idx); // Set bit number i to 1.
}
}
bit_field
}
/// Returns an iterator over all validator indexes whose bits in the `bit_field` are `1`, where
/// the least significant one stands for `first_idx` and the most significant one for
/// `first_idx + 127`, wrapping around.
fn iter_validator_bit_field(
&self,
ValidatorIndex(mut idx): ValidatorIndex,
mut bit_field: u128,
) -> impl Iterator<Item = ValidatorIndex> {
let validator_count = self.validators.len() as u32;
iter::from_fn(move || {
if bit_field == 0 || idx >= validator_count {
return None; // No remaining bits with value 1.
}
let zeros = bit_field.trailing_zeros();
// The index of the validator whose bit is 1. We shift the bits to the right so that the
// least significant bit now corresponds to this one, then we output the index and set
// the bit to 0.
bit_field = bit_field.wrapping_shr(zeros);
bit_field &= !1;
idx = match idx.overflowing_add(zeros) {
(i, false) => i,
// If an overflow occurs, go back via an underflow, so the value modulo
// validator_count is correct again.
(i, true) => i
.checked_rem(validator_count)?
.wrapping_sub(validator_count),
}
.checked_rem(validator_count)?;
Some(ValidatorIndex(idx))
})
}
/// Returns whether `v_idx` is covered by a validator index that starts at `first_idx`.
fn validator_bit_field_includes(
&self,
ValidatorIndex(first_idx): ValidatorIndex,
ValidatorIndex(v_idx): ValidatorIndex,
) -> bool {
let validator_count = self.validators.len() as u32;
if first_idx >= validator_count {
return false;
}
let high_bit = u128::BITS.saturating_sub(1);
// The overflow bit is the 33rd bit of the actual sum.
let (last_idx, last_idx_overflow) = first_idx.overflowing_add(high_bit);
if v_idx >= first_idx {
// v_idx is at least first_idx, so it's in the range unless it's higher than the last
// index, taking into account its 33rd bit.
last_idx_overflow || v_idx <= last_idx
} else {
// v_idx is less than first_idx. But if going from the first to the last index we wrap
// around, we might still arrive at v_idx:
let (v_idx2, v_idx2_overflow) = v_idx.overflowing_add(validator_count);
if v_idx2_overflow == last_idx_overflow {
v_idx2 <= last_idx
} else {
last_idx_overflow
}
}
}
/// Returns the leader in the specified round.
pub(crate) fn leader(&self, round_id: RoundId) -> ValidatorIndex {
if let Some(round) = self.round(round_id) {
return round.leader();
}
self.leader_sequence.leader(u64::from(round_id))
}
fn create_message(
&mut self,
round_id: RoundId,
content: Content<C>,
) -> Option<SignedMessage<C>> {
let (validator_idx, secret_key) = if let Some(active_validator) = &self.active_validator {
(active_validator.idx, &active_validator.secret)
} else {
return None;
};
if self.paused {
return None;
}
let already_signed = match &content {
Content::Echo(_) => self.has_echoed(round_id, validator_idx),
Content::Vote(_) => self.has_voted(round_id, validator_idx),
};
if already_signed {
return None;
}
let signed_msg = SignedMessage::sign_new(
round_id,
*self.instance_id(),
content,
validator_idx,
secret_key,
);
// We only return the new message if we are able to record it. If that fails we
// wouldn't know about our own message after a restart and risk double-signing.
if self.record_entry(&ZugWalEntry::SignedMessage(signed_msg.clone()))
&& self.add_content(signed_msg.clone())
{
Some(signed_msg)
} else {
debug!(
our_idx = self.our_idx(),
%round_id,
?content,
"couldn't record a signed message in the WAL or add it to the protocol state"
);
None
}
}
/// If we are an active validator and it would be safe for us to sign this message and we
/// haven't signed it before, we sign it, add it to our state and gossip it to the network.
///
/// Does not call `update`!
fn create_and_gossip_message(
&mut self,
round_id: RoundId,
content: Content<C>,
) -> ProtocolOutcomes<C> {
let maybe_signed_msg = self.create_message(round_id, content);
maybe_signed_msg
.into_iter()
.map(|signed_msg| {
let message = Message::Signed(signed_msg);
ProtocolOutcome::CreatedGossipMessage(SerializedMessage::from_message(&message))
})
.collect()
}
/// When we receive evidence for a fault, we must notify the rest of the network of this
/// evidence. Beyond that, we can remove all of the faulty validator's previous information
/// from the protocol state.
fn handle_fault(
&mut self,
signed_msg: SignedMessage<C>,
validator_id: C::ValidatorId,
content2: Content<C>,
signature2: C::Signature,
now: Timestamp,
) -> ProtocolOutcomes<C> {
self.record_entry(&ZugWalEntry::Evidence(
signed_msg.clone(),
content2,
signature2,
));
self.handle_fault_no_wal(signed_msg, validator_id, content2, signature2, now)
}
/// Internal to handle_fault, documentation from that applies
fn handle_fault_no_wal(
&mut self,
signed_msg: SignedMessage<C>,
validator_id: C::ValidatorId,
content2: Content<C>,
signature2: C::Signature,
now: Timestamp,
) -> ProtocolOutcomes<C> {
let validator_idx = signed_msg.validator_idx;
warn!(
our_idx = self.our_idx(),
?signed_msg,
?content2,
id = %validator_id,
"validator double-signed"
);
let fault = Fault::Direct(signed_msg, content2, signature2);
self.faults.insert(validator_idx, fault);
if Some(validator_idx) == self.active_validator.as_ref().map(|av| av.idx) {
error!(our_idx = validator_idx.0, "we are faulty; deactivating");
self.active_validator = None;
}
self.active[validator_idx] = None;
self.progress_detected = true;
let mut outcomes = vec![ProtocolOutcome::NewEvidence(validator_id)];
if self.faulty_weight() > self.params.ftt() {
outcomes.push(ProtocolOutcome::FttExceeded);
return outcomes;
}
// Remove all votes and echoes from the faulty validator: They count towards every quorum
// now so nobody has to store their messages.
for round in self.rounds.values_mut() {
round.remove_votes_and_echoes(validator_idx);
}
// Recompute quorums; if any new quorums are found, call `update`.
for round_id in
self.first_non_finalized_round_id..=self.rounds.keys().last().copied().unwrap_or(0)
{
if !self.rounds.contains_key(&round_id) {
continue;
}
if self.rounds[&round_id].quorum_echoes().is_none() {
let hashes = self.rounds[&round_id]
.echoes()
.keys()
.copied()
.collect_vec();
if hashes
.into_iter()
.any(|hash| self.check_new_echo_quorum(round_id, hash))
{
self.mark_dirty(round_id);
}
}
if self.check_new_vote_quorum(round_id, true)
|| self.check_new_vote_quorum(round_id, false)
{
self.mark_dirty(round_id);
}
}
debug!(round_id = ?self.current_round, "Calling update after handle_fault_no_wal");
outcomes.extend(self.update(now));
outcomes
}
/// When we receive a request to synchronize, we must take a careful diff of our state and the
/// state in the sync state to ensure we send them exactly what they need to get back up to
/// speed in the network.
fn handle_sync_request(
&self,
sync_request: SyncRequest<C>,
sender: NodeId,
) -> (ProtocolOutcomes<C>, Option<SerializedMessage>) {
let SyncRequest {
round_id,
mut proposal_hash,
mut has_proposal,
first_validator_idx,
mut echoes,
true_votes,
false_votes,
active,
faulty,
instance_id,
sync_id,
} = sync_request;
if first_validator_idx.0 >= self.validators.len() as u32 {
info!(
our_idx = self.our_idx(),
first_validator_idx = first_validator_idx.0,
%sender,
"invalid SyncRequest message"
);
return (vec![ProtocolOutcome::Disconnect(sender)], None);
}
// If we don't have that round we have no information the requester is missing.
let round = match self.round(round_id) {
Some(round) => round,
None => return (vec![], None),
};
// If the peer has no or a wrong proposal we assume they don't have any echoes for the
// correct one. We don't send them the right proposal, though: they might already have it.
if round.quorum_echoes() != proposal_hash && round.quorum_echoes().is_some() {
has_proposal = true;
echoes = 0;
proposal_hash = round.quorum_echoes();
}
// The bit field of validators we know to be faulty.
let our_faulty = self.validator_bit_field(first_validator_idx, self.faults.keys().cloned());
// The echo signatures and proposal/hash we will send in the response.
let mut proposal_or_hash = None;
let mut echo_sigs = BTreeMap::new();
// The bit field of validators we have echoes from in this round.
let mut our_echoes: u128 = 0;
if let Some(hash) = proposal_hash {
if let Some(echo_map) = round.echoes().get(&hash) {
// Send them echoes they are missing, but exclude faulty validators.
our_echoes =
self.validator_bit_field(first_validator_idx, echo_map.keys().cloned());
let missing_echoes = our_echoes & !(echoes | faulty | our_faulty);
for v_idx in self.iter_validator_bit_field(first_validator_idx, missing_echoes) {
echo_sigs.insert(v_idx, echo_map[&v_idx]);
}
if has_proposal {
proposal_or_hash = Some(Either::Right(hash));
} else {
// If they don't have the proposal make sure we include the leader's echo.
let leader_idx = round.leader();
if !self.validator_bit_field_includes(first_validator_idx, leader_idx) {
if let Some(signature) = echo_map.get(&leader_idx) {
echo_sigs.insert(leader_idx, *signature);
}
}
if let Some(proposal) = round.proposal() {
if *proposal.hash() == hash {
proposal_or_hash = Some(Either::Left(proposal.inner().clone()));
}
}
}
}
}
// Send them votes they are missing, but exclude faulty validators. If there already is a
// quorum omit the votes that go against the quorum, since they are irrelevant.
let our_true_votes: u128 = if round.quorum_votes() == Some(false) {
0
} else {
self.validator_bit_field(first_validator_idx, round.votes(true).keys_some())
};
let missing_true_votes = our_true_votes & !(true_votes | faulty | our_faulty);
let true_vote_sigs = self
.iter_validator_bit_field(first_validator_idx, missing_true_votes)
.map(|v_idx| (v_idx, round.votes(true)[v_idx].unwrap()))
.collect();
let our_false_votes: u128 = if round.quorum_votes() == Some(true) {
0
} else {
self.validator_bit_field(first_validator_idx, round.votes(false).keys_some())
};
let missing_false_votes = our_false_votes & !(false_votes | faulty | our_faulty);
let false_vote_sigs = self
.iter_validator_bit_field(first_validator_idx, missing_false_votes)
.map(|v_idx| (v_idx, round.votes(false)[v_idx].unwrap()))
.collect();
let mut outcomes = vec![];
// Add evidence for validators they don't know are faulty.
let missing_faulty = our_faulty & !faulty;
let mut evidence = vec![];
for v_idx in self.iter_validator_bit_field(first_validator_idx, missing_faulty) {
match &self.faults[&v_idx] {
Fault::Banned => {
info!(
our_idx = self.our_idx(),
validator_index = v_idx.0,
%sender,
"peer disagrees about banned validator; disconnecting"
);
return (vec![ProtocolOutcome::Disconnect(sender)], None);
}
Fault::Direct(signed_msg, content2, signature2) => {
evidence.push((signed_msg.clone(), *content2, *signature2));
}
Fault::Indirect => {
let vid = self.validators.id(v_idx).unwrap().clone();
outcomes.push(ProtocolOutcome::SendEvidence(sender, vid));
}
}
}
// Send any signed messages that prove a validator is not completely inactive. We only
// need to do this for validators that the requester doesn't know are active, and that
// we haven't already included any signature from in our votes, echoes or evidence.
let our_active = self.validator_bit_field(first_validator_idx, self.active.keys_some());
let missing_active =
our_active & !(active | our_echoes | our_true_votes | our_false_votes | our_faulty);
let signed_messages = self
.iter_validator_bit_field(first_validator_idx, missing_active)
.filter_map(|v_idx| self.active[v_idx].clone())
.collect();
// Send the serialized sync response to the requester
let sync_response = SyncResponse {
round_id,
proposal_or_hash,
echo_sigs,
true_vote_sigs,
false_vote_sigs,
signed_messages,
evidence,
instance_id,
sync_id,
};
(
outcomes,
Some(SerializedMessage::from_message(&Message::SyncResponse(
sync_response,
))),
)
}
/// The response containing the parts from the sender's protocol state that we were missing.
fn handle_sync_response(
&mut self,
sync_response: SyncResponse<C>,
sender: NodeId,
now: Timestamp,
) -> ProtocolOutcomes<C> {
let SyncResponse {
round_id,
proposal_or_hash,
echo_sigs,
true_vote_sigs,
false_vote_sigs,
signed_messages,
evidence,
instance_id,
sync_id,
} = sync_response;
// We have not asked for any sync response:
if self.sent_sync_requests.try_remove_id(sync_id).is_none() {
debug!(
?round_id,
?sync_id,
"Disconnecting from peer due to unwanted sync response"
);
return vec![ProtocolOutcome::Disconnect(sender)];
}
// `echo_sigs`, `true_vote_sigs` and `false_vote_sigs` ought not to have more items than the
// amount of validators. In such a case, the sender is malicious.
if echo_sigs
.len()
.max(true_vote_sigs.len())