-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathlib.rs
More file actions
1828 lines (1713 loc) · 72.2 KB
/
lib.rs
File metadata and controls
1828 lines (1713 loc) · 72.2 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
#[cfg(feature = "mocks")]
pub mod aggregation;
#[cfg(feature = "mocks")]
pub mod aggregation_certificate_mock;
pub mod bounds;
pub mod byzzfuzz;
pub mod disrupter;
pub mod id_mock;
pub mod invariants;
#[cfg(feature = "mocks")]
pub mod marshal;
pub mod network;
#[cfg(feature = "mocks")]
pub mod ordered_broadcast;
#[cfg(feature = "mocks")]
pub mod ordered_broadcast_certificate_mock;
pub mod simplex;
#[cfg(feature = "mocks")]
pub mod simplex_certificate_mock;
pub mod simplex_node;
pub mod strategy;
pub mod types;
pub mod utils;
use crate::{
disrupter::Disrupter,
network::ByzantineFirstReceiver,
simplex_node::NodeFuzzInput,
strategy::{AnyScope, FutureScope, SmallScope, Strategy, StrategyChoice},
utils::{apply_partition, link_peers, register, Action, Partition, SetPartition},
};
use arbitrary::Arbitrary;
use commonware_codec::{Decode, DecodeExt, Read};
use commonware_consensus::{
simplex::{
config,
elector::Config as ElectorConfig,
mocks::{application, relay, reporter, twins},
types::{Certificate, Vote},
Engine, Floor, ForwardingPolicy,
},
types::{Delta, Epoch, View},
Monitor, Viewable,
};
use commonware_cryptography::{
certificate::Scheme, sha256::Digest as Sha256Digest, PublicKey as CryptoPublicKey, Sha256,
};
use commonware_p2p::{
simulated::{Config as NetworkConfig, Link, Network, Oracle, SplitOrigin, SplitTarget},
Recipients,
};
use commonware_parallel::Sequential;
use commonware_resolver::p2p::mocks::{Message as ResolverMessage, Payload as ResolverPayload};
use commonware_runtime::{
buffer::paged::CacheRef, deterministic, Clock, IoBuf, Runner, Spawner, Supervisor as _,
};
use commonware_utils::{
channel::mpsc::{self, Receiver},
sequence::U64,
sync::Once,
FuzzRng, NZUsize, NZU16,
};
use futures::future::join_all;
#[cfg(feature = "mocks")]
pub use simplex::SimplexCertificateMock;
pub use simplex::{
SimplexBls12381MinPk, SimplexBls12381MinPkCustomRandom, SimplexBls12381MinSig,
SimplexBls12381MultisigMinPk, SimplexBls12381MultisigMinSig, SimplexEd25519,
SimplexEd25519CustomRoundRobin, SimplexId, SimplexSecp256r1,
};
use std::{
collections::HashMap,
fmt,
num::{NonZeroU16, NonZeroUsize},
panic,
sync::Arc,
time::Duration,
};
pub const EPOCH: u64 = 333;
const FUZZ_LOG_ENV: &str = "CONSENSUS_FUZZ_LOG";
const PAGE_SIZE: NonZeroU16 = NZU16!(1024);
const PAGE_CACHE_SIZE: NonZeroUsize = NZUsize!(10);
pub(crate) const FAULT_INJECTION_RATIO: u64 = 5;
const MIN_NUMBER_OF_FAULTS: u64 = 2;
const MIN_REQUIRED_CONTAINERS: u64 = 1;
const MAX_REQUIRED_CONTAINERS: u64 = 30;
/// Per-view honest-message drop rate range used by `Mode::FaultyMessaging`.
/// Bounded conservatively so finalization remains reachable across the run -
/// `FaultyMessaging` waits for finalization (`Partition::Connected` is enforced),
/// and unbounded loss would let pathological schedules hang the deterministic
/// runtime. Increase only if a complementary timeout is added to the wait loop.
pub(crate) const MIN_HONEST_MESSAGES_DROP_RATIO: u8 = 0;
pub(crate) const MAX_HONEST_MESSAGES_DROP_RATIO: u8 = 5;
pub(crate) const MAX_SLEEP_DURATION: Duration = Duration::from_secs(5);
const NAMESPACE: &[u8] = b"consensus_fuzz";
const MAX_RAW_BYTES: usize = 32_768;
/// Network configuration for fuzz testing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Configuration {
/// Total number of nodes.
pub n: u32,
/// Number of faulty (Byzantine) nodes.
pub faults: u32,
/// Number of correct (honest) nodes.
pub correct: u32,
}
impl Configuration {
pub const fn new(n: u32, faults: u32, correct: u32) -> Self {
Self { n, faults, correct }
}
/// Returns true if this configuration is valid:
/// number of faulty and correct nodes satisfy the protocol fault tolerance constraints.
/// A valid configuration is required for the protocol to make progress in periods of synchrony (liveness).
pub fn is_valid(&self) -> bool {
self.faults <= bounds::max_faults(self.n) && self.n == self.faults + self.correct
}
}
/// 4 nodes, 1 faulty, 3 correct (standard BFT config)
pub const N4F1C3: Configuration = Configuration::new(4, 1, 3);
/// 4 nodes, 3 faulty, 1 correct (adversarial majority, no liveness)
pub const N4F3C1: Configuration = Configuration::new(4, 3, 1);
/// 4 nodes, 0 faulty, 4 correct (all nodes are correct)
pub const N4F0C4: Configuration = Configuration::new(4, 0, 4);
async fn setup_degraded_network<P: CryptoPublicKey, E: Clock>(
oracle: &mut Oracle<P, E>,
participants: &[P],
) {
let Some(victim) = participants.last() else {
return;
};
let victim_idx = participants.len() - 1;
let degraded = Link {
latency: Duration::from_millis(50),
jitter: Duration::from_millis(50),
success_rate: 0.6,
};
for (peer_idx, peer) in participants.iter().enumerate() {
if peer_idx == victim_idx {
continue;
}
oracle.remove_link(victim.clone(), peer.clone()).await.ok();
oracle.remove_link(peer.clone(), victim.clone()).await.ok();
oracle
.add_link(victim.clone(), peer.clone(), degraded.clone())
.await
.unwrap();
oracle
.add_link(peer.clone(), victim.clone(), degraded.clone())
.await
.unwrap();
}
}
/// Per-iteration choice of `Application::certify` behavior.
///
/// `SingleCancel` and `SinglePending` apply their non-default certifier only
/// to the validator at `target_idx` so quorum certification is still reachable
/// when the selected validator already overlaps another modeled adversary.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CertifyChoice {
Always,
SingleCancel { target_idx: u8 },
SinglePending { target_idx: u8 },
}
impl CertifyChoice {
pub fn into_certifier(self, validator_idx: usize) -> application::Certifier<Sha256Digest> {
match self {
CertifyChoice::Always => application::Certifier::Always,
CertifyChoice::SingleCancel { target_idx } => {
if validator_idx == target_idx as usize {
application::Certifier::Cancel
} else {
application::Certifier::Always
}
}
CertifyChoice::SinglePending { target_idx } => {
if validator_idx == target_idx as usize {
application::Certifier::Pending
} else {
application::Certifier::Always
}
}
}
}
}
struct FuzzInputDebug<'a>(&'a FuzzInput);
impl fmt::Debug for FuzzInputDebug<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let input = self.0;
f.debug_struct("FuzzInput")
.field("raw_bytes_len", &input.raw_bytes.len())
.field("required_containers", &input.required_containers)
.field("degraded_network", &input.degraded_network)
.field("configuration", &input.configuration)
.field("partition", &input.partition)
.field("strategy", &input.strategy)
.field("messaging_faults", &input.messaging_faults)
.field("forwarding", &input.forwarding)
.field("certify", &input.certify)
.finish()
}
}
struct NodeFuzzInputDebug<'a>(&'a NodeFuzzInput);
impl fmt::Debug for NodeFuzzInputDebug<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let input = self.0;
f.debug_struct("NodeFuzzInput")
.field("raw_bytes_len", &input.raw_bytes.len())
.field("events", &input.events)
.field("forwarding", &input.forwarding)
.field("certify", &input.certify)
.finish()
}
}
fn print_fuzz_input(mode: Mode, input: &FuzzInput) {
if std::env::var_os(FUZZ_LOG_ENV).is_some() {
eprintln!(
"consensus fuzz configuration: mode={mode:?} input={:?}",
FuzzInputDebug(input)
);
}
}
fn print_node_fuzz_input(mode: simplex_node::NodeMode, input: &NodeFuzzInput) {
if std::env::var_os(FUZZ_LOG_ENV).is_some() {
eprintln!(
"consensus node fuzz configuration: mode={mode:?} input={:?}",
NodeFuzzInputDebug(input)
);
}
}
#[derive(Debug, Clone)]
pub struct FuzzInput {
pub raw_bytes: Vec<u8>,
pub required_containers: u64,
pub degraded_network: bool,
pub configuration: Configuration,
pub partition: Partition,
pub strategy: StrategyChoice,
/// Round-indexed schedule of honest-message drop rates, used only by
/// `Mode::FaultyMessaging`. Each entry `(view, rate)` activates an
/// `rate%` honest-message drop while the reference reporter is in `view`;
/// the rate reverts to 0 outside scheduled views.
pub messaging_faults: Vec<(View, u8)>,
/// Per-iteration forwarding policy threaded into every engine the harness
/// spawns. Sampling lets the fuzzer drive coverage of all three arms of
/// `batcher::forward_targets` instead of pinning to `Disabled`.
pub forwarding: ForwardingPolicy,
/// Per-iteration certify policy threaded into every honest validator
/// the harness spawns.
pub certify: CertifyChoice,
}
impl Arbitrary<'_> for FuzzInput {
fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
// Partition distribution:
// 30% fully Connected (no fault)
// 20% Static fault: uniform sample over the 14 non-trivial set
// partitions of {0,1,2,3} (Bell(4) - 1 = 14; the trivial single-block
// partition is excluded since it equals `Connected`)
// 50% Adaptive (round-indexed schedule, populated later)
let partition = match u.int_in_range(0..=99)? {
0..=29 => Partition::Connected,
30..=49 => {
// 14 non-trivial partitions live at N4[1..15].
let idx = u.int_in_range(1..=14)?;
Partition::Static(SetPartition::n4(idx))
}
_ => Partition::Adaptive(Vec::new()),
};
let configuration = match u.int_in_range(1..=100)? {
1..=95 => N4F1C3, // 95%
_ => N4F0C4, // 5%
};
// Bias degraded networking - 1%
let degraded_network = partition == Partition::Connected
&& configuration == N4F1C3
&& u.int_in_range(0..=99)? == 1;
let required_containers =
u.int_in_range(MIN_REQUIRED_CONTAINERS..=MAX_REQUIRED_CONTAINERS)?;
// SmallScope mutations with round-based injections - 80%,
// AnyScope mutations - 10%,
// FutureScope mutations with round-based injections - 10%
let fault_rounds_bound = u.int_in_range(1..=required_containers)?;
let min_fault_rounds = MIN_NUMBER_OF_FAULTS.min(fault_rounds_bound);
let max_fault_rounds = (fault_rounds_bound / FAULT_INJECTION_RATIO).max(min_fault_rounds);
let fault_rounds = u.int_in_range(min_fault_rounds..=max_fault_rounds)?;
let strategy = match u.int_in_range(0..=9)? {
0 => StrategyChoice::AnyScope,
1 => StrategyChoice::FutureScope {
fault_rounds,
fault_rounds_bound,
},
_ => StrategyChoice::SmallScope {
fault_rounds,
fault_rounds_bound,
},
};
// Forwarding policy distribution:
// 33% Disabled - matches prior fuzz behavior; covers the no-op path
// 33% SilentVoters - exercises `forward_targets` -> `missing_voters`
// 34% SilentLeader - exercises `forward_targets` -> leader-only branch
let forwarding = match u.int_in_range(0..=2)? {
0 => ForwardingPolicy::Disabled,
1 => ForwardingPolicy::SilentVoters,
_ => ForwardingPolicy::SilentLeader,
};
// Single-target certify variants are not sampled here because standard
// N4F1C3 modes have only three honest certifiers; disabling one drops
// below the quorum of three.
let certify = CertifyChoice::Always;
// Collect bytes for RNG
let remaining = u.len().min(MAX_RAW_BYTES);
let raw_bytes = u.bytes(remaining)?.to_vec();
// The messaging-fault schedule (for `Mode::FaultyMessaging`) is generated
// at runtime by `Strategy::messaging_faults` from the deterministic
// FuzzRng, mirroring the `Adaptive` partition path - keeps schedule
// density tied to the chosen byzantine strategy.
Ok(Self {
raw_bytes,
partition,
configuration,
degraded_network,
required_containers,
strategy,
messaging_faults: Vec::new(),
forwarding,
certify,
})
}
}
pub(crate) type PublicKeyOf<P> = <<P as simplex::Simplex>::Scheme as Scheme>::PublicKey;
type ReporterOf<P> = reporter::Reporter<
deterministic::Context,
<P as simplex::Simplex>::Scheme,
<P as simplex::Simplex>::Elector,
Sha256Digest,
>;
type ReporterEntry<P> = (PublicKeyOf<P>, ReporterOf<P>);
type NetworkChannels<P> = (
(
commonware_p2p::simulated::Sender<P, deterministic::Context>,
commonware_p2p::simulated::Receiver<P>,
),
(
commonware_p2p::simulated::Sender<P, deterministic::Context>,
commonware_p2p::simulated::Receiver<P>,
),
(
commonware_p2p::simulated::Sender<P, deterministic::Context>,
commonware_p2p::simulated::Receiver<P>,
),
);
/// Common setup for fuzz tests: network, participants, links.
pub(crate) async fn setup_network<P: simplex::Simplex>(
context: &mut deterministic::Context,
input: &FuzzInput,
) -> (
Oracle<PublicKeyOf<P>, deterministic::Context>,
Vec<PublicKeyOf<P>>,
Vec<P::Scheme>,
HashMap<PublicKeyOf<P>, NetworkChannels<PublicKeyOf<P>>>,
) {
let (participants, schemes) = P::setup(context, NAMESPACE, input.configuration.n);
let (network, mut oracle) = Network::new_with_peers(
context.child("network"),
NetworkConfig {
max_size: 1024 * 1024,
disconnect_on_block: false,
tracked_peer_sets: NZUsize!(1),
},
participants.clone(),
)
.await;
network.start();
let registrations = register(&mut oracle, &participants).await;
let link = Link {
latency: Duration::from_millis(10),
jitter: Duration::from_millis(1),
success_rate: 1.0,
};
link_peers(
&mut oracle,
&participants,
Action::Link(link),
input.partition.set_partition(),
)
.await;
if input.partition == Partition::Connected
&& input.configuration == N4F1C3
&& input.degraded_network
{
setup_degraded_network(&mut oracle, &participants).await;
}
(oracle, participants, schemes, registrations)
}
/// Start a Disrupter with the given strategy and network channels.
fn start_disrupter<P: simplex::Simplex>(
context: deterministic::Context,
scheme: P::Scheme,
strategy: &StrategyChoice,
required_containers: u64,
vote_network: (
impl commonware_p2p::Sender<PublicKey = PublicKeyOf<P>>,
impl commonware_p2p::Receiver<PublicKey = PublicKeyOf<P>>,
),
certificate_network: (
impl commonware_p2p::Sender<PublicKey = PublicKeyOf<P>>,
impl commonware_p2p::Receiver<PublicKey = PublicKeyOf<P>>,
),
resolver_network: (
impl commonware_p2p::Sender<PublicKey = PublicKeyOf<P>>,
impl commonware_p2p::Receiver<PublicKey = PublicKeyOf<P>>,
),
) {
match *strategy {
StrategyChoice::SmallScope {
fault_rounds,
fault_rounds_bound,
} => {
let disrupter = Disrupter::new(
context,
scheme,
SmallScope {
fault_rounds,
fault_rounds_bound,
},
required_containers,
);
disrupter.start(vote_network, certificate_network, resolver_network);
}
StrategyChoice::AnyScope => {
let disrupter = Disrupter::new(context, scheme, AnyScope, required_containers);
disrupter.start(vote_network, certificate_network, resolver_network);
}
StrategyChoice::FutureScope {
fault_rounds,
fault_rounds_bound,
} => {
let disrupter = Disrupter::new(
context,
scheme,
FutureScope {
fault_rounds,
fault_rounds_bound,
},
required_containers,
);
disrupter.start(vote_network, certificate_network, resolver_network);
}
}
}
/// Spawn a Disrupter for a Byzantine node.
fn spawn_disrupter<P: simplex::Simplex>(
context: deterministic::Context,
scheme: P::Scheme,
input: &FuzzInput,
channels: NetworkChannels<PublicKeyOf<P>>,
) {
let (vote_network, certificate_network, resolver_network) = channels;
start_disrupter::<P>(
context.child("disrupter"),
scheme,
&input.strategy,
input.required_containers,
vote_network,
certificate_network,
resolver_network,
);
}
/// Spawn an honest validator with application, reporter, and engine.
#[allow(clippy::too_many_arguments)]
pub(crate) fn spawn_honest_validator<
P,
EC,
PendingSender,
PendingReceiver,
RecoveredSender,
RecoveredReceiver,
ResolverSender,
ResolverReceiver,
>(
context: deterministic::Context,
oracle: &Oracle<PublicKeyOf<P>, deterministic::Context>,
participants: &[PublicKeyOf<P>],
scheme: P::Scheme,
validator: PublicKeyOf<P>,
elector: EC,
relay: Arc<relay::Relay<Sha256Digest, PublicKeyOf<P>>>,
leader_timeout: Duration,
certification_timeout: Duration,
forwarding: ForwardingPolicy,
pending: (PendingSender, PendingReceiver),
recovered: (RecoveredSender, RecoveredReceiver),
resolver: (ResolverSender, ResolverReceiver),
certify: CertifyChoice,
) -> reporter::Reporter<deterministic::Context, P::Scheme, EC, Sha256Digest>
where
P: simplex::Simplex,
EC: ElectorConfig<P::Scheme> + Clone + Send + 'static,
PendingSender: commonware_p2p::Sender<PublicKey = PublicKeyOf<P>>,
PendingReceiver: commonware_p2p::Receiver<PublicKey = PublicKeyOf<P>>,
RecoveredSender: commonware_p2p::Sender<PublicKey = PublicKeyOf<P>>,
RecoveredReceiver: commonware_p2p::Receiver<PublicKey = PublicKeyOf<P>>,
ResolverSender: commonware_p2p::Sender<PublicKey = PublicKeyOf<P>>,
ResolverReceiver: commonware_p2p::Receiver<PublicKey = PublicKeyOf<P>>,
{
let reporter_cfg = reporter::Config {
participants: participants.try_into().expect("public keys are unique"),
scheme: scheme.clone(),
elector: elector.clone(),
};
let reporter = reporter::Reporter::new(context.child("reporter"), reporter_cfg);
let (vote_sender, vote_receiver) = pending;
let (certificate_sender, certificate_receiver) = recovered;
let (resolver_sender, resolver_receiver) = resolver;
let validator_idx = participants
.iter()
.position(|p| p == &validator)
.expect("validator must be in participants");
let app_cfg = application::Config {
hasher: Sha256::default(),
relay,
me: validator.clone(),
propose_latency: (10.0, 5.0),
verify_latency: (10.0, 5.0),
certify_latency: (10.0, 5.0),
should_certify: certify.into_certifier(validator_idx),
};
let (actor, application) = application::Application::new(context.child("application"), app_cfg);
actor.start();
let blocker = oracle.control(validator.clone());
let engine_cfg = config::Config {
blocker,
scheme,
elector,
automaton: application.clone(),
relay: application.clone(),
reporter: reporter.clone(),
partition: validator.to_string(),
mailbox_size: NZUsize!(1024),
epoch: Epoch::new(EPOCH),
floor: Floor::Genesis(application::genesis::<Sha256>(Epoch::new(EPOCH))),
leader_timeout,
certification_timeout,
timeout_retry: Duration::from_secs(10),
fetch_timeout: Duration::from_secs(1),
activity_timeout: Delta::new(10),
skip_timeout: Delta::new(5),
fetch_concurrent: NZUsize!(1),
replay_buffer: NZUsize!(1024 * 1024),
write_buffer: NZUsize!(1024 * 1024),
page_cache: CacheRef::from_pooler(&context, PAGE_SIZE, PAGE_CACHE_SIZE),
strategy: Sequential,
forwarding,
};
let engine = Engine::new(context.child("engine"), engine_cfg);
engine.start(
(vote_sender, vote_receiver),
(certificate_sender, certificate_receiver),
(resolver_sender, resolver_receiver),
);
reporter
}
#[allow(clippy::too_many_arguments)]
fn spawn_honest_validator_in_faulty_messaging<P: simplex::Simplex>(
context: deterministic::Context,
oracle: &Oracle<PublicKeyOf<P>, deterministic::Context>,
participants: &[PublicKeyOf<P>],
scheme: P::Scheme,
validator: PublicKeyOf<P>,
byzantine_router: crate::network::Router<PublicKeyOf<P>, deterministic::Context>,
relay: Arc<relay::Relay<Sha256Digest, PublicKeyOf<P>>>,
leader_timeout: Duration,
certification_timeout: Duration,
forwarding: ForwardingPolicy,
channels: NetworkChannels<PublicKeyOf<P>>,
certify: CertifyChoice,
) -> reporter::Reporter<deterministic::Context, P::Scheme, P::Elector, Sha256Digest> {
let (vote_network, certificate_network, resolver_network) = channels;
let (vote_sender, vote_receiver) = vote_network;
let (certificate_sender, certificate_receiver) = certificate_network;
let (resolver_sender, resolver_receiver) = resolver_network;
let vote_router = byzantine_router.clone();
let (vote_primary, vote_secondary) = vote_receiver
.split_with(context.child("byzantine_first_vote"), move |msg| {
vote_router.route(msg)
});
let vote_receiver = ByzantineFirstReceiver::new(vote_primary, vote_secondary);
let certificate_router = byzantine_router.clone();
let (certificate_primary, certificate_secondary) = certificate_receiver
.split_with(context.child("byzantine_first_certificate"), move |msg| {
certificate_router.route(msg)
});
let certificate_receiver =
ByzantineFirstReceiver::new(certificate_primary, certificate_secondary);
let resolver_router = byzantine_router;
let (resolver_primary, resolver_secondary) = resolver_receiver
.split_with(context.child("byzantine_first_resolver"), move |msg| {
resolver_router.route(msg)
});
let resolver_receiver = ByzantineFirstReceiver::new(resolver_primary, resolver_secondary);
spawn_honest_validator::<P, _, _, _, _, _, _, _>(
context,
oracle,
participants,
scheme,
validator,
P::Elector::default(),
relay,
leader_timeout,
certification_timeout,
forwarding,
(vote_sender, vote_receiver),
(certificate_sender, certificate_receiver),
(resolver_sender, resolver_receiver),
certify,
)
}
/// Default link used by the round-indexed fault scheduler when re-establishing edges.
fn default_link() -> Link {
Link {
latency: Duration::from_millis(10),
jitter: Duration::from_millis(1),
success_rate: 1.0,
}
}
fn scheduled_partition(
schedule: &[(View, SetPartition)],
executing_view: u64,
) -> Option<SetPartition> {
schedule
.iter()
.find_map(|(view, p)| (*view == View::new(executing_view)).then_some(*p))
}
/// Look up the partition scheduled for view 1, the initial executing view.
/// The caller applies this synchronously before validators run so early view-1
/// traffic observes the scheduled topology.
fn initial_network_partition(partition: &Partition) -> Option<SetPartition> {
partition
.schedule()
.and_then(|schedule| scheduled_partition(schedule, 1))
}
async fn reporter_view_stream<P: simplex::Simplex>(
context: &deterministic::Context,
reporters: &mut [ReporterEntry<P>],
) -> Option<(u64, mpsc::UnboundedReceiver<u64>)> {
if reporters.is_empty() {
return None;
}
let (tx, rx) = mpsc::unbounded_channel();
let mut max_finalized_view = 0;
for (idx, (_, reporter)) in reporters.iter_mut().enumerate() {
let (latest, mut monitor) = reporter.subscribe().await;
max_finalized_view = max_finalized_view.max(latest.get());
let tx = tx.clone();
context
.child("reporter_view_watcher")
.with_attribute("index", idx)
.spawn(move |_| async move {
while let Some(next) = monitor.recv().await {
if tx.send(next.get()).is_err() {
break;
}
}
});
}
drop(tx);
Some((max_finalized_view, rx))
}
async fn spawn_network_fault_scheduler<P: simplex::Simplex>(
context: &deterministic::Context,
oracle: &Oracle<PublicKeyOf<P>, deterministic::Context>,
participants: &[PublicKeyOf<P>],
reporters: &mut [ReporterEntry<P>],
partition: Partition,
required_containers: u64,
initial_partition: Option<SetPartition>,
) {
let Some(schedule) = partition.schedule() else {
return;
};
if schedule.is_empty() || reporters.is_empty() {
return;
}
let Some((mut finalized_view, mut view_rx)) =
reporter_view_stream::<P>(context, reporters).await
else {
return;
};
let oracle = oracle.clone();
let participants: Vec<_> = participants.to_vec();
let schedule = schedule.to_vec();
context
.child("network_fault_scheduler")
.spawn(move |_| async move {
let link = default_link();
let mut active = initial_partition;
loop {
let executing_view = finalized_view.saturating_add(1);
let target = scheduled_partition(&schedule, executing_view);
if target != active {
apply_partition(&oracle, &participants, target.as_ref(), &link).await;
active = target;
}
if executing_view > required_containers {
break;
}
let Some(next) = view_rx.recv().await else {
break;
};
finalized_view = finalized_view.max(next);
}
});
}
/// Look up the rate scheduled for view 1 (the initial executing view), or `0`
/// if no entry matches. Used to seed the drop-rate cell synchronously *before*
/// validators run, so that very early view-1 traffic sees the scheduled rate.
fn initial_drop_rate(schedule: &[(View, u8)]) -> u8 {
schedule
.iter()
.find_map(|(view, rate)| (*view == View::new(1)).then_some(*rate))
.unwrap_or(0)
}
/// Drives the per-view honest-message drop rate for `Mode::FaultyMessaging`.
/// Subscribes to the first reporter's view monitor and updates the shared
/// [`network::DropRateCell`] when the active *executing* view's scheduled rate
/// differs from the current one. No-op when the schedule is empty or no
/// reporters were spawned.
///
/// `initial_rate` must equal the value the caller already wrote to `drop_rate`
/// before spawning validators (i.e., the rate for view 1). The scheduler uses
/// it to seed `active`, avoiding a redundant first-iteration write.
///
/// Clock-source note: the reporter's monitor reports the most recent
/// **finalized** view (see `consensus/src/simplex/mocks/reporter.rs::handle`).
/// When `monitor` fires with view `k`, the protocol has just finalized `k` and
/// the validators have already moved on to view `k + 1`. To realize the intent
/// "fault view v while consensus is executing view v" the lookup uses
/// `executing_view = finalized_view + 1`. The initial pre-recv lookup with
/// `finalized_view = 0` therefore covers view 1.
async fn spawn_messaging_fault_scheduler<P: simplex::Simplex>(
context: &deterministic::Context,
reporters: &mut [ReporterEntry<P>],
schedule: Vec<(View, u8)>,
required_containers: u64,
drop_rate: network::DropRateCell,
initial_rate: u8,
) {
if schedule.is_empty() || reporters.is_empty() {
return;
}
let Some((mut finalized_view, mut view_rx)) =
reporter_view_stream::<P>(context, reporters).await
else {
return;
};
context
.child("messaging_fault_scheduler")
.spawn(move |_| async move {
let mut active: u8 = initial_rate;
loop {
let executing_view = finalized_view.saturating_add(1);
let target: u8 = schedule
.iter()
.find_map(|(view, rate)| (*view == View::new(executing_view)).then_some(*rate))
.unwrap_or(0);
if target != active {
*drop_rate.lock() = target;
active = target;
}
if executing_view > required_containers {
break;
}
let Some(next) = view_rx.recv().await else {
break;
};
finalized_view = finalized_view.max(next);
}
});
}
pub(crate) fn network_faults(
strategy: StrategyChoice,
required_containers: u64,
rng: &mut impl rand::Rng,
) -> Vec<(View, SetPartition)> {
match strategy {
StrategyChoice::SmallScope {
fault_rounds,
fault_rounds_bound,
} => SmallScope {
fault_rounds,
fault_rounds_bound,
}
.network_faults(required_containers, rng),
StrategyChoice::AnyScope => AnyScope.network_faults(required_containers, rng),
StrategyChoice::FutureScope {
fault_rounds,
fault_rounds_bound,
} => FutureScope {
fault_rounds,
fault_rounds_bound,
}
.network_faults(required_containers, rng),
}
}
fn messaging_faults(
strategy: StrategyChoice,
required_containers: u64,
rng: &mut impl rand::Rng,
) -> Vec<(View, u8)> {
match strategy {
StrategyChoice::SmallScope {
fault_rounds,
fault_rounds_bound,
} => SmallScope {
fault_rounds,
fault_rounds_bound,
}
.messaging_faults(required_containers, rng),
StrategyChoice::AnyScope => AnyScope.messaging_faults(required_containers, rng),
StrategyChoice::FutureScope {
fault_rounds,
fault_rounds_bound,
} => FutureScope {
fault_rounds,
fault_rounds_bound,
}
.messaging_faults(required_containers, rng),
}
}
fn run<P: simplex::Simplex>(mut input: FuzzInput) {
let rng = FuzzRng::new(input.raw_bytes.clone());
let cfg = deterministic::Config::new().with_rng(Box::new(rng));
let executor = deterministic::Runner::new(cfg);
executor.start(|mut context| async move {
if matches!(input.partition, Partition::Adaptive(_)) {
input.partition = Partition::Adaptive(network_faults(
input.strategy,
input.required_containers,
&mut context,
));
}
let (oracle, participants, schemes, mut registrations) =
setup_network::<P>(&mut context, &input).await;
let initial_partition = initial_network_partition(&input.partition);
if initial_partition.is_some() {
apply_partition(
&oracle,
&participants,
initial_partition.as_ref(),
&default_link(),
)
.await;
}
let relay = Arc::new(relay::Relay::new());
let mut reporters = Vec::new();
let config = input.configuration;
// Spawn Byzantine nodes (Disrupters only)
for i in 0..config.faults as usize {
let validator = participants[i].clone();
let channels = registrations.remove(&validator).unwrap();
let ctx = context
.child("validator")
.with_attribute("public_key", &validator);
spawn_disrupter::<P>(ctx, schemes[i].clone(), &input, channels);
}
// Spawn honest validators
for i in (config.faults as usize)..(config.n as usize) {
let validator = participants[i].clone();
let (pending, recovered, resolver) = registrations.remove(&validator).unwrap();
let ctx = context
.child("validator")
.with_attribute("public_key", &validator);
let reporter = spawn_honest_validator::<P, _, _, _, _, _, _, _>(
ctx,
&oracle,
&participants,
schemes[i].clone(),
validator.clone(),
P::Elector::default(),
relay.clone(),
Duration::from_secs(1),
Duration::from_secs(2),
input.forwarding,
pending,
recovered,
resolver,
input.certify,
);
reporters.push((validator, reporter));
}
spawn_network_fault_scheduler::<P>(
&context,
&oracle,
&participants,
&mut reporters,
input.partition.clone(),
input.required_containers,
initial_partition,
)
.await;
if input.partition.is_connected() && config.is_valid() {
let mut finalizers = Vec::new();
for (validator, reporter) in reporters.iter_mut() {
let required_containers = input.required_containers;
let (mut latest, mut monitor): (View, Receiver<View>) = reporter.subscribe().await;
finalizers.push(
context
.child("finalizer")
.with_attribute("public_key", validator)
.spawn(move |_| async move {
while latest.get() < required_containers {
latest = monitor.recv().await.expect("event missing");
}
}),
);
}
join_all(finalizers).await;
} else {
context.sleep(MAX_SLEEP_DURATION).await;
}
if config.is_valid() {
let reporter_only: Vec<_> = reporters.iter().map(|(_, r)| r.clone()).collect();
invariants::check_no_invalid_reports_if_no_faults(config.faults, &reporter_only);
invariants::check_vote_invariants(config.faults as usize, &reporter_only);
let states = invariants::extract(reporter_only, config.n as usize);
invariants::check::<P>(config.n, states);
}
});
}
fn run_with_faulty_messaging<P: simplex::Simplex>(mut input: FuzzInput) {
// FaultyMessaging is a transport-layer fault axis; topology is always fully
// connected. Network-layer fault axes (`Static` / `Adaptive` partitions,
// degraded link) are explicitly disabled here so the only adversarial
// delivery effects come from the per-view messaging schedule below.
input.partition = Partition::Connected;
input.configuration = N4F1C3;
input.degraded_network = false;