-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathmod.rs
More file actions
3965 lines (3623 loc) · 161 KB
/
mod.rs
File metadata and controls
3965 lines (3623 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
//! Standard variant for Marshal.
//!
//! # Overview
//!
//! The standard variant broadcasts complete blocks to all peers. Each validator
//! receives the full block directly from the proposer or via gossip.
//!
//! # Components
//!
//! - [`Standard`]: The variant marker type that configures marshal for full-block broadcast.
//! - [`Deferred`]: Deferred-verification wrapper that enforces epoch boundaries and
//! coordinates with the marshal actor.
//! - [`Inline`]: Inline-verification wrapper for applications whose blocks do not
//! implement [`crate::CertifiableBlock`].
//!
//! # Usage
//!
//! The standard variant uses the core [`crate::marshal::core::Actor`] and
//! [`crate::marshal::core::Mailbox`] with [`Standard`] as the variant type parameter.
//! Blocks are broadcast through [`commonware_broadcast::buffered`].
//!
//! # When to Use
//!
//! Prefer this variant when block sizes are small enough that shipping full blocks
//! to every peer is acceptable or if participants have sufficiently powerful networking
//! and want to avoid encoding / decoding overhead.
commonware_macros::stability_scope!(ALPHA {
mod deferred;
pub use deferred::Deferred;
mod inline;
pub use inline::Inline;
mod validation;
});
mod variant;
pub use variant::Standard;
#[cfg(test)]
mod tests {
use super::{Deferred, Inline, Standard};
use crate::{
marshal::{
ancestry::BlockProvider,
config::Config,
core::{cache, Actor, CommitmentFallback, Mailbox},
mocks::{
application::Application,
harness::{
self, default_leader, make_raw_block, setup_network_links,
setup_network_with_participants, Ctx, DeferredHarness, EmptyProvider,
InlineHarness, StandardHarness, TestHarness, ValidatorHandle, B,
BLOCKS_PER_EPOCH, D, LINK, NAMESPACE, NUM_VALIDATORS, PAGE_CACHE_SIZE,
PAGE_SIZE, QUORUM, S, UNRELIABLE_LINK, V,
},
verifying::MockVerifyingApp,
},
resolver::handler,
Identifier, Update,
},
simplex::{
scheme::bls12381_threshold::vrf as bls12381_threshold_vrf,
types::{Finalization, Proposal},
},
types::{Epoch, Epocher, FixedEpocher, Height, Round, View, ViewDelta},
Automaton, CertifiableAutomaton, Heightable, Reporter,
};
use bytes::Bytes;
use commonware_actor::{mailbox, Feedback};
use commonware_broadcast::buffered;
use commonware_codec::Encode;
use commonware_cryptography::{
certificate::{mocks::Fixture, ConstantProvider, Scheme as _},
ed25519::PublicKey,
sha256::Sha256,
Digestible, Hasher as _,
};
use commonware_macros::{select, test_group, test_traced};
use commonware_p2p::{
simulated::{self, Network},
Manager as _, Recipients,
};
use commonware_parallel::Sequential;
use commonware_resolver::{Consumer, Delivery, Fetch, Resolver};
use commonware_runtime::{
buffer::paged::CacheRef, deterministic, Clock, Metrics, Quota, Runner, Spawner,
Supervisor as _,
};
use commonware_storage::{
archive::{immutable, prunable, Archive as _},
metadata::{self, Metadata},
translator::{EightCap, TwoCap},
};
use commonware_utils::{
acknowledgement::Exact,
channel::{fallible::OneshotExt, oneshot},
ordered::Set,
sync::Mutex,
vec::NonEmptyVec,
NZUsize, NZU16, NZU64,
};
use std::{
num::{NonZeroU32, NonZeroU64, NonZeroUsize},
sync::Arc,
time::Duration,
};
#[test]
fn mailbox_provides_application_blocks() {
fn assert_provider<P: BlockProvider<Block = B>>() {}
assert_provider::<Mailbox<S, Standard<B>>>();
}
#[test_traced("WARN")]
fn test_standard_block_provider_parent_fetches_by_commitment() {
let runner = deterministic::Runner::timed(Duration::from_secs(30));
runner.start(|mut context| async move {
let Fixture { schemes, .. } =
bls12381_threshold_vrf::fixture::<V, _>(&mut context, NAMESPACE, NUM_VALIDATORS);
let buffer = RecordingBuffer::default();
let (mailbox, buffer, _resolver, _actor_handle) = start_standard_actor(
context.child("validator"),
"standard-provider-parent-commitment",
ConstantProvider::new(schemes[0].clone()),
Application::<B>::manual_ack(),
buffer,
)
.await;
let parent = make_raw_block(Sha256::hash(b""), Height::new(1), 100);
let child = make_raw_block(parent.digest(), Height::new(2), 200);
let subscription = context
.child("subscribe")
.spawn(move |_| BlockProvider::subscribe(mailbox, child));
context.sleep(Duration::from_millis(100)).await;
assert_eq!(
buffer.commitment_subscription_count(),
1,
"parent walkback should use the standard parent commitment"
);
subscription.abort();
});
}
fn assert_finalize_deterministic<H: TestHarness>(
seed: u64,
link: commonware_p2p::simulated::Link,
quorum_sees_finalization: bool,
) {
let r1 = harness::finalize::<H>(seed, link.clone(), quorum_sees_finalization);
let r2 = harness::finalize::<H>(seed, link, quorum_sees_finalization);
assert_eq!(r1, r2);
}
fn assert_hailstorm_deterministic<H: TestHarness>(seed: u64) {
let r1 = harness::hailstorm::<H>(seed, 4, 4, 1, LINK);
let r2 = harness::hailstorm::<H>(seed, 4, 4, 1, LINK);
assert_eq!(r1, r2);
}
fn assert_hailstorm_multi_deterministic<H: TestHarness>(seed: u64) {
let r1 = harness::hailstorm::<H>(seed, 4, 4, 2, LINK);
let r2 = harness::hailstorm::<H>(seed, 4, 4, 2, LINK);
assert_eq!(r1, r2);
}
#[test_group("slow")]
#[test_traced("WARN")]
fn test_standard_finalize_good_links() {
for seed in 0..5 {
assert_finalize_deterministic::<InlineHarness>(seed, LINK, false);
assert_finalize_deterministic::<DeferredHarness>(seed, LINK, false);
}
}
#[test_group("slow")]
#[test_traced("WARN")]
fn test_standard_finalize_bad_links() {
for seed in 0..5 {
assert_finalize_deterministic::<InlineHarness>(seed, UNRELIABLE_LINK, false);
assert_finalize_deterministic::<DeferredHarness>(seed, UNRELIABLE_LINK, false);
}
}
#[test_group("slow")]
#[test_traced("WARN")]
fn test_standard_finalize_good_links_quorum_sees_finalization() {
for seed in 0..5 {
assert_finalize_deterministic::<InlineHarness>(seed, LINK, true);
assert_finalize_deterministic::<DeferredHarness>(seed, LINK, true);
}
}
#[test_group("slow")]
#[test_traced("WARN")]
fn test_standard_finalize_bad_links_quorum_sees_finalization() {
for seed in 0..5 {
assert_finalize_deterministic::<InlineHarness>(seed, UNRELIABLE_LINK, true);
assert_finalize_deterministic::<DeferredHarness>(seed, UNRELIABLE_LINK, true);
}
}
#[test_group("slow")]
#[test_traced("WARN")]
fn test_standard_hailstorm_restarts() {
for seed in 0..2 {
assert_hailstorm_deterministic::<InlineHarness>(seed);
assert_hailstorm_deterministic::<DeferredHarness>(seed);
}
}
#[test_group("slow")]
#[test_traced("WARN")]
fn test_standard_hailstorm_multi_restarts() {
for seed in 0..2 {
assert_hailstorm_multi_deterministic::<InlineHarness>(seed);
assert_hailstorm_multi_deterministic::<DeferredHarness>(seed);
}
}
#[test_traced("WARN")]
fn test_standard_ack_pipeline_backlog() {
harness::ack_pipeline_backlog::<InlineHarness>();
harness::ack_pipeline_backlog::<DeferredHarness>();
}
#[test_traced("WARN")]
fn test_standard_ack_pipeline_backlog_persists_on_restart() {
harness::ack_pipeline_backlog_persists_on_restart::<InlineHarness>();
harness::ack_pipeline_backlog_persists_on_restart::<DeferredHarness>();
}
#[test_traced("WARN")]
fn test_standard_proposed_success_implies_recoverable_after_restart() {
harness::proposed_success_implies_recoverable_after_restart::<InlineHarness>(0..16);
harness::proposed_success_implies_recoverable_after_restart::<DeferredHarness>(0..16);
}
#[test_traced("WARN")]
fn test_standard_verified_success_implies_recoverable_after_restart() {
harness::verified_success_implies_recoverable_after_restart::<InlineHarness>(0..16);
harness::verified_success_implies_recoverable_after_restart::<DeferredHarness>(0..16);
}
#[test_traced("WARN")]
fn test_standard_certify_persists_equivocated_block() {
harness::certify_persists_equivocated_block::<InlineHarness>();
harness::certify_persists_equivocated_block::<DeferredHarness>();
}
#[test_traced("WARN")]
fn test_standard_certified_success_implies_recoverable_after_restart() {
harness::certified_success_implies_recoverable_after_restart::<InlineHarness>(0..16);
harness::certified_success_implies_recoverable_after_restart::<DeferredHarness>(0..16);
}
#[test_traced("WARN")]
fn test_standard_certify_at_later_view_survives_earlier_view_pruning() {
harness::certify_at_later_view_survives_earlier_view_pruning::<InlineHarness>();
harness::certify_at_later_view_survives_earlier_view_pruning::<DeferredHarness>();
}
#[test_traced("WARN")]
fn test_standard_delivery_visibility_implies_recoverable_after_restart() {
harness::delivery_visibility_implies_recoverable_after_restart::<InlineHarness>(0..16);
harness::delivery_visibility_implies_recoverable_after_restart::<DeferredHarness>(0..16);
}
#[test_traced("WARN")]
fn test_standard_sync_height_floor() {
harness::sync_height_floor::<InlineHarness>();
harness::sync_height_floor::<DeferredHarness>();
}
#[test_traced("WARN")]
fn test_standard_reject_stale_block_delivery_after_floor_update() {
harness::reject_stale_block_delivery_after_floor_update::<InlineHarness>();
harness::reject_stale_block_delivery_after_floor_update::<DeferredHarness>();
}
#[test_traced("WARN")]
fn test_standard_commitment_fetch_height_hint_mismatch_wakes_subscriber() {
harness::commitment_fetch_height_hint_mismatch_wakes_subscriber::<InlineHarness>();
harness::commitment_fetch_height_hint_mismatch_wakes_subscriber::<DeferredHarness>();
}
#[test_traced("WARN")]
fn test_standard_prune_finalized_archives() {
harness::prune_finalized_archives::<InlineHarness>();
harness::prune_finalized_archives::<DeferredHarness>();
}
#[test_traced("WARN")]
fn test_standard_subscribe_basic_block_delivery() {
harness::subscribe_basic_block_delivery::<InlineHarness>();
harness::subscribe_basic_block_delivery::<DeferredHarness>();
}
#[test_traced("WARN")]
fn test_standard_subscribe_multiple_subscriptions() {
harness::subscribe_multiple_subscriptions::<InlineHarness>();
harness::subscribe_multiple_subscriptions::<DeferredHarness>();
}
#[test_traced("WARN")]
fn test_standard_subscribe_canceled_subscriptions() {
harness::subscribe_canceled_subscriptions::<InlineHarness>();
harness::subscribe_canceled_subscriptions::<DeferredHarness>();
}
#[test_traced("WARN")]
fn test_standard_subscribe_blocks_from_different_sources() {
harness::subscribe_blocks_from_different_sources::<InlineHarness>();
harness::subscribe_blocks_from_different_sources::<DeferredHarness>();
}
#[test_traced("WARN")]
fn test_standard_get_info_basic_queries_present_and_missing() {
harness::get_info_basic_queries_present_and_missing::<InlineHarness>();
harness::get_info_basic_queries_present_and_missing::<DeferredHarness>();
}
#[test_traced("WARN")]
fn test_standard_get_info_latest_progression_multiple_finalizations() {
harness::get_info_latest_progression_multiple_finalizations::<InlineHarness>();
harness::get_info_latest_progression_multiple_finalizations::<DeferredHarness>();
}
#[test_traced("WARN")]
fn test_standard_get_block_by_height_and_latest() {
harness::get_block_by_height_and_latest::<InlineHarness>();
harness::get_block_by_height_and_latest::<DeferredHarness>();
}
// Directly writes blocks and finalizations into the storage archives
// used by the marshal, bypassing the normal finalization flow. This lets
// us manufacture inconsistent on-disk state (a finalization without
// its corresponding block) to simulate crash-recovery scenarios.
async fn seed_inconsistent_restart_state(
context: deterministic::Context,
partition_prefix: &str,
blocks: &[B],
finalizations: &[(Height, Finalization<S, D>)],
) {
let page_cache = CacheRef::from_pooler(&context, PAGE_SIZE, PAGE_CACHE_SIZE);
let replay_buffer = NonZeroUsize::new(1024).unwrap();
let write_buffer = NonZeroUsize::new(1024).unwrap();
let items_per_section = NonZeroU64::new(10).unwrap();
let mut finalizations_by_height = immutable::Archive::init(
context.child("seed_finalizations_by_height"),
immutable::Config {
metadata_partition: format!("{partition_prefix}-finalizations-by-height-metadata"),
freezer_table_partition: format!(
"{partition_prefix}-finalizations-by-height-freezer-table"
),
freezer_table_initial_size: 64,
freezer_table_resize_frequency: 10,
freezer_table_resize_chunk_size: 10,
freezer_key_partition: format!(
"{partition_prefix}-finalizations-by-height-freezer-key"
),
freezer_key_page_cache: page_cache.clone(),
freezer_value_partition: format!(
"{partition_prefix}-finalizations-by-height-freezer-value"
),
freezer_value_target_size: 1024,
freezer_value_compression: None,
ordinal_partition: format!("{partition_prefix}-finalizations-by-height-ordinal"),
items_per_section,
codec_config: S::certificate_codec_config_unbounded(),
replay_buffer,
freezer_key_write_buffer: write_buffer,
freezer_value_write_buffer: write_buffer,
ordinal_write_buffer: write_buffer,
},
)
.await
.expect("failed to initialize finalizations archive for seeded restart state");
let mut finalized_blocks = immutable::Archive::init(
context.child("seed_finalized_blocks"),
immutable::Config {
metadata_partition: format!("{partition_prefix}-finalized_blocks-metadata"),
freezer_table_partition: format!(
"{partition_prefix}-finalized_blocks-freezer-table"
),
freezer_table_initial_size: 64,
freezer_table_resize_frequency: 10,
freezer_table_resize_chunk_size: 10,
freezer_key_partition: format!("{partition_prefix}-finalized_blocks-freezer-key"),
freezer_key_page_cache: page_cache,
freezer_value_partition: format!(
"{partition_prefix}-finalized_blocks-freezer-value"
),
freezer_value_target_size: 1024,
freezer_value_compression: None,
ordinal_partition: format!("{partition_prefix}-finalized_blocks-ordinal"),
items_per_section,
codec_config: (),
replay_buffer,
freezer_key_write_buffer: write_buffer,
freezer_value_write_buffer: write_buffer,
ordinal_write_buffer: write_buffer,
},
)
.await
.expect("failed to initialize finalized blocks archive for seeded restart state");
for block in blocks {
finalized_blocks
.put(block.height().get(), block.digest(), block.clone())
.await
.expect("failed to seed finalized block");
}
finalized_blocks
.sync()
.await
.expect("failed to sync seeded finalized blocks");
for (height, finalization) in finalizations {
finalizations_by_height
.put(
height.get(),
finalization.proposal.payload,
finalization.clone(),
)
.await
.expect("failed to seed finalization");
}
finalizations_by_height
.sync()
.await
.expect("failed to sync seeded finalizations");
}
// Writes a block directly into the cache's per-epoch notarized storage,
// simulating a block that was notarized but never finalized before a crash.
async fn seed_cache_block(
context: deterministic::Context,
partition_prefix: &str,
epoch: Epoch,
view: View,
block: &B,
) {
let cache_prefix = format!("{partition_prefix}-cache");
let replay_buffer = NonZeroUsize::new(1024).unwrap();
let write_buffer = NonZeroUsize::new(1024).unwrap();
let mut metadata: Metadata<deterministic::Context, u8, (Epoch, Epoch)> = Metadata::init(
context.child("seed_cache_metadata"),
metadata::Config {
partition: format!("{cache_prefix}-metadata"),
codec_config: ((), ()),
},
)
.await
.expect("failed to initialize cache metadata");
metadata.put(0, (epoch, epoch));
metadata
.sync()
.await
.expect("failed to sync cache metadata");
let page_cache = CacheRef::from_pooler(&context, PAGE_SIZE, PAGE_CACHE_SIZE);
let mut notarized: prunable::Archive<TwoCap, deterministic::Context, D, B> =
prunable::Archive::init(
context.child("seed_notarized"),
prunable::Config {
translator: TwoCap,
key_partition: format!("{cache_prefix}-cache-{epoch}-notarized-key"),
key_page_cache: page_cache,
value_partition: format!("{cache_prefix}-cache-{epoch}-notarized-value"),
items_per_section: NonZeroU64::new(10).unwrap(),
compression: None,
codec_config: (),
replay_buffer,
key_write_buffer: write_buffer,
value_write_buffer: write_buffer,
},
)
.await
.expect("failed to initialize notarized blocks archive");
notarized
.put_sync(view.get(), block.digest(), block.clone())
.await
.expect("failed to seed notarized block");
}
// Verifies that a validator whose finalized-blocks archive is missing
// the block at the tip (has finalization for height 2 but only block 1)
// fetches the missing block from a peer on restart.
#[test_traced("WARN")]
fn test_standard_restart_repairs_trailing_missing_finalized_block() {
let runner = deterministic::Runner::timed(Duration::from_secs(30));
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.child("network"),
NZUsize!(3),
participants.clone(),
)
.await;
setup_network_links(&mut oracle, &participants, LINK).await;
let recovering_validator = participants[0].clone();
let peer_validator = participants[1].clone();
// Build chain: genesis -> block_one -> block_two
let genesis = make_raw_block(Sha256::hash(b""), Height::zero(), 0);
let block_one = make_raw_block(genesis.digest(), Height::new(1), 100);
let block_two = make_raw_block(block_one.digest(), Height::new(2), 200);
let finalization_two = StandardHarness::make_finalization(
Proposal::new(
Round::new(Epoch::zero(), View::new(2)),
View::new(1),
StandardHarness::commitment(&block_two),
),
&schemes,
3,
);
// Give the peer all blocks so it can serve them during repair.
let mut peer_mailbox = StandardHarness::setup_validator(
context.child("peer_validator"),
&mut oracle,
peer_validator.clone(),
ConstantProvider::new(schemes[1].clone()),
)
.await
.mailbox;
assert!(
peer_mailbox
.verified(Round::new(Epoch::zero(), View::new(1)), block_one.clone())
.await
);
assert!(
peer_mailbox
.verified(Round::new(Epoch::zero(), View::new(2)), block_two.clone())
.await
);
StandardHarness::report_finalization(&mut peer_mailbox, finalization_two.clone()).await;
context.sleep(Duration::from_millis(200)).await;
// Seed inconsistent state: has block_one but only a finalization
// (no block data) for height 2.
let partition_prefix = format!("validator-{recovering_validator}");
seed_inconsistent_restart_state(
context.child("storage"),
&partition_prefix,
&[block_one],
&[(Height::new(2), finalization_two)],
)
.await;
// Start the recovering validator and verify initial state.
let recovering = StandardHarness::setup_validator_with(
context.child("recovering_validator"),
&mut oracle,
recovering_validator,
ConstantProvider::new(schemes[0].clone()),
NZUsize!(1),
crate::marshal::mocks::application::Application::manual_ack(),
)
.await;
// Walk through all blocks sequentially. Block 2 must be
// repaired from the peer before it can be dispatched.
for expected_height in 1..=2 {
let h = recovering.application.acknowledged().await;
assert_eq!(h, Height::new(expected_height));
}
});
}
// Verifies that a validator missing an internal block (has blocks 1 and 3
// but not 2, with finalizations for both 2 and 3) fetches the gap from a
// peer on restart.
#[test_traced("WARN")]
fn test_standard_restart_repairs_internal_missing_finalized_block() {
let runner = deterministic::Runner::timed(Duration::from_secs(30));
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.child("network"),
NZUsize!(3),
participants.clone(),
)
.await;
setup_network_links(&mut oracle, &participants, LINK).await;
let recovering_validator = participants[0].clone();
let peer_validator = participants[1].clone();
// Build chain: genesis -> block_one -> block_two -> block_three
let genesis = make_raw_block(Sha256::hash(b""), Height::zero(), 0);
let block_one = make_raw_block(genesis.digest(), Height::new(1), 100);
let block_two = make_raw_block(block_one.digest(), Height::new(2), 200);
let block_three = make_raw_block(block_two.digest(), Height::new(3), 300);
let finalization_two = StandardHarness::make_finalization(
Proposal::new(
Round::new(Epoch::zero(), View::new(2)),
View::new(1),
StandardHarness::commitment(&block_two),
),
&schemes,
3,
);
let finalization_three = StandardHarness::make_finalization(
Proposal::new(
Round::new(Epoch::zero(), View::new(3)),
View::new(2),
StandardHarness::commitment(&block_three),
),
&schemes,
3,
);
// Give the peer all blocks so it can serve them during repair.
let mut peer_mailbox = StandardHarness::setup_validator(
context.child("peer_validator"),
&mut oracle,
peer_validator.clone(),
ConstantProvider::new(schemes[1].clone()),
)
.await
.mailbox;
assert!(
peer_mailbox
.verified(Round::new(Epoch::zero(), View::new(1)), block_one.clone())
.await
);
assert!(
peer_mailbox
.verified(Round::new(Epoch::zero(), View::new(2)), block_two.clone())
.await
);
assert!(
peer_mailbox
.verified(Round::new(Epoch::zero(), View::new(3)), block_three.clone())
.await
);
StandardHarness::report_finalization(&mut peer_mailbox, finalization_two.clone()).await;
StandardHarness::report_finalization(&mut peer_mailbox, finalization_three.clone())
.await;
context.sleep(Duration::from_millis(200)).await;
// Seed inconsistent state: has blocks 1 and 3 but is missing
// block 2 (an internal gap in the finalized chain).
let partition_prefix = format!("validator-{recovering_validator}");
seed_inconsistent_restart_state(
context.child("storage"),
&partition_prefix,
&[block_one, block_three.clone()],
&[
(Height::new(2), finalization_two),
(Height::new(3), finalization_three),
],
)
.await;
let recovering = StandardHarness::setup_validator_with(
context.child("recovering_validator"),
&mut oracle,
recovering_validator,
ConstantProvider::new(schemes[0].clone()),
NZUsize!(1),
crate::marshal::mocks::application::Application::manual_ack(),
)
.await;
// Walk through all three blocks sequentially. Block 2 must be
// repaired from the peer before it can be dispatched.
for expected_height in 1..=3 {
let h = recovering.application.acknowledged().await;
assert_eq!(h, Height::new(expected_height));
}
});
}
// Verifies that a block persisted at a height beyond the last finalization
// is still surfaced via get_block and dispatched to the application. This
// can happen if a crash occurs after persisting the block but before
// persisting its finalization.
#[test_traced("WARN")]
fn test_standard_restart_surfaces_block_without_finalization() {
let runner = deterministic::Runner::timed(Duration::from_secs(30));
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.child("network"),
NZUsize!(3),
participants.clone(),
)
.await;
setup_network_links(&mut oracle, &participants, LINK).await;
let recovering_validator = participants[0].clone();
// Build chain: genesis -> block_one -> block_two
// Only block_one gets a finalization; block_two is an orphan.
let genesis = make_raw_block(Sha256::hash(b""), Height::zero(), 0);
let block_one = make_raw_block(genesis.digest(), Height::new(1), 100);
let block_two = make_raw_block(block_one.digest(), Height::new(2), 200);
let finalization_one = StandardHarness::make_finalization(
Proposal::new(
Round::new(Epoch::zero(), View::new(1)),
View::zero(),
StandardHarness::commitment(&block_one),
),
&schemes,
3,
);
// Seed state: both blocks persisted, but only block_one has a
// finalization. block_two is a block without a corresponding
// finalization row.
let partition_prefix = format!("validator-{recovering_validator}");
seed_inconsistent_restart_state(
context.child("storage"),
&partition_prefix,
&[block_one.clone(), block_two.clone()],
&[(Height::new(1), finalization_one)],
)
.await;
let recovering = StandardHarness::setup_validator_with(
context.child("recovering_validator"),
&mut oracle,
recovering_validator,
ConstantProvider::new(schemes[0].clone()),
NZUsize!(1),
crate::marshal::mocks::application::Application::manual_ack(),
)
.await;
// The tip tracks the highest finalization, not the highest block.
assert_eq!(
recovering.mailbox.get_info(Identifier::Latest).await,
Some((Height::new(1), block_one.digest())),
"latest tip should be derived from the highest stored finalization"
);
assert_eq!(
recovering.mailbox.get_block(Height::new(2)).await,
Some(block_two.clone()),
"block without a finalization row should still be queryable by height"
);
// Walk the application through sequential acks. Even though
// block_two has no finalization, it is still dispatched because
// its block data exists in the archive.
for expected_height in 1..=2 {
let h = recovering.application.acknowledged().await;
assert_eq!(h, Height::new(expected_height));
}
});
}
// Verifies repair when many trailing blocks are missing. Seed state has
// only block_one's data but finalizations for heights 1-5. The recovering
// validator must fetch blocks 2-5 from the peer.
#[test_traced("WARN")]
fn test_standard_restart_repairs_multiple_trailing_missing_finalized_blocks() {
let runner = deterministic::Runner::timed(Duration::from_secs(30));
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.child("network"),
NZUsize!(3),
participants.clone(),
)
.await;
setup_network_links(&mut oracle, &participants, LINK).await;
let recovering_validator = participants[0].clone();
let peer_validator = participants[1].clone();
// Build a 5-block chain.
let genesis = make_raw_block(Sha256::hash(b""), Height::zero(), 0);
let block_one = make_raw_block(genesis.digest(), Height::new(1), 100);
let block_two = make_raw_block(block_one.digest(), Height::new(2), 200);
let block_three = make_raw_block(block_two.digest(), Height::new(3), 300);
let block_four = make_raw_block(block_three.digest(), Height::new(4), 400);
let block_five = make_raw_block(block_four.digest(), Height::new(5), 500);
let mut finalizations = Vec::new();
let blocks = [
&block_one,
&block_two,
&block_three,
&block_four,
&block_five,
];
for (i, block) in blocks.iter().enumerate() {
let view = View::new(block.height().get());
let parent_view = if i == 0 {
View::zero()
} else {
View::new(blocks[i - 1].height().get())
};
finalizations.push(StandardHarness::make_finalization(
Proposal::new(
Round::new(Epoch::zero(), view),
parent_view,
StandardHarness::commitment(block),
),
&schemes,
3,
));
}
// Give the peer all blocks and finalizations.
let mut peer_mailbox = StandardHarness::setup_validator(
context.child("peer_validator"),
&mut oracle,
peer_validator.clone(),
ConstantProvider::new(schemes[1].clone()),
)
.await
.mailbox;
for (i, block) in blocks.iter().enumerate() {
assert!(
peer_mailbox
.verified(
Round::new(Epoch::zero(), View::new(block.height().get())),
(*block).clone(),
)
.await
);
StandardHarness::report_finalization(&mut peer_mailbox, finalizations[i].clone())
.await;
}
context.sleep(Duration::from_millis(200)).await;
// Seed inconsistent state: only block_one persisted but all 5
// finalizations exist, leaving blocks 2-5 missing.
let partition_prefix = format!("validator-{recovering_validator}");
seed_inconsistent_restart_state(
context.child("storage"),
&partition_prefix,
&[block_one],
&finalizations
.iter()
.enumerate()
.map(|(i, f)| (Height::new(i as u64 + 1), f.clone()))
.collect::<Vec<_>>(),
)
.await;
let recovering = StandardHarness::setup_validator_with(
context.child("recovering_validator"),
&mut oracle,
recovering_validator,
ConstantProvider::new(schemes[0].clone()),
NZUsize!(1),
crate::marshal::mocks::application::Application::manual_ack(),
)
.await;
// Walk through all five blocks sequentially. Blocks 2-5 must be
// repaired from the peer before they can be dispatched.
for expected_height in 1..=5 {
let h = recovering.application.acknowledged().await;
assert_eq!(h, Height::new(expected_height));
}
});
}
// Verifies repair when the finalized tip is far ahead of the last stored
// block and only the tip has a direct finalization. This forces recovery to
// walk the chain backwards by block commitment for more than `max_repair`
// missing heights.
#[test_traced("WARN")]
fn test_standard_restart_repairs_large_pending_tip_by_commitment() {
let runner = deterministic::Runner::timed(Duration::from_secs(120));
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.child("network"),
NZUsize!(3),
participants.clone(),
)
.await;
setup_network_links(&mut oracle, &participants, LINK).await;
let recovering_validator = participants[0].clone();
let peer_validator = participants[1].clone();
let pending_tip = 18;
let mut blocks = Vec::new();
let mut parent = Sha256::hash(b"");
for height in 1..=pending_tip {
let block = make_raw_block(parent, Height::new(height), height * 100);
parent = block.digest();
blocks.push(block);
}
let tip_block = blocks.last().expect("tip block exists");
let tip_finalization = StandardHarness::make_finalization(
Proposal::new(
Round::new(Epoch::zero(), View::new(pending_tip)),
View::new(pending_tip - 1),
StandardHarness::commitment(tip_block),
),
&schemes,
QUORUM,
);
// Give the peer every block, but the recovering validator will only
// know the tip finalization. The repair loop must fetch blocks
// 18 down to 2 by commitment.
let peer_mailbox = StandardHarness::setup_validator(
context.child("peer_validator"),
&mut oracle,
peer_validator.clone(),
ConstantProvider::new(schemes[1].clone()),
)
.await
.mailbox;
for block in blocks.iter() {
assert!(
peer_mailbox
.verified(
Round::new(Epoch::zero(), View::new(block.height().get())),
block.clone(),
)
.await
);
}
context.sleep(Duration::from_millis(200)).await;
let partition_prefix = format!("validator-{recovering_validator}");
seed_inconsistent_restart_state(
context.child("storage"),
&partition_prefix,
&[blocks[0].clone()],
&[(Height::new(pending_tip), tip_finalization)],
)
.await;
let recovering = StandardHarness::setup_validator_with(
context.child("recovering_validator"),
&mut oracle,
recovering_validator,
ConstantProvider::new(schemes[0].clone()),
NZUsize!(1),
crate::marshal::mocks::application::Application::manual_ack(),
)
.await;
for _ in 0..100 {
if recovering.application.tip().map(|(height, _)| height)
== Some(Height::new(pending_tip))
{
break;
}
context.sleep(Duration::from_millis(10)).await;
}
assert_eq!(
recovering.application.tip().map(|(height, _)| height),
Some(Height::new(pending_tip)),
"restart should surface the pending finalized tip before all blocks are repaired"
);
for expected_height in 1..=pending_tip {
let h = recovering.application.acknowledged().await;
assert_eq!(h, Height::new(expected_height));
}
for height in [2, 10, pending_tip] {
let block = recovering
.mailbox
.get_block(Height::new(height))
.await
.unwrap_or_else(|| panic!("block {height} should be recoverable"));
assert_eq!(block.digest(), blocks[(height - 1) as usize].digest());
}
});