commonware-consensus 2026.10.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
use crate::{
    marshal::resolver::handler::{Annotation, Key, Request},
    simplex::types::Finalization,
    types::{Epoch, Epocher, Height, Round},
};
use commonware_cryptography::{Digest, certificate::Scheme};
use commonware_resolver::{Resolver, TargetedResolver};
use commonware_utils::{futures::Aborter, vec::NonEmptyVec};
use std::{
    cmp::Ordering,
    fmt::{self, Display, Formatter},
};

/// Marshal's durable processed height and the stored block that backs it.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Processed {
    /// The block at this height is processed and stored.
    Block(Height),
    /// This height is processed but its block is not stored. A floor was installed at the next
    /// height, and the floor block backs this position.
    Absent(Height),
}

impl Processed {
    /// Returns the processed height.
    pub const fn height(self) -> Height {
        match self {
            Self::Block(height) | Self::Absent(height) => height,
        }
    }

    /// Returns the height of the stored block that backs the processed height.
    pub const fn anchor(self) -> Height {
        match self {
            Self::Block(height) => height,
            Self::Absent(height) => height.next(),
        }
    }
}

/// An inclusive bound on finalization rounds: a round, or the end of an epoch.
///
/// Cutoffs are ordered by the rounds they cover. A cutoff in an earlier epoch sits below one in a
/// later epoch, and within one epoch [`Self::Epoch`] sits above every [`Self::Round`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Cutoff {
    /// Covers this round and every earlier round.
    Round(Round),
    /// Covers every round of this epoch and of every earlier epoch.
    Epoch(Epoch),
}

impl Cutoff {
    /// Returns the cutoff that covers only the zero round.
    pub const fn zero() -> Self {
        Self::Round(Round::zero())
    }

    /// Returns true if `round` is at or below the cutoff, that is, if
    /// `self >= Cutoff::Round(round)`.
    pub const fn covers(&self, round: Round) -> bool {
        match *self {
            Self::Round(last) => {
                round.epoch().get() < last.epoch().get()
                    || (round.epoch().get() == last.epoch().get()
                        && round.view().get() <= last.view().get())
            }
            Self::Epoch(epoch) => round.epoch().get() <= epoch.get(),
        }
    }
}

impl Ord for Cutoff {
    fn cmp(&self, other: &Self) -> Ordering {
        match (*self, *other) {
            (Self::Round(a), Self::Round(b)) => a.cmp(&b),
            (Self::Epoch(a), Self::Epoch(b)) => a.cmp(&b),
            (Self::Round(a), Self::Epoch(b)) => a.epoch().cmp(&b).then(Ordering::Less),
            (Self::Epoch(a), Self::Round(b)) => a.cmp(&b.epoch()).then(Ordering::Greater),
        }
    }
}

impl PartialOrd for Cutoff {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Display for Cutoff {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Round(round) => Display::fmt(round, f),
            Self::Epoch(epoch) => Display::fmt(epoch, f),
        }
    }
}

/// Durable height and round bounds restored when marshal initializes.
///
/// The components are independent retention bounds and need not identify the
/// same finalization.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Floor {
    processed: Option<Processed>,
    cutoff: Cutoff,
}

impl Floor {
    /// Creates a floor from its independent processed position and round floor.
    pub(super) const fn new(processed: Option<Processed>, cutoff: Cutoff) -> Self {
        Self { processed, cutoff }
    }

    /// Returns the latest durably processed position, if any.
    pub const fn processed(&self) -> Option<Processed> {
        self.processed
    }

    /// Returns the durable round floor.
    ///
    /// Every finalization at a covered round names a block at or below the processed height, or
    /// the stored block just above it.
    pub const fn cutoff(&self) -> Cutoff {
        self.cutoff
    }
}

/// Returns the newest epoch whose last block is at or below `anchor`, or `None` when no epoch
/// ends at or below `anchor` or `epocher` cannot place `anchor`.
///
/// Verification requires every proposal, re-proposals included, to carry a block of its own epoch.
/// [`Epocher`] requires `epocher` to place every height as the validators do. So every
/// finalization an honest quorum produces in the returned epoch or an earlier one names a block at
/// or below `anchor`.
pub(super) fn closed_epoch<E: Epocher>(epocher: &E, anchor: Height) -> Option<Epoch> {
    let info = epocher.containing(anchor)?;
    if info.last() == anchor {
        Some(info.epoch())
    } else {
        info.epoch().previous()
    }
}

/// A floor finalization awaiting its anchor block.
///
/// Dropping the pending floor aborts its buffer waiter, if one exists.
struct Pending<S: Scheme, C: Digest> {
    finalization: Finalization<S, C>,
    _aborter: Option<Aborter>,
}

/// Durable floor state, the configured floor until startup takes it, and any update
/// awaiting its anchor block.
///
/// The processed position and the round floor mirror the stream metadata. The arm that raises
/// one syncs the stream before the actor handles its next event, so the value here is durable
/// whenever another arm or a mailbox caller reads it.
pub(super) struct State<S: Scheme, C: Digest> {
    /// The durable processed position, if any.
    processed: Option<Processed>,
    /// The durable round floor. Start restores it from the stream metadata or derives a higher
    /// one from the archives and the epocher.
    cutoff: Cutoff,
    /// The newest finalization round witnessed for a processed block or an installed floor anchor.
    /// Start restores it from the archives, including the finalization of a block stored just
    /// above the processed height. Cache retention follows this round because a round floor that
    /// covers a whole epoch has no view to measure retention from.
    witnessed: Round,
    /// The configured floor until startup takes it.
    configured: Option<Finalization<S, C>>,
    /// A floor finalization awaiting its anchor block.
    pending: Option<Pending<S, C>>,
}

impl<S: Scheme, C: Digest> State<S, C> {
    /// Creates floor state from the configured floor, if any, the restored floor, and the newest
    /// finalization round recovered from the archives.
    pub(super) const fn new(
        configured: Option<Finalization<S, C>>,
        floor: Floor,
        witnessed: Round,
    ) -> Self {
        Self {
            processed: floor.processed,
            cutoff: floor.cutoff,
            witnessed,
            configured,
            pending: None,
        }
    }

    /// Takes the configured floor, if any.
    #[must_use]
    pub(super) const fn take_configured(&mut self) -> Option<Finalization<S, C>> {
        self.configured.take()
    }

    /// Returns the durable floor, without the configured or pending floor.
    pub(super) const fn snapshot(&self) -> Floor {
        Floor::new(self.processed, self.cutoff)
    }

    /// Returns the durable processed position, if any.
    pub(super) const fn processed(&self) -> Option<Processed> {
        self.processed
    }

    /// Returns the inclusive height floor. Finalized blocks at or below it are
    /// neither stored nor repaired.
    ///
    /// Nothing processed maps to zero because height zero is genesis, which is
    /// anchored at startup or sits below a floor anchor and never carries a
    /// finalization. Delivery uses the stream cursor, which keeps that state
    /// distinct.
    pub(super) const fn processed_height(&self) -> Height {
        match self.processed {
            Some(processed) => processed.height(),
            None => Height::zero(),
        }
    }

    /// Returns the durable round floor.
    pub(super) const fn cutoff(&self) -> Cutoff {
        self.cutoff
    }

    /// Returns the newest witnessed finalization round.
    pub(super) const fn witnessed(&self) -> Round {
        self.witnessed
    }

    /// Sets the processed position. The caller buffers the same height in the stream metadata and
    /// syncs the stream before the actor handles its next event.
    pub(super) const fn set_processed(&mut self, processed: Processed) {
        self.processed = Some(processed);
    }

    /// Sets the round floor. The caller buffers the same cutoff in the stream metadata and syncs
    /// the stream before the actor handles its next event.
    pub(super) const fn set_cutoff(&mut self, cutoff: Cutoff) {
        self.cutoff = cutoff;
    }

    /// Records `round` as the newest witnessed finalization round and returns the previous one,
    /// or `None` when `round` is not newer.
    #[must_use]
    pub(super) fn witness(&mut self, round: Round) -> Option<Round> {
        if round <= self.witnessed {
            return None;
        }
        let previous = self.witnessed;
        self.witnessed = round;
        Some(previous)
    }

    /// Returns true while repair and application dispatch must wait for the floor anchor.
    pub(super) const fn blocks_progress(&self) -> bool {
        self.pending.is_some()
    }

    /// Returns the pending floor, if one awaits its anchor block.
    pub(super) fn pending(&self) -> Option<&Finalization<S, C>> {
        self.pending.as_ref().map(|pending| &pending.finalization)
    }

    /// Drops the pending floor and aborts any buffer waiter it holds.
    pub(super) fn clear_pending(&mut self) {
        self.pending = None;
    }

    /// Records a verified floor finalization whose block anchor still needs to arrive.
    ///
    /// Taking or replacing the pending floor drops `aborter`, which aborts its
    /// buffer waiter.
    pub(super) fn set_pending(
        &mut self,
        finalization: Finalization<S, C>,
        aborter: Option<Aborter>,
    ) {
        self.pending = Some(Pending {
            finalization,
            _aborter: aborter,
        });
    }

    /// Takes the pending floor if `commitment` is its payload.
    #[must_use]
    pub(super) fn take_matching(&mut self, commitment: C) -> Option<Finalization<S, C>> {
        self.pending
            .take_if(|pending| pending.finalization.proposal.payload == commitment)
            .map(|pending| pending.finalization)
    }

    /// Returns true when the resolver request is above all processed floors.
    fn permits(&self, fetch: &Request<C>) -> bool {
        if let Some(processed) = self.processed
            && !fetch.above_height_floor(processed.height())
        {
            return false;
        }

        fetch.above_round_floor(self.cutoff)
    }

    pub(super) fn fetch_if_permitted<R>(
        &self,
        resolver: &mut R,
        fetch: Request<C>,
    ) -> FetchAdmission
    where
        R: Resolver<Key = Key<C>, Subscriber = Annotation>,
    {
        if !self.permits(&fetch) {
            return FetchAdmission::Denied;
        }
        resolver.fetch(fetch);
        FetchAdmission::Issued
    }

    pub(super) fn fetch_targeted_if_permitted<R>(
        &self,
        resolver: &mut R,
        fetch: Request<C>,
        targets: NonEmptyVec<R::PublicKey>,
    ) -> FetchAdmission
    where
        R: TargetedResolver<Key = Key<C>, Subscriber = Annotation>,
    {
        if !self.permits(&fetch) {
            return FetchAdmission::Denied;
        }
        resolver.fetch_targeted(fetch, targets);
        FetchAdmission::Issued
    }

    pub(super) fn fetch_all_if_permitted<R>(
        &self,
        resolver: &mut R,
        fetches: Vec<Request<C>>,
    ) -> FetchAdmission
    where
        R: Resolver<Key = Key<C>, Subscriber = Annotation>,
    {
        let fetches = fetches
            .into_iter()
            .filter(|fetch| self.permits(fetch))
            .collect::<Vec<_>>();
        if fetches.is_empty() {
            return FetchAdmission::Denied;
        }
        resolver.fetch_all(fetches);
        FetchAdmission::Issued
    }
}

/// Whether floor admission issued at least one resolver fetch.
#[must_use = "fetch admission must be handled explicitly"]
pub(super) enum FetchAdmission {
    Issued,
    Denied,
}

impl FetchAdmission {
    pub(super) const fn ignore(self) {}
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        marshal::resolver::handler::Finalized,
        simplex::scheme::ed25519 as simplex_ed25519,
        types::{FixedEpocher, View},
    };
    use commonware_actor::Feedback;
    use commonware_cryptography::{Signer as _, ed25519 as crypto_ed25519, sha256::Sha256};
    use commonware_math::algebra::Random as _;
    use commonware_resolver::Fetch;
    use commonware_utils::{NZU64, sync::Mutex};
    use std::sync::Arc;

    type TestDigest = <Sha256 as commonware_cryptography::Hasher>::Digest;
    type TestScheme = simplex_ed25519::Scheme;
    type FetchRecord = Fetch<Key<TestDigest>, Annotation>;
    type RecordedFetches = Arc<Mutex<Vec<FetchRecord>>>;
    type RecordedTargets = Arc<Mutex<Vec<Key<TestDigest>>>>;

    #[derive(Clone, Default)]
    struct TestResolver {
        fetches: RecordedFetches,
        targeted: RecordedTargets,
    }

    impl TestResolver {
        fn fetches(&self) -> Vec<FetchRecord> {
            self.fetches.lock().clone()
        }

        fn targeted(&self) -> Vec<Key<TestDigest>> {
            self.targeted.lock().clone()
        }
    }

    impl Resolver for TestResolver {
        type Key = Key<TestDigest>;
        type Subscriber = Annotation;

        fn fetch<F>(&mut self, fetch: F) -> Feedback
        where
            F: Into<Fetch<Self::Key, Self::Subscriber>> + Send,
        {
            self.fetches.lock().push(fetch.into());
            Feedback::Ok
        }

        fn fetch_all<F>(&mut self, fetches: Vec<F>) -> Feedback
        where
            F: Into<Fetch<Self::Key, Self::Subscriber>> + Send,
        {
            self.fetches
                .lock()
                .extend(fetches.into_iter().map(Into::into));
            Feedback::Ok
        }

        fn retain(
            &mut self,
            _predicate: impl Fn(&Self::Key, &Self::Subscriber) -> bool + Send + 'static,
        ) -> Feedback {
            Feedback::Ok
        }
    }

    impl TargetedResolver for TestResolver {
        type PublicKey = crypto_ed25519::PublicKey;

        fn fetch_targeted(
            &mut self,
            fetch: impl Into<Fetch<Self::Key, Self::Subscriber>> + Send,
            _targets: NonEmptyVec<Self::PublicKey>,
        ) -> Feedback {
            self.targeted.lock().push(fetch.into().key);
            Feedback::Ok
        }

        fn fetch_all_targeted<F>(
            &mut self,
            fetches: Vec<(F, NonEmptyVec<Self::PublicKey>)>,
        ) -> Feedback
        where
            F: Into<Fetch<Self::Key, Self::Subscriber>> + Send,
        {
            self.targeted
                .lock()
                .extend(fetches.into_iter().map(|(fetch, _)| fetch.into().key));
            Feedback::Ok
        }
    }

    fn round(view: u64) -> Round {
        Round::new(Epoch::zero(), View::new(view))
    }

    fn digest(byte: u8) -> TestDigest {
        Sha256::fill(byte)
    }

    #[test]
    fn cutoff_orders_by_covered_rounds() {
        let epoch = Epoch::new(3);
        let last_view = Cutoff::Round(Round::new(epoch, View::new(u64::MAX)));
        let next_first = Cutoff::Round(Round::new(epoch.next(), View::zero()));

        // An epoch cutoff sits above every round of its epoch and below the next epoch.
        assert!(Cutoff::Epoch(epoch) > last_view);
        assert!(Cutoff::Epoch(epoch) < next_first);
        assert!(Cutoff::Epoch(epoch) > Cutoff::Round(Round::zero()));
        assert!(Cutoff::Epoch(Epoch::zero()) > Cutoff::zero());

        // Cutoffs of one kind follow their round or epoch order.
        assert!(last_view > Cutoff::Round(Round::new(epoch, View::new(7))));
        assert!(Cutoff::Epoch(epoch) < Cutoff::Epoch(epoch.next()));
        assert_eq!(
            Cutoff::Epoch(epoch).cmp(&Cutoff::Epoch(epoch)),
            Ordering::Equal
        );
        assert_eq!(Cutoff::Epoch(epoch).max(last_view), Cutoff::Epoch(epoch));
        assert_eq!(Cutoff::Epoch(epoch).max(next_first), next_first);
    }

    #[test]
    fn cutoff_covers_matches_its_order() {
        let epoch = Epoch::new(3);
        let at_round = Cutoff::Round(Round::new(epoch, View::new(10)));
        let whole_epoch = Cutoff::Epoch(epoch);
        let rounds = [
            Round::zero(),
            Round::new(
                epoch.previous().expect("epoch must have a predecessor"),
                View::new(u64::MAX),
            ),
            Round::new(epoch, View::zero()),
            Round::new(epoch, View::new(10)),
            Round::new(epoch, View::new(11)),
            Round::new(epoch, View::new(u64::MAX)),
            Round::new(epoch.next(), View::zero()),
        ];

        // A round cutoff covers its round and every earlier round.
        assert!(at_round.covers(Round::new(epoch, View::new(10))));
        assert!(!at_round.covers(Round::new(epoch, View::new(11))));
        assert!(at_round.covers(Round::new(Epoch::zero(), View::new(u64::MAX))));

        // An epoch cutoff covers every view of its epoch and nothing of the next epoch.
        assert!(whole_epoch.covers(Round::new(epoch, View::new(u64::MAX))));
        assert!(!whole_epoch.covers(Round::new(epoch.next(), View::zero())));

        // The zero cutoff covers only the zero round.
        assert!(Cutoff::zero().covers(Round::zero()));
        assert!(!Cutoff::zero().covers(Round::new(Epoch::zero(), View::new(1))));

        // Coverage equals the order against a round cutoff.
        for cutoff in [Cutoff::zero(), at_round, whole_epoch] {
            for round in rounds {
                assert_eq!(cutoff.covers(round), cutoff >= Cutoff::Round(round));
            }
        }
    }

    #[test]
    fn fetch_if_permitted_denies_covered_epoch_and_admits_the_next() {
        let floor = State::<TestScheme, TestDigest>::new(
            None,
            Floor::new(
                Some(Processed::Block(Height::new(10))),
                Cutoff::Epoch(Epoch::zero()),
            ),
            round(10),
        );
        let mut resolver = TestResolver::default();

        // Every round of the covered epoch is denied, including its last view.
        assert!(matches!(
            floor.fetch_if_permitted(&mut resolver, Request::notarized(round(40))),
            FetchAdmission::Denied
        ));
        assert!(matches!(
            floor.fetch_if_permitted(&mut resolver, Request::notarized(round(u64::MAX))),
            FetchAdmission::Denied
        ));
        assert!(matches!(
            floor.fetch_if_permitted(
                &mut resolver,
                Request::finalized_by_round(digest(1), round(40)),
            ),
            FetchAdmission::Denied
        ));
        assert!(resolver.fetches().is_empty());

        // The next epoch's first round and height-bound requests above the floor are admitted.
        let next = Round::new(Epoch::new(1), View::zero());
        assert!(matches!(
            floor.fetch_if_permitted(&mut resolver, Request::notarized(next)),
            FetchAdmission::Issued
        ));
        assert!(matches!(
            floor.fetch_if_permitted(&mut resolver, Request::finalized(Height::new(11))),
            FetchAdmission::Issued
        ));
        assert_eq!(resolver.fetches().len(), 2);
    }

    #[test]
    fn closed_epoch_returns_ended_epochs_only() {
        let epocher = FixedEpocher::new(NZU64!(11));

        // Epoch zero ends at height 10. An anchor inside it closes nothing.
        assert_eq!(closed_epoch(&epocher, Height::zero()), None);
        assert_eq!(closed_epoch(&epocher, Height::new(9)), None);
        assert_eq!(closed_epoch(&epocher, Height::new(10)), Some(Epoch::zero()));

        // An anchor inside epoch one closes epoch zero, and its last block closes epoch one.
        assert_eq!(closed_epoch(&epocher, Height::new(11)), Some(Epoch::zero()));
        assert_eq!(closed_epoch(&epocher, Height::new(20)), Some(Epoch::zero()));
        assert_eq!(closed_epoch(&epocher, Height::new(21)), Some(Epoch::new(1)));

        // Heights the epocher cannot place close nothing.
        assert_eq!(closed_epoch(&epocher, Height::new(u64::MAX)), None);
    }

    fn floor() -> State<TestScheme, TestDigest> {
        State::new(
            None,
            Floor::new(
                Some(Processed::Block(Height::new(5))),
                Cutoff::Round(round(5)),
            ),
            round(5),
        )
    }

    #[test]
    fn fetch_if_permitted_applies_height_and_round_floors() {
        let floor = floor();
        let mut resolver = TestResolver::default();

        assert!(matches!(
            floor.fetch_if_permitted(&mut resolver, Request::finalized(Height::new(5))),
            FetchAdmission::Denied
        ));
        assert!(matches!(
            floor.fetch_if_permitted(
                &mut resolver,
                Request::finalized_by_height(digest(1), Height::new(4)),
            ),
            FetchAdmission::Denied
        ));
        assert!(matches!(
            floor.fetch_if_permitted(&mut resolver, Request::notarized(round(5))),
            FetchAdmission::Denied
        ));
        assert!(resolver.fetches().is_empty());

        assert!(matches!(
            floor.fetch_if_permitted(&mut resolver, Request::finalized(Height::new(6))),
            FetchAdmission::Issued
        ));
        assert!(matches!(
            floor.fetch_if_permitted(&mut resolver, Request::notarized(round(6))),
            FetchAdmission::Issued
        ));

        let fetches = resolver.fetches();
        assert_eq!(fetches.len(), 2);
        assert!(matches!(
            fetches[0],
            Fetch {
                key: Key::Finalized {
                    height
                },
                subscriber: Annotation::Finalized(Finalized::ByHeight {
                    height: subscriber_height
                }),
                ..
            } if height == Height::new(6) && subscriber_height == Height::new(6)
        ));
        assert!(matches!(
            fetches[1],
            Fetch {
                key: Key::Notarized {
                    round: request_round
                },
                subscriber: Annotation::Notarization {
                    round: subscriber_round
                },
                ..
            } if request_round == round(6) && subscriber_round == round(6)
        ));
    }

    #[test]
    fn fetch_targeted_if_permitted_returns_denied_without_fetching() {
        let floor = floor();
        let mut resolver = TestResolver::default();
        let mut rng = commonware_utils::test_rng();
        let target = crypto_ed25519::PrivateKey::random(&mut rng).public_key();

        assert!(matches!(
            floor.fetch_targeted_if_permitted(
                &mut resolver,
                Request::finalized(Height::new(5)),
                NonEmptyVec::new(target.clone()),
            ),
            FetchAdmission::Denied
        ));
        assert!(resolver.targeted().is_empty());

        assert!(matches!(
            floor.fetch_targeted_if_permitted(
                &mut resolver,
                Request::finalized(Height::new(6)),
                NonEmptyVec::new(target),
            ),
            FetchAdmission::Issued
        ));
        assert_eq!(
            resolver.targeted(),
            vec![Key::Finalized {
                height: Height::new(6)
            }]
        );
    }

    #[test]
    fn fetch_all_if_permitted_filters_denied_requests() {
        let floor = floor();
        let mut resolver = TestResolver::default();

        assert!(matches!(
            floor.fetch_all_if_permitted(
                &mut resolver,
                vec![
                    Request::finalized(Height::new(5)),
                    Request::finalized(Height::new(6)),
                    Request::notarized(round(5)),
                    Request::notarized(round(6)),
                ],
            ),
            FetchAdmission::Issued
        ));

        let fetches = resolver.fetches();
        assert_eq!(fetches.len(), 2);
        assert!(matches!(fetches[0].key, Key::Finalized { height } if height == Height::new(6)));
        assert!(
            matches!(fetches[1].key, Key::Notarized { round: request_round } if request_round == round(6))
        );

        let mut resolver = TestResolver::default();
        assert!(matches!(
            floor.fetch_all_if_permitted(
                &mut resolver,
                vec![
                    Request::finalized(Height::new(5)),
                    Request::notarized(round(5)),
                ],
            ),
            FetchAdmission::Denied
        ));
        assert!(resolver.fetches().is_empty());
    }

    #[test]
    fn fetch_if_permitted_without_height_floor_allows_genesis_height() {
        let floor = State::<TestScheme, TestDigest>::new(
            None,
            Floor::new(None, Cutoff::Round(round(5))),
            round(5),
        );
        let mut resolver = TestResolver::default();

        assert!(matches!(
            floor.fetch_if_permitted(&mut resolver, Request::finalized(Height::zero())),
            FetchAdmission::Issued
        ));

        let fetches = resolver.fetches();
        assert_eq!(fetches.len(), 1);
        assert!(matches!(
            fetches[0],
            Fetch {
                key: Key::Finalized {
                    height
                },
                subscriber: Annotation::Finalized(Finalized::ByHeight {
                    height: subscriber_height
                }),
                ..
            } if height == Height::zero() && subscriber_height == Height::zero()
        ));
    }
}