commonware-consensus 2026.9.0

Order opaque messages in a Byzantine environment.
Documentation
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
use crate::{
    Viewable,
    simplex::types::{Certificate, Notarization},
    types::{TermLength, View},
};
use commonware_cryptography::{Digest, certificate::Scheme};
use std::collections::BTreeMap;

/// Why a resolver fetch was requested.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum FetchReason {
    MissingNullification,
    CertificationFailed,
}

impl FetchReason {
    /// Returns the stable trace field value for this reason.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::MissingNullification => "missing_nullification",
            Self::CertificationFailed => "certification_failed",
        }
    }
}

/// Side effects requested by resolver state.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum Effect {
    /// Issue a resolver fetch for `view`.
    Fetch {
        /// The view to fetch.
        view: View,
        /// The view whose processing caused this fetch.
        cause: View,
        /// Why the fetch is needed.
        reason: FetchReason,
    },
    /// Retain only views above this floor.
    RetainAbove(View),
}

/// Tracks certificates used to construct and repair ancestry through the
/// current view.
pub struct State<S: Scheme, D: Digest> {
    /// Highest seen view.
    current_view: View,
    /// Highest certificate used as the construction floor.
    floor: Option<Certificate<S, D>>,
    /// Highest finalization, retained across floor advances because it settles
    /// every request at or below its view.
    finalization: Option<Certificate<S, D>>,
    /// Notarizations pending certification (possible floors).
    notarizations: BTreeMap<View, Notarization<S, D>>,
    /// Nullifications that cover any view greater than the floor.
    nullifications: BTreeMap<View, Certificate<S, D>>,
    /// Lowest anchor that fetch scans still need to consider (see
    /// [Self::fetch_missing]). Anchors below this cursor have already been
    /// requested or are covered by a stored nullification. A floor raise
    /// landing mid-term pulls it back to just above the floor (see
    /// [Self::prune]).
    fetch_floor: View,
    /// Number of views in each leader term.
    term_length: TermLength,
}

impl<S: Scheme, D: Digest> State<S, D> {
    /// Create a new instance of [State].
    pub const fn new(term_length: TermLength) -> Self {
        Self {
            current_view: View::zero(),
            floor: None,
            finalization: None,
            notarizations: BTreeMap::new(),
            nullifications: BTreeMap::new(),
            fetch_floor: View::zero(),
            term_length,
        }
    }

    /// Returns the term length this state was built with.
    pub const fn term_length(&self) -> TermLength {
        self.term_length
    }

    /// Handle a new certificate and return any effects the resolver actor should apply.
    pub fn handle(&mut self, certificate: Certificate<S, D>) -> Vec<Effect> {
        let cause = certificate.view();
        self.current_view = self.current_view.max(cause);
        let mut effects = Vec::new();
        match certificate {
            Certificate::Nullification(nullification) => {
                let view = nullification.view();
                if covers_above_floor(view, self.term_length, self.floor_view()) {
                    self.nullifications
                        .insert(view, Certificate::Nullification(nullification));
                }
            }
            Certificate::Notarization(notarization) => {
                let view = notarization.view();
                if view > self.floor_view() {
                    self.notarizations.insert(view, notarization);
                }
            }
            Certificate::Finalization(finalization) => {
                // Retain the proof, not just its view: it may need to be served
                // after a higher certified notarization advances the floor.
                let view = finalization.view();
                let certificate = Certificate::Finalization(finalization);
                if self
                    .finalization
                    .as_ref()
                    .is_none_or(|known| view > known.view())
                {
                    self.finalization = Some(certificate.clone());
                }
                if view > self.floor_view() || self.can_upgrade_floor(view) {
                    self.floor = Some(certificate);
                    effects.push(self.prune());
                }
            }
        }

        effects.extend(self.fetch_missing(cause));
        effects
    }

    /// Handle a certification result from the voter.
    pub fn handle_certified(&mut self, view: View, success: bool) -> Vec<Effect> {
        let mut effects = Vec::new();
        if success {
            // Certification passed: raise the floor to the notarization if we
            // still hold it. This may occur before or after a nullification
            // for the same view (and should always be favored). Finalization
            // remains the stronger proof and can later supersede this floor
            // at the same or higher view.
            if let Some(notarization) = self.notarizations.remove(&view)
                && view > self.floor_view()
            {
                self.floor = Some(Certificate::Notarization(notarization));
                effects.push(self.prune());
            }

            // Re-scan for missing nullifications: a floor raise landing
            // mid-term pulls the fetch cursor back (see [Self::prune]).
            effects.extend(self.fetch_missing(view));
        } else {
            self.notarizations.remove(&view);

            // Request a nullification for this view (if not already covered).
            // Existing fetches remain active when the failed notarization did
            // not satisfy their subscribers, so the resolver retries them.
            if self.needs_nullification(view) {
                effects.push(Effect::Fetch {
                    view,
                    cause: view,
                    reason: FetchReason::CertificationFailed,
                });
            }
        }
        effects
    }

    /// Get the best certificate for a given view.
    ///
    /// The retained finalization is preferred at or below its view because it
    /// settles those requests. A higher notarization may be the current floor
    /// without settling a targeted request for older ancestry.
    pub fn get(&self, view: View) -> Option<&Certificate<S, D>> {
        if let Some(finalization) = &self.finalization
            && view <= finalization.view()
        {
            return Some(finalization);
        }

        if let Some(floor) = &self.floor
            && view <= floor.view()
        {
            return Some(floor);
        }

        // Otherwise, return the nullification covering the view if it exists.
        self.covering_nullification(view)
    }

    /// Returns the highest finalization certificate retained independently of
    /// the construction floor.
    pub const fn finalization(&self) -> Option<&Certificate<S, D>> {
        self.finalization.as_ref()
    }

    /// Returns the stored nullification covering `view`, if any.
    ///
    /// Since a nullification covers the rest of its term, it may be keyed at
    /// an earlier view in `view`'s term.
    fn covering_nullification(&self, view: View) -> Option<&Certificate<S, D>> {
        self.nullifications
            .range(view.covering_range(self.term_length))
            .next_back()
            .map(|(_, n)| n)
    }

    /// Get the view of the floor.
    fn floor_view(&self) -> View {
        self.floor
            .as_ref()
            .map(|floor| floor.view())
            .unwrap_or(View::zero())
    }

    /// Returns whether `view` still needs a covering nullification to make
    /// progress: it is above the floor and no stored nullification covers it.
    fn needs_nullification(&self, view: View) -> bool {
        view > self.floor_view() && self.covering_nullification(view).is_none()
    }

    /// Returns true if the floor can be upgraded at the given view.
    fn can_upgrade_floor(&self, view: View) -> bool {
        matches!(
            self.floor.as_ref(),
            Some(Certificate::Notarization(n)) if n.view() == view
        )
    }

    /// Return requests for any missing nullifications.
    ///
    /// Scans from the cursor (never below the floor), requesting each term's
    /// anchor and advancing the cursor past everything scanned. Requests
    /// stay pending in the resolver until answered or retained out (we must
    /// eventually receive a nullification at the anchor or a
    /// notarization/finalization at a higher view). See the
    /// [module docs](super) for the full strategy, including how mid-term
    /// floor raises pull the cursor back.
    fn fetch_missing(&mut self, cause: View) -> Vec<Effect> {
        let mut effects = Vec::new();
        let mut cursor = self.fetch_floor.max(self.floor_view().next());
        while cursor < self.current_view {
            if self.covering_nullification(cursor).is_none() {
                effects.push(Effect::Fetch {
                    view: cursor,
                    cause,
                    reason: FetchReason::MissingNullification,
                });
            }
            cursor = cursor.next_term_start(self.term_length);
        }
        self.fetch_floor = cursor;
        effects
    }

    /// Prune stored certificates and requests that are not higher than the floor.
    fn prune(&mut self) -> Effect {
        let floor = self.floor_view();
        self.notarizations.retain(|view, _| *view > floor);
        let term_length = self.term_length;
        self.nullifications
            .retain(|view, _| covers_above_floor(*view, term_length, floor));

        // A floor inside a partially-fetched term strands the term's tail
        // (see the module docs). Pull the cursor back to just above the
        // floor so a later scan re-requests the tail (the cursor may exceed
        // the current view here, so an eager fetch could not).
        let next = floor.next();
        if !next.is_term_start(self.term_length) {
            self.fetch_floor = self.fetch_floor.min(next);
        }
        Effect::RetainAbove(floor)
    }
}

/// Returns whether a nullification at `view` covers any view above `floor`.
///
/// A nullification covers the rest of its term, so it remains relevant while
/// its term end is above the floor (even when the nullification itself is at
/// or below the floor). Admission (`handle`) and retention (`prune`) must
/// agree on this boundary.
fn covers_above_floor(view: View, term_length: TermLength, floor: View) -> bool {
    view.term_end(term_length) > floor
}

#[cfg(test)]
mod tests {
    use super::{super::test_helpers::*, *};
    use crate::{simplex::scheme::ed25519, types::Epoch};
    use commonware_cryptography::{certificate::mocks::Fixture, sha256::Digest as Sha256Digest};
    use commonware_utils::{NZU32, test_rng};
    use std::collections::BTreeSet;

    const NAMESPACE: &[u8] = b"resolver-state";
    const EPOCH: Epoch = Epoch::new(9);

    type TestScheme = ed25519::Scheme;

    fn ed25519_fixture() -> (Vec<TestScheme>, TestScheme) {
        let mut rng = test_rng();
        let Fixture {
            schemes, verifier, ..
        } = ed25519::fixture(&mut rng, NAMESPACE, 5);
        (schemes, verifier)
    }

    fn fetch(view: u64, cause: u64, reason: FetchReason) -> Effect {
        Effect::Fetch {
            view: View::new(view),
            cause: View::new(cause),
            reason,
        }
    }

    fn apply_effects(outstanding: &mut BTreeSet<View>, effects: &[Effect]) {
        for effect in effects {
            match *effect {
                Effect::Fetch { view, .. } => {
                    outstanding.insert(view);
                }
                Effect::RetainAbove(floor) => {
                    outstanding.retain(|view| *view > floor);
                }
            }
        }
    }

    fn outstanding_views(views: &BTreeSet<View>) -> Vec<u64> {
        views.iter().map(|view| view.get()).collect()
    }

    #[test]
    fn handle_nullification_requests_missing_views() {
        let (schemes, verifier) = ed25519_fixture();
        let mut state: State<TestScheme, Sha256Digest> = State::new(TermLength::ONE);
        let mut outstanding = BTreeSet::new();

        let nullification_v4 = build_nullification(&schemes, &verifier, EPOCH, View::new(4));
        let effects = state.handle(Certificate::Nullification(nullification_v4.clone()));
        assert_eq!(
            effects,
            vec![
                fetch(1, 4, FetchReason::MissingNullification),
                fetch(2, 4, FetchReason::MissingNullification),
                fetch(3, 4, FetchReason::MissingNullification),
            ]
        );
        apply_effects(&mut outstanding, &effects);
        assert_eq!(state.current_view, View::new(4));
        assert!(
            matches!(state.get(View::new(4)), Some(Certificate::Nullification(n)) if n == &nullification_v4)
        );
        assert_eq!(outstanding_views(&outstanding), vec![1, 2, 3]);

        let nullification_v2 = build_nullification(&schemes, &verifier, EPOCH, View::new(2));
        let effects = state.handle(Certificate::Nullification(nullification_v2.clone()));
        assert!(effects.is_empty());
        outstanding.remove(&View::new(2));
        apply_effects(&mut outstanding, &effects);
        assert_eq!(state.current_view, View::new(4));
        assert!(
            matches!(state.get(View::new(2)), Some(Certificate::Nullification(n)) if n == &nullification_v2)
        );
        assert_eq!(outstanding_views(&outstanding), vec![1, 3]);

        let nullification_v1 = build_nullification(&schemes, &verifier, EPOCH, View::new(1));
        let effects = state.handle(Certificate::Nullification(nullification_v1.clone()));
        assert!(effects.is_empty());
        outstanding.remove(&View::new(1));
        apply_effects(&mut outstanding, &effects);
        assert_eq!(state.current_view, View::new(4));
        assert!(
            matches!(state.get(View::new(1)), Some(Certificate::Nullification(n)) if n == &nullification_v1)
        );
        assert_eq!(outstanding_views(&outstanding), vec![3]);
    }

    #[test]
    fn fetch_requests_only_term_anchor_nullifications() {
        let (schemes, verifier) = ed25519_fixture();
        let mut state: State<TestScheme, Sha256Digest> = State::new(TermLength::new(NZU32!(5)));
        let mut outstanding = BTreeSet::new();

        let nullification_v14 = build_nullification(&schemes, &verifier, EPOCH, View::new(14));
        let effects = state.handle(Certificate::Nullification(nullification_v14));
        assert_eq!(
            effects,
            vec![
                fetch(1, 14, FetchReason::MissingNullification),
                fetch(6, 14, FetchReason::MissingNullification),
                fetch(11, 14, FetchReason::MissingNullification),
            ]
        );
        apply_effects(&mut outstanding, &effects);
        assert_eq!(outstanding_views(&outstanding), vec![1, 6, 11]);

        let nullification_v1 = build_nullification(&schemes, &verifier, EPOCH, View::new(1));
        let effects = state.handle(Certificate::Nullification(nullification_v1));
        outstanding.remove(&View::new(1));
        apply_effects(&mut outstanding, &effects);
        assert_eq!(outstanding_views(&outstanding), vec![6, 11]);

        let nullification_v6 = build_nullification(&schemes, &verifier, EPOCH, View::new(6));
        let effects = state.handle(Certificate::Nullification(nullification_v6));
        outstanding.remove(&View::new(6));
        apply_effects(&mut outstanding, &effects);
        assert_eq!(outstanding_views(&outstanding), vec![11]);
    }

    #[test]
    fn same_term_nullification_serves_later_views_until_pruned() {
        let (schemes, verifier) = ed25519_fixture();
        let mut state: State<TestScheme, Sha256Digest> = State::new(TermLength::new(NZU32!(5)));

        let nullification_v2 = build_nullification(&schemes, &verifier, EPOCH, View::new(2));
        state.handle(Certificate::Nullification(nullification_v2.clone()));

        assert!(
            matches!(state.get(View::new(2)), Some(Certificate::Nullification(n)) if n == &nullification_v2)
        );
        assert!(
            matches!(state.get(View::new(5)), Some(Certificate::Nullification(n)) if n == &nullification_v2)
        );
        assert!(state.get(View::new(6)).is_none());

        let finalization_v3 = build_finalization(&schemes, &verifier, EPOCH, View::new(3));
        state.handle(Certificate::Finalization(finalization_v3));
        assert_eq!(state.nullifications.len(), 1);
        assert!(
            matches!(state.get(View::new(4)), Some(Certificate::Nullification(n)) if n == &nullification_v2)
        );

        let finalization_v5 = build_finalization(&schemes, &verifier, EPOCH, View::new(5));
        state.handle(Certificate::Finalization(finalization_v5));
        assert!(state.nullifications.is_empty());
    }

    #[test]
    fn nullification_below_floor_can_cover_unresolved_term_views() {
        let (schemes, verifier) = ed25519_fixture();
        let mut state: State<TestScheme, Sha256Digest> = State::new(TermLength::new(NZU32!(5)));
        let mut outstanding = BTreeSet::new();

        let finalization_v3 = build_finalization(&schemes, &verifier, EPOCH, View::new(3));
        let effects = state.handle(Certificate::Finalization(finalization_v3));
        apply_effects(&mut outstanding, &effects);

        let nullification_v6 = build_nullification(&schemes, &verifier, EPOCH, View::new(6));
        let effects = state.handle(Certificate::Nullification(nullification_v6));
        apply_effects(&mut outstanding, &effects);
        assert_eq!(outstanding_views(&outstanding), vec![4]);

        let nullification_v2 = build_nullification(&schemes, &verifier, EPOCH, View::new(2));
        let effects = state.handle(Certificate::Nullification(nullification_v2.clone()));
        outstanding.remove(&View::new(4));
        apply_effects(&mut outstanding, &effects);

        assert!(outstanding.is_empty());
        assert!(
            matches!(state.get(View::new(4)), Some(Certificate::Nullification(n)) if n == &nullification_v2)
        );
        assert!(
            matches!(state.get(View::new(5)), Some(Certificate::Nullification(n)) if n == &nullification_v2)
        );
    }

    #[test]
    fn nullification_admission_matches_pruning_boundary() {
        let (schemes, verifier) = ed25519_fixture();
        let mut state: State<TestScheme, Sha256Digest> = State::new(TermLength::new(NZU32!(5)));

        let finalization_v3 = build_finalization(&schemes, &verifier, EPOCH, View::new(3));
        let effects = state.handle(Certificate::Finalization(finalization_v3));
        assert_eq!(effects, vec![Effect::RetainAbove(View::new(3))]);

        let nullification_v2 = build_nullification(&schemes, &verifier, EPOCH, View::new(2));
        let effects = state.handle(Certificate::Nullification(nullification_v2.clone()));
        assert!(effects.is_empty());
        assert!(
            matches!(state.get(View::new(4)), Some(Certificate::Nullification(n)) if n == &nullification_v2)
        );

        let finalization_v5 = build_finalization(&schemes, &verifier, EPOCH, View::new(5));
        let effects = state.handle(Certificate::Finalization(finalization_v5));
        assert_eq!(effects, vec![Effect::RetainAbove(View::new(5))]);
        assert!(state.nullifications.is_empty());

        let effects = state.handle(Certificate::Nullification(nullification_v2));
        assert!(effects.is_empty());
        assert!(state.nullifications.is_empty());
    }

    #[test]
    fn floor_prunes_outstanding_requests() {
        let (schemes, verifier) = ed25519_fixture();
        let mut state: State<TestScheme, Sha256Digest> = State::new(TermLength::ONE);
        let mut outstanding = BTreeSet::new();

        for view in 4..=6 {
            let nullification = build_nullification(&schemes, &verifier, EPOCH, View::new(view));
            let effects = state.handle(Certificate::Nullification(nullification));
            apply_effects(&mut outstanding, &effects);
        }
        assert_eq!(state.current_view, View::new(6));
        assert_eq!(outstanding_views(&outstanding), vec![1, 2, 3]);

        let notarization = build_notarization(&schemes, &verifier, EPOCH, View::new(6));
        let effects = state.handle(Certificate::Notarization(notarization));
        apply_effects(&mut outstanding, &effects);
        assert!(state.floor.is_none());
        assert_eq!(state.nullifications.len(), 3);
        assert_eq!(outstanding_views(&outstanding), vec![1, 2, 3]);

        let finalization = build_finalization(&schemes, &verifier, EPOCH, View::new(6));
        let effects = state.handle(Certificate::Finalization(finalization.clone()));
        assert_eq!(effects, vec![Effect::RetainAbove(View::new(6))]);
        apply_effects(&mut outstanding, &effects);
        assert!(
            matches!(state.floor.as_ref(), Some(Certificate::Finalization(f)) if f == &finalization)
        );
        assert!(state.notarizations.is_empty());
        assert!(state.nullifications.is_empty());
        assert!(outstanding.is_empty());
    }

    #[test]
    fn produce_returns_floor_or_nullifications() {
        let (schemes, verifier) = ed25519_fixture();
        let mut state: State<TestScheme, Sha256Digest> = State::new(TermLength::ONE);

        let finalization = build_finalization(&schemes, &verifier, EPOCH, View::new(3));
        let effects = state.handle(Certificate::Finalization(finalization.clone()));
        assert_eq!(effects, vec![Effect::RetainAbove(View::new(3))]);
        assert!(
            matches!(state.get(View::new(1)), Some(Certificate::Finalization(f)) if f == &finalization)
        );
        assert!(
            matches!(state.get(View::new(3)), Some(Certificate::Finalization(f)) if f == &finalization)
        );

        let nullification_v4 = build_nullification(&schemes, &verifier, EPOCH, View::new(4));
        let effects = state.handle(Certificate::Nullification(nullification_v4.clone()));
        assert!(effects.is_empty());
        assert!(
            matches!(state.get(View::new(4)), Some(Certificate::Nullification(n)) if n == &nullification_v4)
        );
        assert!(
            matches!(state.get(View::new(2)), Some(Certificate::Finalization(f)) if f == &finalization)
        );

        let nullification_v1 = build_nullification(&schemes, &verifier, EPOCH, View::new(1));
        let effects = state.handle(Certificate::Nullification(nullification_v1));
        assert!(effects.is_empty());
        assert!(
            matches!(state.get(View::new(1)), Some(Certificate::Finalization(f)) if f == &finalization)
        );
        assert!(
            matches!(state.get(View::new(2)), Some(Certificate::Finalization(f)) if f == &finalization)
        );
        assert!(
            matches!(state.get(View::new(3)), Some(Certificate::Finalization(f)) if f == &finalization)
        );
        assert!(
            matches!(state.get(View::new(4)), Some(Certificate::Nullification(n)) if n == &nullification_v4)
        );
    }

    #[test]
    fn produce_tracks_preferred_ancestry_when_certificates_coexist() {
        let (schemes, verifier) = ed25519_fixture();
        let mut state: State<TestScheme, Sha256Digest> = State::new(TermLength::ONE);
        let view = View::new(3);

        // Before the notarization certifies, a leader can only justify
        // skipping this view with its nullification.
        let nullification = build_nullification(&schemes, &verifier, EPOCH, view);
        state.handle(Certificate::Nullification(nullification.clone()));
        assert!(
            matches!(state.get(view), Some(Certificate::Nullification(n)) if n == &nullification)
        );

        // If certification completes after that decision, serving the
        // certified floor matches the leader's newly preferred ancestry.
        let notarization = build_notarization(&schemes, &verifier, EPOCH, view);
        state.handle(Certificate::Notarization(notarization.clone()));
        state.handle_certified(view, true);
        assert!(
            matches!(state.get(view), Some(Certificate::Notarization(n)) if n == &notarization)
        );
    }

    #[test]
    fn certification_failure_re_requests_failed_view() {
        let (schemes, verifier) = ed25519_fixture();
        let mut state: State<TestScheme, Sha256Digest> = State::new(TermLength::ONE);

        // Handling a notarization requests the missing nullifications below it
        let notarization_v5 = build_notarization(&schemes, &verifier, EPOCH, View::new(5));
        let effects = state.handle(Certificate::Notarization(notarization_v5));
        assert_eq!(
            effects,
            vec![
                fetch(1, 5, FetchReason::MissingNullification),
                fetch(2, 5, FetchReason::MissingNullification),
                fetch(3, 5, FetchReason::MissingNullification),
                fetch(4, 5, FetchReason::MissingNullification),
            ]
        );

        // Certification fails for view 5
        let effects = state.handle_certified(View::new(5), false);

        // Only the failed view gets a new background request. Requests
        // answered by the failed notarization are retried by the resolver
        // engine.
        assert_eq!(effects, vec![fetch(5, 5, FetchReason::CertificationFailed)]);
    }

    #[test]
    fn certification_success_sets_floor() {
        let (schemes, verifier) = ed25519_fixture();
        let mut state: State<TestScheme, Sha256Digest> = State::new(TermLength::ONE);

        // Handling a notarization requests the missing nullifications below it
        let notarization_v5 = build_notarization(&schemes, &verifier, EPOCH, View::new(5));
        let effects = state.handle(Certificate::Notarization(notarization_v5.clone()));
        assert_eq!(
            effects,
            vec![
                fetch(1, 5, FetchReason::MissingNullification),
                fetch(2, 5, FetchReason::MissingNullification),
                fetch(3, 5, FetchReason::MissingNullification),
                fetch(4, 5, FetchReason::MissingNullification),
            ]
        );

        // Certification succeeds for view 5
        let effects = state.handle_certified(View::new(5), true);

        // The certified notarization becomes the floor
        assert!(
            matches!(state.floor.as_ref(), Some(Certificate::Notarization(n)) if n == &notarization_v5)
        );
        assert_eq!(effects, vec![Effect::RetainAbove(View::new(5))]);
    }

    #[test]
    fn certification_success_preserves_remaining_anchor_requests() {
        let (schemes, verifier) = ed25519_fixture();
        let mut state: State<TestScheme, Sha256Digest> = State::new(TermLength::new(NZU32!(5)));
        let mut outstanding = BTreeSet::new();

        let nullification_v14 = build_nullification(&schemes, &verifier, EPOCH, View::new(14));
        let effects = state.handle(Certificate::Nullification(nullification_v14));
        apply_effects(&mut outstanding, &effects);
        assert_eq!(outstanding_views(&outstanding), vec![1, 6, 11]);

        // The notarization does not duplicate any outstanding anchor while
        // certification is pending.
        let notarization_v5 = build_notarization(&schemes, &verifier, EPOCH, View::new(5));
        let effects = state.handle(Certificate::Notarization(notarization_v5.clone()));
        assert!(effects.is_empty());
        apply_effects(&mut outstanding, &effects);
        assert_eq!(outstanding_views(&outstanding), vec![1, 6, 11]);

        // Certification raises the floor past anchor 1 and leaves the higher
        // anchor requests pending.
        let effects = state.handle_certified(View::new(5), true);
        apply_effects(&mut outstanding, &effects);

        assert!(
            matches!(state.floor.as_ref(), Some(Certificate::Notarization(n)) if n == &notarization_v5)
        );
        assert_eq!(state.current_view, View::new(14));
        assert_eq!(outstanding_views(&outstanding), vec![6, 11]);
    }

    #[test]
    fn certification_success_at_mid_term_floor_refetches_term_tail() {
        let (schemes, verifier) = ed25519_fixture();
        let mut state: State<TestScheme, Sha256Digest> = State::new(TermLength::new(NZU32!(5)));
        let mut outstanding = BTreeSet::new();

        let nullification_v14 = build_nullification(&schemes, &verifier, EPOCH, View::new(14));
        let effects = state.handle(Certificate::Nullification(nullification_v14));
        apply_effects(&mut outstanding, &effects);
        assert_eq!(outstanding_views(&outstanding), vec![1, 6, 11]);

        // A mid-term notarization answers the request for anchor 1, but once
        // certified it only covers views 1..=3 of term [1, 5].
        let notarization_v3 = build_notarization(&schemes, &verifier, EPOCH, View::new(3));
        let effects = state.handle(Certificate::Notarization(notarization_v3.clone()));
        apply_effects(&mut outstanding, &effects);
        assert_eq!(outstanding_views(&outstanding), vec![1, 6, 11]);

        // Certification raises the floor to 3 and prunes the anchor-1 request.
        // Views 4-5 still need a covering nullification, which only a request
        // at a view in [4, 5] can retrieve (the outstanding requests at 6 and
        // 11 accept nothing from term [1, 5]), so the fetch scan must resume
        // from just above the mid-term floor rather than from the cursor.
        let effects = state.handle_certified(View::new(3), true);
        apply_effects(&mut outstanding, &effects);
        assert!(
            matches!(state.floor.as_ref(), Some(Certificate::Notarization(n)) if n == &notarization_v3)
        );
        assert_eq!(outstanding_views(&outstanding), vec![4, 6, 11]);
    }

    #[test]
    fn mid_term_floor_at_current_view_refetches_term_tail_later() {
        let (schemes, verifier) = ed25519_fixture();
        let mut state: State<TestScheme, Sha256Digest> = State::new(TermLength::new(NZU32!(5)));
        let mut outstanding = BTreeSet::new();

        // A gossiped notarization at view 4 is the highest view seen: the
        // fetch scan requests anchor 1, and the cursor jumps past the
        // current view to the next term anchor.
        let notarization_v4 = build_notarization(&schemes, &verifier, EPOCH, View::new(4));
        let effects = state.handle(Certificate::Notarization(notarization_v4.clone()));
        apply_effects(&mut outstanding, &effects);
        assert_eq!(outstanding_views(&outstanding), vec![1]);

        // Certification raises the floor to 4 (the current view itself),
        // mid-term of [1, 5]. The anchor-1 request is pruned and no view
        // above the floor is below the current view yet, so nothing can be
        // fetched here.
        let effects = state.handle_certified(View::new(4), true);
        apply_effects(&mut outstanding, &effects);
        assert!(
            matches!(state.floor.as_ref(), Some(Certificate::Notarization(n)) if n == &notarization_v4)
        );
        assert!(outstanding_views(&outstanding).is_empty());

        // Once the current view grows, the scan must resume from just above
        // the mid-term floor: view 5 is only coverable by a nullification
        // from term [1, 5], which the requests at anchors 6 and 11 reject.
        let nullification_v14 = build_nullification(&schemes, &verifier, EPOCH, View::new(14));
        let effects = state.handle(Certificate::Nullification(nullification_v14));
        apply_effects(&mut outstanding, &effects);
        assert_eq!(outstanding_views(&outstanding), vec![5, 6, 11]);
    }

    #[test]
    fn fetch_requests_each_anchor_once() {
        let (schemes, verifier) = ed25519_fixture();
        let mut state: State<TestScheme, Sha256Digest> = State::new(TermLength::new(NZU32!(5)));

        let nullification_v14 = build_nullification(&schemes, &verifier, EPOCH, View::new(14));
        let effects = state.handle(Certificate::Nullification(nullification_v14));
        assert_eq!(
            effects,
            vec![
                fetch(1, 14, FetchReason::MissingNullification),
                fetch(6, 14, FetchReason::MissingNullification),
                fetch(11, 14, FetchReason::MissingNullification),
            ]
        );

        // A notarization satisfying the request for anchor 1 must not trigger
        // a re-request of anchor 1 while its certification is pending, no
        // matter how many times it is delivered.
        let notarization_v5 = build_notarization(&schemes, &verifier, EPOCH, View::new(5));
        for _ in 0..3 {
            let effects = state.handle(Certificate::Notarization(notarization_v5.clone()));
            assert!(effects.is_empty(), "anchor re-requested: {effects:?}");
        }

        // A later certificate must only request newly-uncovered anchors, not
        // re-issue the outstanding ones (the p2p resolver owns retries).
        let nullification_v20 = build_nullification(&schemes, &verifier, EPOCH, View::new(20));
        let effects = state.handle(Certificate::Nullification(nullification_v20));
        assert_eq!(
            effects,
            vec![fetch(16, 20, FetchReason::MissingNullification)]
        );
    }

    #[test]
    fn certification_failure_skips_covered_re_requests() {
        let (schemes, verifier) = ed25519_fixture();
        let mut state: State<TestScheme, Sha256Digest> = State::new(TermLength::new(NZU32!(5)));

        let nullification_v14 = build_nullification(&schemes, &verifier, EPOCH, View::new(14));
        state.handle(Certificate::Nullification(nullification_v14));

        let notarization_v5 = build_notarization(&schemes, &verifier, EPOCH, View::new(5));
        state.handle(Certificate::Notarization(notarization_v5));

        // A nullification at view 1 covers the whole term [1, 5], so the
        // failed view needs no re-request.
        let nullification_v1 = build_nullification(&schemes, &verifier, EPOCH, View::new(1));
        state.handle(Certificate::Nullification(nullification_v1));

        let effects = state.handle_certified(View::new(5), false);
        assert!(effects.is_empty());
    }

    #[test]
    fn finalization_upgrades_certified_notarization_at_same_view() {
        let (schemes, verifier) = ed25519_fixture();
        let mut state: State<TestScheme, Sha256Digest> = State::new(TermLength::ONE);

        let notarization_v5 = build_notarization(&schemes, &verifier, EPOCH, View::new(5));
        let effects = state.handle(Certificate::Notarization(notarization_v5.clone()));
        assert_eq!(
            effects,
            vec![
                fetch(1, 5, FetchReason::MissingNullification),
                fetch(2, 5, FetchReason::MissingNullification),
                fetch(3, 5, FetchReason::MissingNullification),
                fetch(4, 5, FetchReason::MissingNullification),
            ]
        );
        let effects = state.handle_certified(View::new(5), true);
        assert_eq!(effects, vec![Effect::RetainAbove(View::new(5))]);

        assert!(
            matches!(state.floor.as_ref(), Some(Certificate::Notarization(n)) if n == &notarization_v5)
        );
        assert_eq!(state.floor_view(), View::new(5));

        let finalization_v5 = build_finalization(&schemes, &verifier, EPOCH, View::new(5));
        let effects = state.handle(Certificate::Finalization(finalization_v5.clone()));

        assert!(
            matches!(state.floor.as_ref(), Some(Certificate::Finalization(f)) if f == &finalization_v5)
        );
        assert_eq!(effects, vec![Effect::RetainAbove(View::new(5))]);
    }
}