-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathharness.rs
More file actions
4608 lines (4186 loc) · 161 KB
/
harness.rs
File metadata and controls
4608 lines (4186 loc) · 161 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
//! Test harness for marshal variants.
//!
//! This module provides a trait-based abstraction that allows writing tests once
//! and running them against both the standard and coding marshal variants.
use crate::{
marshal::{
coding::{
shards,
types::{coding_config_for_participants, CodedBlock},
Coding,
},
config::Config,
core::{Actor, Mailbox},
mocks::{application::Application, block::Block},
resolver::p2p as resolver,
standard::Standard,
Identifier,
},
simplex::{
scheme::bls12381_threshold::vrf as bls12381_threshold_vrf,
types::{Activity, Context, Finalization, Finalize, Notarization, Notarize, Proposal},
},
types::{coding::Commitment, Epoch, Epocher, FixedEpocher, Height, Round, View, ViewDelta},
Heightable, Reporter,
};
use commonware_broadcast::buffered;
use commonware_coding::{CodecConfig, ReedSolomon};
use commonware_cryptography::{
bls12381::primitives::variant::MinPk,
certificate::{mocks::Fixture, ConstantProvider, Provider, Scheme as _},
ed25519::{PrivateKey, PublicKey},
sha256::{Digest as Sha256Digest, Sha256},
Committable, Digest as DigestTrait, Digestible, Hasher as _, Signer,
};
use commonware_p2p::simulated::{self, Link, Network, Oracle};
use commonware_parallel::Sequential;
use commonware_runtime::{buffer::paged::CacheRef, deterministic, Clock, Metrics, Quota, Runner};
use commonware_storage::{
archive::{immutable, prunable},
translator::EightCap,
};
use commonware_utils::{test_rng_seeded, vec::NonEmptyVec, NZUsize, NZU16, NZU64};
use futures::StreamExt;
use rand::{
seq::{IteratorRandom, SliceRandom},
Rng,
};
use std::{
collections::BTreeMap,
future::Future,
num::{NonZeroU16, NonZeroU32, NonZeroU64, NonZeroUsize},
time::{Duration, Instant},
};
use tracing::info;
// Common type aliases
pub type D = Sha256Digest;
pub type K = PublicKey;
pub type Ctx = Context<D, K>;
pub type B = Block<D, Ctx>;
pub type V = MinPk;
pub type S = bls12381_threshold_vrf::Scheme<K, V>;
pub type P = ConstantProvider<S, Epoch>;
// Coding variant type aliases (uses Commitment in context)
pub type CodingCtx = Context<Commitment, K>;
pub type CodingB = Block<D, CodingCtx>;
// Common test constants
pub const PAGE_SIZE: NonZeroU16 = NZU16!(1024);
pub const PAGE_CACHE_SIZE: NonZeroUsize = NZUsize!(10);
pub const NAMESPACE: &[u8] = b"test";
pub const NUM_VALIDATORS: u32 = 4;
pub const QUORUM: u32 = 3;
pub const NUM_BLOCKS: u64 = 160;
pub const BLOCKS_PER_EPOCH: NonZeroU64 = NZU64!(20);
pub const LINK: Link = Link {
latency: Duration::from_millis(100),
jitter: Duration::from_millis(1),
success_rate: 1.0,
};
pub const UNRELIABLE_LINK: Link = Link {
latency: Duration::from_millis(200),
jitter: Duration::from_millis(50),
success_rate: 0.7,
};
pub const TEST_QUOTA: Quota = Quota::per_second(NonZeroU32::MAX);
/// A provider that always returns `None`, modeling an application that
/// has pruned all epoch state.
#[derive(Clone)]
pub struct EmptyProvider;
impl Provider for EmptyProvider {
type Scope = Epoch;
type Scheme = S;
fn scoped(&self, _scope: Epoch) -> Option<std::sync::Arc<S>> {
None
}
}
/// Default leader key for tests.
pub fn default_leader() -> K {
PrivateKey::from_seed(0).public_key()
}
/// Create a raw test block with a derived context.
pub fn make_raw_block(parent: D, height: Height, timestamp: u64) -> B {
let parent_view = height
.previous()
.map(|h| View::new(h.get()))
.unwrap_or(View::zero());
let context = Ctx {
round: Round::new(Epoch::zero(), View::new(height.get())),
leader: default_leader(),
parent: (parent_view, parent),
};
B::new::<Sha256>(context, parent, height, timestamp)
}
/// Setup network for tests with an initial participant peer set.
pub async fn setup_network_with_participants<I>(
context: deterministic::Context,
tracked_peer_sets: NonZeroUsize,
participants: I,
) -> Oracle<K, deterministic::Context>
where
I: IntoIterator<Item = K>,
{
let (network, oracle) = Network::new_with_peers(
context.with_label("network"),
simulated::Config {
max_size: 1024 * 1024,
disconnect_on_block: true,
tracked_peer_sets,
},
participants,
)
.await;
network.start();
oracle
}
/// Setup network links between peers.
pub async fn setup_network_links(
oracle: &mut Oracle<K, deterministic::Context>,
peers: &[K],
link: Link,
) {
for p1 in peers.iter() {
for p2 in peers.iter() {
if p2 == p1 {
continue;
}
let _ = oracle.add_link(p1.clone(), p2.clone(), link.clone()).await;
}
}
}
/// Result of setting up a validator.
pub struct ValidatorSetup<H: TestHarness> {
pub application: Application<H::ApplicationBlock>,
pub mailbox: Mailbox<S, H::Variant>,
pub extra: H::ValidatorExtra,
pub height: Height,
pub actor_handle: commonware_runtime::Handle<()>,
}
/// Per-validator handle for test operations.
pub struct ValidatorHandle<H: TestHarness> {
pub mailbox: Mailbox<S, H::Variant>,
pub extra: H::ValidatorExtra,
}
impl<H: TestHarness> Clone for ValidatorHandle<H> {
fn clone(&self) -> Self {
Self {
mailbox: self.mailbox.clone(),
extra: self.extra.clone(),
}
}
}
/// A test harness that abstracts over marshal variant differences.
pub trait TestHarness: 'static + Sized {
/// The application block type.
/// Note: We require `Digestible<Digest = D>` so generic test functions can use
/// `subscribe_by_digest` which expects the block's digest type.
type ApplicationBlock: crate::Block + Digestible<Digest = D> + Clone + Send + 'static;
/// The marshal variant type.
type Variant: crate::marshal::core::Variant<
ApplicationBlock = Self::ApplicationBlock,
Commitment = Self::Commitment,
>;
/// The block type used in test operations.
type TestBlock: Heightable + Clone + Send;
/// Additional per-validator state (e.g., shards mailbox for coding).
type ValidatorExtra: Clone + Send;
/// The commitment type for consensus certificates.
type Commitment: DigestTrait;
/// Setup a single validator with all necessary infrastructure.
fn setup_validator(
context: deterministic::Context,
oracle: &mut Oracle<K, deterministic::Context>,
validator: K,
provider: P,
) -> impl Future<Output = ValidatorSetup<Self>> + Send;
/// Setup a single validator with custom acknowledgement pipeline settings.
fn setup_validator_with(
context: deterministic::Context,
oracle: &mut Oracle<K, deterministic::Context>,
validator: K,
provider: P,
max_pending_acks: NonZeroUsize,
application: Application<Self::ApplicationBlock>,
) -> impl Future<Output = ValidatorSetup<Self>> + Send;
/// Create a test block from parent and height.
fn genesis_parent_commitment(num_participants: u16) -> Self::Commitment;
/// Create a test block from parent and height.
fn make_test_block(
parent: D,
parent_commitment: Self::Commitment,
height: Height,
timestamp: u64,
num_participants: u16,
) -> Self::TestBlock;
/// Get the commitment from a test block.
fn commitment(block: &Self::TestBlock) -> Self::Commitment;
/// Get the digest from a test block.
fn digest(block: &Self::TestBlock) -> D;
/// Get the height from a test block.
fn height(block: &Self::TestBlock) -> Height;
/// Propose a block (broadcast to network).
fn propose(
handle: &mut ValidatorHandle<Self>,
round: Round,
block: &Self::TestBlock,
) -> impl Future<Output = ()> + Send;
/// Mark a block as verified.
fn verify(
handle: &mut ValidatorHandle<Self>,
round: Round,
block: &Self::TestBlock,
all_handles: &mut [ValidatorHandle<Self>],
) -> impl Future<Output = ()> + Send;
/// Mark a block as certified.
fn certify(
handle: &mut ValidatorHandle<Self>,
round: Round,
block: &Self::TestBlock,
) -> impl Future<Output = bool> + Send;
/// Create a finalization certificate.
fn make_finalization(
proposal: Proposal<Self::Commitment>,
schemes: &[S],
quorum: u32,
) -> Finalization<S, Self::Commitment>;
/// Create a notarization certificate.
fn make_notarization(
proposal: Proposal<Self::Commitment>,
schemes: &[S],
quorum: u32,
) -> Notarization<S, Self::Commitment>;
/// Report a finalization to the mailbox.
fn report_finalization(
mailbox: &mut Mailbox<S, Self::Variant>,
finalization: Finalization<S, Self::Commitment>,
) -> impl Future<Output = ()> + Send;
/// Report a notarization to the mailbox.
fn report_notarization(
mailbox: &mut Mailbox<S, Self::Variant>,
notarization: Notarization<S, Self::Commitment>,
) -> impl Future<Output = ()> + Send;
/// Get the timeout duration for the finalize test.
fn finalize_timeout() -> Duration;
/// Setup validator for pruning test with prunable archives.
#[allow(clippy::type_complexity)]
fn setup_prunable_validator(
context: deterministic::Context,
oracle: &Oracle<K, deterministic::Context>,
validator: K,
schemes: &[S],
partition_prefix: &str,
page_cache: CacheRef,
) -> impl Future<
Output = (
Mailbox<S, Self::Variant>,
Self::ValidatorExtra,
Application<Self::ApplicationBlock>,
),
> + Send;
/// Verify a block for the pruning test (simpler than full verify).
fn verify_for_prune(
handle: &mut ValidatorHandle<Self>,
round: Round,
block: &Self::TestBlock,
) -> impl Future<Output = ()> + Send;
}
fn contract_runner(seed: u64) -> deterministic::Runner {
deterministic::Runner::new(
deterministic::Config::new()
.with_seed(seed)
.with_timeout(Some(Duration::from_secs(30))),
)
}
fn restart_cycles_for_seed(seed: u64) -> usize {
let mut rng = test_rng_seeded(seed);
rng.gen_range(2..=4)
}
struct HailstormValidator<H: TestHarness> {
application: Application<H::ApplicationBlock>,
handle: ValidatorHandle<H>,
actor_handle: commonware_runtime::Handle<()>,
}
type CanonicalEntry<H> = (Height, D, Finalization<S, <H as TestHarness>::Commitment>);
type CanonicalChain<H> = Vec<CanonicalEntry<H>>;
struct HailstormState<'a, H: TestHarness> {
validators: &'a mut [Option<HailstormValidator<H>>],
canonical: &'a mut CanonicalChain<H>,
parent: &'a mut D,
parent_commitment: &'a mut H::Commitment,
participants: &'a [K],
schemes: &'a [S],
propagation_delay: Duration,
}
fn active_validator_indices<H: TestHarness>(
validators: &[Option<HailstormValidator<H>>],
) -> Vec<usize> {
validators
.iter()
.enumerate()
.filter_map(|(idx, validator)| validator.as_ref().map(|_| idx))
.collect()
}
async fn wait_for_validator_height<H: TestHarness>(
context: &mut deterministic::Context,
validator: &HailstormValidator<H>,
height: Height,
expected_digest: D,
expected_finalization: &Finalization<S, H::Commitment>,
label: &str,
) {
loop {
let block = validator.handle.mailbox.get_block(height).await;
let finalization = validator.handle.mailbox.get_finalization(height).await;
if let (Some(block), Some(finalization)) = (block, finalization) {
assert_eq!(
block.digest(),
expected_digest,
"{label}: wrong block digest at height {}",
height.get()
);
assert_eq!(
finalization.round(),
expected_finalization.round(),
"{label}: wrong finalization round at height {}",
height.get()
);
assert_eq!(
finalization.proposal.payload,
expected_finalization.proposal.payload,
"{label}: wrong finalization payload at height {}",
height.get()
);
break;
}
context.sleep(Duration::from_millis(10)).await;
}
}
async fn assert_validator_matches_canonical<H: TestHarness>(
validator: &HailstormValidator<H>,
canonical: &[CanonicalEntry<H>],
label: &str,
) {
let delivered = validator.application.blocks();
for (height, block) in delivered {
let (_, expected_digest, _) = canonical
.iter()
.find(|(expected_height, _, _)| *expected_height == height)
.unwrap_or_else(|| {
panic!(
"{label}: unexpected delivered block at height {}",
height.get()
)
});
assert_eq!(
block.digest(),
*expected_digest,
"{label}: application delivered wrong digest at height {}",
height.get()
);
}
if let Some((height, digest)) = validator.application.tip() {
let (_, expected_digest, _) = canonical
.iter()
.find(|(expected_height, _, _)| *expected_height == height)
.unwrap_or_else(|| {
panic!(
"{label}: unexpected delivered tip at height {}",
height.get()
)
});
assert_eq!(
digest,
*expected_digest,
"{label}: application reported wrong tip digest at height {}",
height.get()
);
}
for (height, expected_digest, expected_finalization) in canonical {
let stored_block = validator
.handle
.mailbox
.get_block(*height)
.await
.unwrap_or_else(|| {
panic!(
"{label}: missing finalized block at height {}",
height.get()
)
});
assert_eq!(
stored_block.digest(),
*expected_digest,
"{label}: stored wrong block digest at height {}",
height.get()
);
let stored_finalization = validator
.handle
.mailbox
.get_finalization(*height)
.await
.unwrap_or_else(|| panic!("{label}: missing finalization at height {}", height.get()));
assert_eq!(
stored_finalization.round(),
expected_finalization.round(),
"{label}: stored wrong finalization round at height {}",
height.get()
);
assert_eq!(
stored_finalization.proposal.payload,
expected_finalization.proposal.payload,
"{label}: stored wrong finalization payload at height {}",
height.get()
);
}
if let Some((height, digest, _)) = canonical.last() {
assert_eq!(
validator.handle.mailbox.get_info(Identifier::Latest).await,
Some((*height, *digest)),
"{label}: latest info should match the canonical tip",
);
}
}
async fn assert_active_validators_match_canonical<H: TestHarness>(
validators: &[Option<HailstormValidator<H>>],
canonical: &[CanonicalEntry<H>],
) {
for idx in active_validator_indices(validators) {
let validator = validators[idx]
.as_ref()
.expect("active validator should be present");
assert_validator_matches_canonical(validator, canonical, &format!("validator_{idx}")).await;
}
}
async fn advance_hailstorm_to<H: TestHarness>(
target: u64,
context: &mut deterministic::Context,
state: &mut HailstormState<'_, H>,
) {
for height_value in (state.canonical.len() as u64 + 1)..=target {
let height = Height::new(height_value);
let active = active_validator_indices(state.validators);
let proposer_idx = active[context.gen_range(0..active.len())];
let verifier_count = usize::min(QUORUM as usize, active.len());
let verifier_indices = active
.iter()
.copied()
.filter(|idx| *idx != proposer_idx)
.choose_multiple(context, verifier_count.saturating_sub(1));
let block = H::make_test_block(
*state.parent,
*state.parent_commitment,
height,
height_value,
state.participants.len() as u16,
);
let round = Round::new(Epoch::zero(), View::new(height_value));
let proposal = Proposal {
round,
parent: height
.previous()
.map(|previous| View::new(previous.get()))
.unwrap_or(View::zero()),
payload: H::commitment(&block),
};
let expected_digest = H::digest(&block);
let finalization = H::make_finalization(proposal.clone(), state.schemes, QUORUM);
{
let proposer = state.validators[proposer_idx]
.as_mut()
.expect("proposer should be active");
H::propose(&mut proposer.handle, round, &block).await;
H::report_notarization(
&mut proposer.handle.mailbox,
H::make_notarization(proposal, state.schemes, QUORUM),
)
.await;
}
for verifier_idx in verifier_indices.iter().copied() {
let verifier = state.validators[verifier_idx]
.as_mut()
.expect("verifier should be active");
H::verify(&mut verifier.handle, round, &block, &mut []).await;
}
context.sleep(state.propagation_delay).await;
for idx in active_validator_indices(state.validators) {
let validator = state.validators[idx]
.as_mut()
.expect("validator should remain active");
H::report_finalization(&mut validator.handle.mailbox, finalization.clone()).await;
}
state
.canonical
.push((height, expected_digest, finalization));
*state.parent = expected_digest;
*state.parent_commitment = H::commitment(&block);
let (_, _, expected_finalization) = state
.canonical
.last()
.expect("canonical chain should contain the new height");
for idx in active_validator_indices(state.validators) {
let validator = state.validators[idx]
.as_ref()
.expect("validator should be active");
wait_for_validator_height(
context,
validator,
height,
expected_digest,
expected_finalization,
&format!("validator_{idx}"),
)
.await;
}
}
assert_active_validators_match_canonical(state.validators, state.canonical).await;
}
/// Stress marshal with repeated validator crashes and recoveries while a
/// canonical finalized chain continues to advance.
pub fn hailstorm<H: TestHarness>(
seed: u64,
shutdowns: usize,
interval: u64,
max_down: usize,
link: Link,
) -> String {
let runner = deterministic::Runner::new(
deterministic::Config::new()
.with_seed(seed)
.with_timeout(Some(H::finalize_timeout())),
);
runner.start(|mut context| async move {
let Fixture {
participants,
schemes,
..
} = bls12381_threshold_vrf::fixture::<V, _>(&mut context, NAMESPACE, NUM_VALIDATORS);
let mut oracle =
setup_network_with_participants(context.clone(), NZUsize!(3), participants.clone())
.await;
let propagation_delay = link.latency;
setup_network_links(&mut oracle, &participants, link.clone()).await;
let mut validators = Vec::new();
for (idx, validator) in participants.iter().enumerate() {
let setup = H::setup_validator(
context.with_label(&format!("validator_{idx}")),
&mut oracle,
validator.clone(),
ConstantProvider::new(schemes[idx].clone()),
)
.await;
validators.push(Some(HailstormValidator::<H> {
application: setup.application,
handle: ValidatorHandle {
mailbox: setup.mailbox,
extra: setup.extra,
},
actor_handle: setup.actor_handle,
}));
}
let mut canonical = CanonicalChain::<H>::new();
let mut parent = Sha256::hash(b"");
let mut parent_commitment = H::genesis_parent_commitment(participants.len() as u16);
let mut target_height = 0u64;
let max_interval = interval.max(1);
let max_down = max_down.max(1);
for shutdown_idx in 0..shutdowns {
let leadup = context.gen_range(1..=max_interval);
target_height += leadup;
let mut state = HailstormState {
validators: &mut validators,
canonical: &mut canonical,
parent: &mut parent,
parent_commitment: &mut parent_commitment,
participants: &participants,
schemes: &schemes,
propagation_delay,
};
advance_hailstorm_to(target_height, &mut context, &mut state).await;
let active = active_validator_indices(&validators);
let down_limit = usize::min(max_down, active.len().saturating_sub(1));
let down_count = down_limit.max(1);
let down_count = context.gen_range(1..=down_count);
let mut selected = active
.iter()
.copied()
.choose_multiple(&mut context, down_count);
selected.sort_unstable();
let persisted_height = target_height;
for idx in selected.iter().copied() {
let crashed = validators[idx]
.take()
.expect("selected validator should be active");
crashed.actor_handle.abort();
let _ = crashed.actor_handle.await;
}
info!(
seed,
shutdown_idx,
?selected,
down_count,
persisted_height,
leadup,
"marshal hailstorm shutdown"
);
let downtime = context.gen_range(1..=max_interval);
target_height += downtime;
let mut state = HailstormState {
validators: &mut validators,
canonical: &mut canonical,
parent: &mut parent,
parent_commitment: &mut parent_commitment,
participants: &participants,
schemes: &schemes,
propagation_delay,
};
advance_hailstorm_to(target_height, &mut context, &mut state).await;
for idx in selected.iter().copied() {
let restarted = H::setup_validator(
context.with_label(&format!("validator_{idx}_restart_{shutdown_idx}")),
&mut oracle,
participants[idx].clone(),
ConstantProvider::new(schemes[idx].clone()),
)
.await;
assert_eq!(
restarted.height,
Height::new(persisted_height),
"validator {idx} should recover its persisted finalized height before replay"
);
let mut restarted = HailstormValidator::<H> {
application: restarted.application,
handle: ValidatorHandle {
mailbox: restarted.mailbox,
extra: restarted.extra,
},
actor_handle: restarted.actor_handle,
};
for (_, _, finalization) in canonical.iter().skip(persisted_height as usize) {
H::report_finalization(&mut restarted.handle.mailbox, finalization.clone())
.await;
}
validators[idx] = Some(restarted);
}
for idx in selected.iter().copied() {
let validator = validators[idx]
.as_ref()
.expect("restarted validator should be active");
for (height, digest, finalization) in canonical.iter() {
wait_for_validator_height(
&mut context,
validator,
*height,
*digest,
finalization,
&format!("validator_{idx}_restarted"),
)
.await;
}
}
assert_active_validators_match_canonical(&validators, &canonical).await;
info!(
seed,
shutdown_idx,
?selected,
target_height,
downtime,
"marshal hailstorm recovered"
);
}
context.auditor().state()
})
}
/// Contract: `marshal.proposed(...)=true` means the block survives an
/// immediate crash and repeated recoveries.
pub fn proposed_success_implies_recoverable_after_restart<H: TestHarness>(
seeds: impl IntoIterator<Item = u64>,
) {
for seed in seeds {
let Fixture {
participants,
schemes,
..
} = bls12381_threshold_vrf::fixture::<V, _>(
&mut test_rng_seeded(seed),
NAMESPACE,
NUM_VALIDATORS,
);
let me = participants[0].clone();
let provider = ConstantProvider::new(schemes[0].clone());
let round = Round::new(Epoch::zero(), View::new(1));
let block = H::make_test_block(
Sha256::hash(b""),
H::genesis_parent_commitment(NUM_VALIDATORS as u16),
Height::new(1),
100,
NUM_VALIDATORS as u16,
);
let digest = H::digest(&block);
let recovery_cycles = restart_cycles_for_seed(seed);
let (_, mut checkpoint) = contract_runner(seed).start_and_recover({
let participants = participants.clone();
let me = me.clone();
let provider = provider.clone();
let block = block.clone();
move |context| async move {
let mut oracle = setup_network_with_participants(
context.clone(),
NZUsize!(1),
participants.clone(),
)
.await;
let setup = H::setup_validator(
context.with_label("validator_0"),
&mut oracle,
me.clone(),
provider.clone(),
)
.await;
let mut handle = ValidatorHandle::<H> {
mailbox: setup.mailbox,
extra: setup.extra,
};
H::propose(&mut handle, round, &block).await;
}
});
for cycle in 0..recovery_cycles {
let ((), next_checkpoint) =
deterministic::Runner::from(checkpoint).start_and_recover({
let participants = participants.clone();
let me = me.clone();
let provider = provider.clone();
move |context| async move {
let mut oracle = setup_network_with_participants(
context.clone(),
NZUsize!(1),
participants.clone(),
)
.await;
let restarted = H::setup_validator(
context.with_label(&format!("validator_0_restart_{cycle}")),
&mut oracle,
me.clone(),
provider.clone(),
)
.await;
assert!(
restarted.mailbox.get_block(&digest).await.is_some(),
"marshal.proposed() returning true must imply the block is recoverable \
after restart (seed={seed}, cycle={cycle})"
);
}
});
checkpoint = next_checkpoint;
}
}
}
/// Contract: `marshal.verified(...)=true` means the block survives an
/// immediate crash and repeated recoveries.
pub fn verified_success_implies_recoverable_after_restart<H: TestHarness>(
seeds: impl IntoIterator<Item = u64>,
) {
for seed in seeds {
let Fixture {
participants,
schemes,
..
} = bls12381_threshold_vrf::fixture::<V, _>(
&mut test_rng_seeded(seed),
NAMESPACE,
NUM_VALIDATORS,
);
let me = participants[0].clone();
let provider = ConstantProvider::new(schemes[0].clone());
let round = Round::new(Epoch::zero(), View::new(1));
let block = H::make_test_block(
Sha256::hash(b""),
H::genesis_parent_commitment(NUM_VALIDATORS as u16),
Height::new(1),
100,
NUM_VALIDATORS as u16,
);
let digest = H::digest(&block);
let recovery_cycles = restart_cycles_for_seed(seed);
let (_, mut checkpoint) = contract_runner(seed).start_and_recover({
let participants = participants.clone();
let me = me.clone();
let provider = provider.clone();
let block = block.clone();
move |context| async move {
let mut oracle = setup_network_with_participants(
context.clone(),
NZUsize!(1),
participants.clone(),
)
.await;
let setup = H::setup_validator(
context.with_label("validator_0"),
&mut oracle,
me.clone(),
provider.clone(),
)
.await;
let mut handle = ValidatorHandle::<H> {
mailbox: setup.mailbox,
extra: setup.extra,
};
let mut peers: [ValidatorHandle<H>; 0] = [];
H::verify(&mut handle, round, &block, &mut peers).await;
}
});
for cycle in 0..recovery_cycles {
let ((), next_checkpoint) =
deterministic::Runner::from(checkpoint).start_and_recover({
let participants = participants.clone();
let me = me.clone();
let provider = provider.clone();
move |context| async move {
let mut oracle = setup_network_with_participants(
context.clone(),
NZUsize!(1),
participants.clone(),
)
.await;
let restarted = H::setup_validator(
context.with_label(&format!("validator_0_restart_{cycle}")),
&mut oracle,
me.clone(),
provider.clone(),
)
.await;
assert!(
restarted.mailbox.get_block(&digest).await.is_some(),
"marshal.verified() returning true must imply the block is recoverable \
after restart (seed={seed}, cycle={cycle})"
);
}
});
checkpoint = next_checkpoint;
}
}
}
/// Regression: when the same block is verified at an earlier view and later
/// certified at a much later view (epoch-boundary reproposal), both writes
/// must land so retention can prune the earlier view without losing the
/// block. A naive "skip the sibling write if the block's digest is already
/// present in the other archive" optimization is unsafe because the two
/// archives prune per-view on the same boundary: if the block lives only in
/// `verified_blocks[V_early]` and never gets written to
/// `notarized_blocks[V_late]`, advancing retention past V_early drops the
/// block even though V_late is still within the window.
pub fn certify_at_later_view_survives_earlier_view_pruning<H: TestHarness>() {
let runner = deterministic::Runner::timed(Duration::from_secs(60));
runner.start(|mut context| async move {
let Fixture {
participants,
schemes,
..
} = bls12381_threshold_vrf::fixture::<V, _>(&mut context, NAMESPACE, NUM_VALIDATORS);
let mut oracle =
setup_network_with_participants(context.clone(), NZUsize!(1), participants.clone())
.await;
let setup = H::setup_validator(
context.with_label("validator_0"),
&mut oracle,
participants[0].clone(),
ConstantProvider::new(schemes[0].clone()),
)
.await;
let application = setup.application;
let mut handle = ValidatorHandle::<H> {
mailbox: setup.mailbox,
extra: setup.extra,
};
// A repeated block that we will verify at an early view and certify
// at a later view. Its height is intentionally well beyond the chain
// we'll drive below, so it never enters the finalized archive via
// gap repair and lives solely in the prunable caches.
let repeated = H::make_test_block(
Sha256::hash(b""),
H::genesis_parent_commitment(NUM_VALIDATORS as u16),
Height::new(5_000),
9_999,
NUM_VALIDATORS as u16,
);
let repeated_digest = H::digest(&repeated);
// Negative control: a verify-only block at the same early view. Because
// it is never certified, it lives solely in `verified_blocks[V=1]` and
// must disappear once retention pruning advances past V=1. Asserting it
// is gone confirms the prune actually fires at the expected floor, so
// the `repeated` survivor assertion below is genuinely load-bearing.
let orphan = H::make_test_block(
Sha256::hash(b"orphan"),
H::genesis_parent_commitment(NUM_VALIDATORS as u16),
Height::new(6_000),
9_998,
NUM_VALIDATORS as u16,
);
let orphan_digest = H::digest(&orphan);
// Verify `repeated` at V=1, then certify at V=25 (reproposal-style gap).
let v_early = Round::new(Epoch::zero(), View::new(1));
let v_late = Round::new(Epoch::zero(), View::new(25));
let mut peers: [ValidatorHandle<H>; 0] = [];