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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
//! Wrapper for consensus applications that handles epochs and block dissemination.
//!
//! # Overview
//!
//! [`Deferred`] is an adapter that wraps any [`Application`] implementation to handle
//! epoch transitions automatically. It intercepts consensus operations (propose, verify) and
//! ensures blocks are only produced within valid epoch boundaries.
//!
//! # Epoch Boundaries
//!
//! When the parent is the last block in an epoch (as determined by the [`Epocher`]), this wrapper
//! re-proposes that boundary block instead of building a new block. This avoids producing blocks
//! that would be pruned by the epoch transition.
//!
//! # Deferred Verification
//!
//! Before casting a notarize vote, [`Deferred`] waits for the block to become available and
//! then verifies that the block's embedded context matches the consensus context. However, it does not
//! wait for the application to finish verifying the block contents before voting. This enables verification
//! to run while we wait for a quorum of votes to form a certificate (hiding verification latency behind network
//! latency). Once a certificate is formed, we wait on the verification result in [`CertifiableAutomaton::certify`]
//! before voting to finalize (ensuring no invalid blocks are admitted to the canonical chain).
//!
//! A validator whose verification stays pending has already voted to notarize the block but
//! withholds its finalize vote. Peers that voted to finalize cannot nullify the view, so once
//! `f+1` honest peers have voted to finalize, the view cannot be nullified, and the pending
//! validator is a fault for that view until the block finalizes without it.
//!
//! All validators must run the same wrapper for all views in a given epoch (see
//! [`crate::marshal::standard`] for more details).
//!
//! # Usage
//!
//! Wrap your [`Application`] implementation with [`Deferred::new`] and provide it to your
//! consensus engine for the [`Automaton`], [`Relay`], and [`Reporter`]. As the reporter, the
//! wrapper forwards consensus activity to marshal and releases the state it keeps for each round
//! once consensus finalizes that round. The wrapper handles all epoch logic transparently.
//!
//! ```rust,ignore
//! let application = Deferred::new(
//!     context,
//!     my_application,
//!     marshal_mailbox,
//!     epocher,
//! );
//! ```
//!
//! # Implementation Notes
//!
//! - Genesis blocks are handled specially: epoch 0 returns the application's genesis block,
//!   while subsequent epochs use the last block of the previous epoch as genesis
//! - Blocks are automatically verified to be within the current epoch
//!
//! # Notarization and Data Availability
//!
//! In rare crash cases, it is possible for a notarization certificate to exist without a block being
//! available to the honest parties. [`CertifiableAutomaton::certify`] may then remain pending while
//! it waits for the block. Simplex may time out and nullify the view without resolving that request.
//!
//! For this reason, it should not be expected that every notarized payload will be certifiable due
//! to the lack of an available block. However, if even one honest and online party has the block,
//! they will attempt to forward it to others via marshal's resolver.
//!
//! ```text
//!                                      ┌───────────────────────────────────────────────────┐
//!                                      ▼                                                   │
//! ┌─────────────────────┐   ┌─────────────────────┐   ┌─────────────────────┐   ┌─────────────────────┐
//! │          B1         │◀──│          B2         │◀──│          B3         │XXX│          B4         │
//! └─────────────────────┘   └─────────────────────┘   └──────────┬──────────┘   └─────────────────────┘
//!                                                                │
//!                                                         Pending Certify
//! ```
//!
//! # Future Work
//!
//! - To further reduce view latency, a participant could optimistically vote for a block prior to
//!   observing its availability during [`Automaton::verify`]. However, this would require updating
//!   other components (like [`crate::marshal`]) to handle backfill where notarization does not imply
//!   a block is fetchable (without modification, a malicious leader that withholds blocks during propose
//!   could get an honest node to exhaust their network rate limit fetching things that don't exist rather
//!   than blocks they need AND can fetch).

use crate::{
    Application, Automaton, Block, CertifiableAutomaton, CertifiableBlock, Epochable, Handoff,
    Heightable, Relay, Reporter,
    marshal::{
        ancestry::Ancestry,
        application::{
            build::{self, Resolved},
            gates::{self, GateOutcome, Gates},
            relay,
            validation::{Stage, is_inferred_reproposal_at_certify},
        },
        core::{CommitmentFallback, DigestFallback, Mailbox},
        standard::{
            Standard,
            validation::{
                Decision, ParentCheck, await_and_validate_parent, precheck_epoch_and_reproposal,
                run_app_verify,
            },
        },
    },
    simplex::{
        Plan,
        types::{Activity, Context},
    },
    types::{Epocher, Round, View},
};
use commonware_actor::Feedback;
use commonware_codec::Codec;
use commonware_cryptography::{Digested, Digestible, certificate::Scheme};
use commonware_macros::select;
use commonware_runtime::{
    Clock, Metrics, Spawner,
    telemetry::{
        metrics::{
            MetricsExt as _,
            histogram::{Buckets, Timed},
        },
        traces::TracedExt as _,
    },
};
use commonware_utils::channel::{fallible::OneshotExt, oneshot};
use std::{
    future::{Future, ready},
    sync::Arc,
};
use tracing::{Instrument as _, debug, info_span};

/// An [`Application`] adapter that handles epoch transitions and validates block ancestry.
///
/// This wrapper intercepts consensus operations to enforce epoch boundaries and validate
/// block ancestry. It prevents blocks from being produced outside their valid epoch,
/// handles the special case of re-proposing boundary blocks at epoch boundaries,
/// and ensures all blocks have valid parent linkage and contiguous heights.
///
/// # Ancestry Validation
///
/// Applications wrapped by [`Deferred`] can rely on the following ancestry checks being
/// performed automatically during verification:
/// - Parent digest matches the consensus context's expected parent
/// - Block height is exactly one greater than the parent's height
///
/// Verifying only the immediate parent is sufficient since the parent was either notarized by
/// consensus, whose honest voters verified its context, or verified locally before this
/// participant voted for it (optimistic validation). Either way the entire ancestry chain back
/// to genesis is transitively validated.
///
/// Applications do not need to re-implement these checks in their own verification logic.
///
/// # Context Recovery
///
/// With deferred verification, validators wait for data availability (DA) and verify the context
/// before voting. If a validator crashes after voting but before certification, they lose their in-memory
/// certification gate task. When recovering, validators extract context from a [`CertifiableBlock`].
///
/// _This embedded context is trustworthy because the notarizing quorum (which contains at least f+1 honest
/// validators) verified that the block's context matched the consensus context before voting._
pub struct Deferred<E, S, A, B, ES>
where
    S: Scheme,
    A: Application<E>,
    B: CertifiableBlock + Codec,
    ES: Epocher,
{
    context: Arc<E>,
    application: A,
    marshal: Mailbox<S, Standard<B>>,
    epocher: ES,
    gates: Gates<<B as Digestible>::Digest, Digested<B>>,

    build_duration: Timed,
    proposal_parent_fetch_duration: Timed,
    ancestor_fetch_duration: Timed,
}

impl<E, S, A, B, ES> Clone for Deferred<E, S, A, B, ES>
where
    S: Scheme,
    A: Application<E>,
    B: CertifiableBlock + Codec,
    ES: Epocher,
{
    fn clone(&self) -> Self {
        Self {
            context: self.context.clone(),
            application: self.application.clone(),
            marshal: self.marshal.clone(),
            epocher: self.epocher.clone(),
            gates: self.gates.clone(),
            build_duration: self.build_duration.clone(),
            proposal_parent_fetch_duration: self.proposal_parent_fetch_duration.clone(),
            ancestor_fetch_duration: self.ancestor_fetch_duration.clone(),
        }
    }
}

impl<E, S, A, B, ES> Deferred<E, S, A, B, ES>
where
    E: Spawner + Metrics + Clock,
    S: Scheme,
    A: Application<
            E,
            Block = B,
            SigningScheme = S,
            Context = Context<B::Digest, S::PublicKey>,
            Input = (),
        >,
    B: CertifiableBlock<Context = <A as Application<E>>::Context> + Codec,
    ES: Epocher,
{
    /// Creates a new [`Deferred`] wrapper.
    pub fn new(context: E, application: A, marshal: Mailbox<S, Standard<B>>, epocher: ES) -> Self {
        let build_histogram = context.histogram(
            "build_duration",
            "Histogram of time taken for the application to build a new block, in seconds",
            Buckets::LOCAL,
        );
        let build_duration = Timed::new(build_histogram);
        let parent_fetch_histogram = context.histogram(
            "parent_fetch_duration",
            "Histogram of time taken to fetch a parent block in proposal, in seconds",
            Buckets::LOCAL,
        );
        let proposal_parent_fetch_duration = Timed::new(parent_fetch_histogram);
        let ancestor_fetch_histogram = context.histogram(
            "ancestor_fetch_duration",
            "Histogram of time taken to fetch a block via the ancestry stream, in seconds",
            Buckets::LOCAL,
        );
        let ancestor_fetch_duration = Timed::new(ancestor_fetch_histogram);

        Self {
            context: Arc::new(context),
            application,
            marshal,
            epocher,
            gates: Gates::new(),

            build_duration,
            proposal_parent_fetch_duration,
            ancestor_fetch_duration,
        }
    }

    /// Verifies a proposed block's application-level validity.
    ///
    /// This method validates that:
    /// 1. The block's parent digest matches the expected parent
    /// 2. The block's height is exactly one greater than the parent's height
    /// 3. The underlying application's verification logic passes
    ///
    /// The `parent_request` must be a subscription to the parent named by `context.parent`,
    /// started by the caller so the parent fetch can overlap work that precedes this call.
    ///
    /// Verification is spawned in a background task and returns a receiver that will contain
    /// the verification result. Valid blocks are reported to the marshal as verified.
    #[inline]
    fn deferred_verify(
        &self,
        context: <Self as Automaton>::Context,
        block: Digested<B>,
        parent_request: oneshot::Receiver<Digested<B>>,
        stage: Stage,
    ) -> oneshot::Receiver<GateOutcome> {
        let marshal = self.marshal.clone();
        let mut application = self.application.clone();
        let (mut tx, rx) = oneshot::channel();
        let ancestor_fetch_duration = self.ancestor_fetch_duration.clone();
        let runtime_context = self
            .context
            .child("deferred_verify")
            .with_attribute("round", context.round);
        let span = info_span!(
            "marshal.deferred.verify.deferred",
            round = %context.round
        );
        runtime_context.spawn(move |runtime_context| {
            async move {
                let round = context.round;

                // Start the candidate store immediately: it depends on neither the
                // parent fetch (which may hit the network) nor the verdict below.
                // Storing before validation is intentional: these caches provide
                // candidate availability/recovery, not a validity decision. This
                // task gates the finalize vote by resolving true only after both
                // app verification succeeds and the store is durable.
                let store = stage.store(&marshal, round, block.clone());
                let verify = async {
                    // Validate the parent we already started fetching.
                    let parent = match await_and_validate_parent(
                        context.parent.1,
                        &block,
                        parent_request,
                        &mut tx,
                    )
                    .await
                    {
                        Some(ParentCheck::Valid(parent)) => parent,
                        Some(ParentCheck::Invalid) => return Some(false),
                        None => return None,
                    };
                    run_app_verify(
                        runtime_context,
                        context,
                        block.clone(),
                        parent,
                        &mut application,
                        &marshal,
                        &mut tx,
                        ancestor_fetch_duration,
                    )
                    .await
                };
                let (verdict, durable) = futures::join!(verify, store);

                // Publish only when the block is both valid and durable. App-invalid
                // candidates may already be in the cache from the concurrent store above,
                // so the gate verdict is the authority for consensus progress.
                if let Some(application_valid) = gates::resolve(verdict, durable) {
                    tx.send_lossy(GateOutcome::Ready(application_valid));
                }
            }
            .instrument(span)
        });

        rx
    }

    fn certify_from_embedded_context(
        &self,
        round: Round,
        digest: B::Digest,
    ) -> oneshot::Receiver<bool> {
        // No in-progress task means we never verified this proposal locally. We can use the
        // block's embedded context to help complete finalization when Byzantine validators
        // withhold their finalize votes. If a Byzantine proposer embedded a malicious context,
        // the f+1 honest validators from the notarizing quorum will verify against the proper
        // context and reject the mismatch, preventing a 2f+1 finalization quorum.
        //
        // We must fetch here rather than only wait for local broadcast delivery. A Byzantine
        // leader can send a proposal to just f+1 honest validators, collect enough honest
        // notarize votes to form a notarization, and leave the remaining honest validators
        // without the block. Those validators need the notarized round to recover the block
        // and certify; otherwise they can remain stuck if the Byzantine validators stop
        // participating in the next view.
        //
        // Subscribe to the block and verify using its embedded context once available.
        debug!(
            ?round,
            ?digest,
            "subscribing to block for certification using embedded context"
        );
        let block_rx = self
            .marshal
            .subscribe_by_digest(digest, DigestFallback::FetchByRound { round });
        let marshaled = self.clone();
        let epocher = self.epocher.clone();
        let (mut tx, rx) = oneshot::channel();
        let context = self.context.child("certify").with_attribute("round", round);
        context.spawn(move |_| {
            async move {
                let block = select! {
                    _ = tx.closed() => {
                        debug!(
                            reason = "consensus dropped receiver",
                            "skipping certification"
                        );
                        return;
                    },
                    result = block_rx => match result {
                        Ok(block) => block,
                        Err(_) => {
                            debug!(
                                ?digest,
                                reason = "failed to fetch block for certification",
                                "skipping certification"
                            );
                            return;
                        }
                    },
                };

                // Re-proposal detection for certify path: we don't have the consensus context,
                // only the block's embedded context from original proposal. Infer re-proposal from:
                // 1. Block is at epoch boundary (only boundary blocks can be re-proposed)
                // 2. Certification round's view > embedded context's view (re-proposals retain their
                //    original embedded context, so a later view indicates the block was re-proposed)
                // 3. Same epoch (re-proposals don't cross epoch boundaries)
                let embedded_context = block.context();
                let is_reproposal = is_inferred_reproposal_at_certify(
                    &epocher,
                    block.height(),
                    embedded_context.round,
                    round,
                );
                if is_reproposal {
                    // Certifier holds a notarization for this block, so route
                    // the write to the notarized cache. `certified` is
                    // idempotent, so crash-recovery double-invocation is safe.
                    if !marshaled.marshal.certified(round, block).await {
                        return;
                    }
                    tx.send_lossy(true);
                    return;
                }

                // Start the parent fetch for the deferred verification below,
                // which expects a caller-started subscription. Certify does not
                // carry the consensus context, so the parent round comes from
                // the block's embedded context. That context is trustworthy
                // because the digest is notarized and the notarizing quorum's
                // f+1 honest validators verified it against the consensus
                // context before voting.
                let (parent_view, parent_commitment) = embedded_context.parent;
                let parent_request = marshaled.marshal.subscribe_by_commitment(
                    parent_commitment,
                    CommitmentFallback::FetchByRound {
                        round: Round::new(embedded_context.epoch(), parent_view),
                    },
                );

                let verify_rx = marshaled.deferred_verify(
                    embedded_context,
                    block,
                    parent_request,
                    Stage::Certified,
                );
                gates::forward(tx, verify_rx, |result| match result {
                    GateOutcome::Ready(result) => Some(result),
                    GateOutcome::Recover => None,
                })
                .await;
            }
            .instrument(info_span!(
                "marshal.deferred.certify.embedded",
                round = %round,
                digest = %digest
            ))
        });
        rx
    }
    fn certify_from_existing_task(
        &self,
        round: Round,
        digest: B::Digest,
        task: oneshot::Receiver<GateOutcome>,
    ) -> oneshot::Receiver<bool> {
        // `verify()` waits only on local broadcast delivery, so nudge a
        // round-bound notarized fetch that can unblock the existing waiter
        // if local broadcast never arrives. For the standard variant, the
        // digest is also the variant commitment.
        self.marshal.hint_notarized(round, digest);

        // A completed gate either carries an applicable local verdict or requests
        // recovery. After an unclean restart the in-memory task is gone, which also
        // recovers via the embedded-context fetch path.
        let marshaled = self.clone();
        let (tx, rx) = oneshot::channel();
        let context = self
            .context
            .child("certify_existing")
            .with_attribute("round", round);
        context.spawn(move |_| {
            gates::drive(tx, task, round, digest, move || {
                marshaled.certify_from_embedded_context(round, digest)
            })
            .instrument(info_span!(
                "marshal.deferred.certify.existing",
                round = %round,
                digest = %digest
            ))
        });
        rx
    }

    /// Runs the proposal checks for `consensus_context` and yields what the proposal path does
    /// next: re-propose the epoch boundary block, decline a parent the marshal cannot build on,
    /// or build on the fetched parent.
    ///
    /// The returned future borrows nothing from `self`, so it can move into the spawned prepare
    /// or propose task.
    fn checks(
        &self,
        consensus_context: Context<B::Digest, S::PublicKey>,
    ) -> impl Future<Output = Resolved<B::Digest, Digested<B>, impl Ancestry<B>>> + Send + 'static
    {
        let context = self.context.clone();
        let marshal = self.marshal.clone();
        let epocher = self.epocher.clone();
        let proposal_parent_fetch_duration = self.proposal_parent_fetch_duration.clone();
        let ancestor_fetch_duration = self.ancestor_fetch_duration.clone();
        let build_duration = self.build_duration.clone();
        async move {
            // The parent for any consensus context is in the same epoch: the
            // boundary block of the previous epoch is the genesis block of the
            // current epoch.
            //
            // Proposal context carries the parent view and commitment but not
            // the parent height. The parent may sit above the finalized tip and
            // may still be uncertified, so this must stay round-bound until the
            // block is returned.
            let (parent_view, parent_commitment) = consensus_context.parent;
            let parent_request = marshal.subscribe_by_commitment(
                parent_commitment,
                CommitmentFallback::FetchByRound {
                    round: Round::new(consensus_context.epoch(), parent_view),
                },
            );
            let parent_timer = proposal_parent_fetch_duration.timer(&*context);
            let Ok(parent) = parent_request.await else {
                debug!(
                    ?parent_commitment,
                    reason = "failed to fetch parent block",
                    "skipping proposal"
                );
                return Resolved::Skip;
            };
            parent_timer.observe(&*context);

            // Deferred verification votes before it checks that a block's parent field
            // matches the parent named by its consensus context, so an uncertified
            // handoff parent may be unlinked. Build only on a linked parent. A parent at
            // view zero is the epoch's genesis block, which needs no link check. The first
            // epoch's genesis has no context parent to match, and a later epoch's genesis
            // is the previous epoch's finalized boundary block.
            //
            // The coding variant needs no such check: it fetches each parent by the
            // commitment in its child's consensus context, and its ancestry stream ends
            // at a fetched parent that does not match the child's link.
            if parent_view != View::zero() && parent.parent() != parent.context().parent.1 {
                debug!(
                    ?parent_commitment,
                    reason = "parent does not link to its context parent",
                    "skipping proposal"
                );
                return Resolved::Skip;
            }

            // Special case: If the parent block is the last block in the epoch,
            // re-propose it so as not to produce any blocks that will be cut out
            // by the epoch transition.
            let last_in_epoch = epocher
                .last(consensus_context.epoch())
                .expect("current epoch should exist");
            if parent.height() == last_in_epoch {
                return Resolved::Reuse(parent.digest(), parent);
            }

            let ancestor_stream =
                marshal.ancestor_stream(context.clone(), [parent], ancestor_fetch_duration);
            Resolved::Build(ancestor_stream, build_duration.timer(&*context), ())
        }
    }
}

impl<E, S, A, B, ES> Automaton for Deferred<E, S, A, B, ES>
where
    E: Spawner + Metrics + Clock,
    S: Scheme,
    A: Application<
            E,
            Block = B,
            SigningScheme = S,
            Context = Context<B::Digest, S::PublicKey>,
            Input = (),
        >,
    B: CertifiableBlock<Context = <A as Application<E>>::Context> + Codec,
    ES: Epocher,
{
    type Digest = B::Digest;
    type Context = Context<Self::Digest, S::PublicKey>;

    /// Proposes a new block or re-proposes the epoch boundary block.
    ///
    /// This method builds a new block from the underlying application unless the parent block
    /// is the last block in the current epoch. When at an epoch boundary, it re-proposes the
    /// boundary block to avoid creating blocks that would be invalidated by the epoch transition.
    ///
    /// The proposal operation is spawned in a background task and returns a receiver that will
    /// contain the proposed block's digest when ready. The block is staged before the digest is
    /// delivered and handed to marshal when consensus requests the relay broadcast, which
    /// persists it after the send. The resulting sync handle is awaited only at certification so
    /// it overlaps consensus voting. The digest does not imply durability on
    /// its own; [`CertifiableAutomaton::certify`] awaits the registered certification gate before
    /// the finalize vote.
    #[allow(clippy::async_yields_async)]
    #[tracing::instrument(name = "marshal.deferred.propose", level = "info", skip_all, fields(round = %consensus_context.round))]
    async fn propose(
        &mut self,
        consensus_context: Context<Self::Digest, S::PublicKey>,
    ) -> oneshot::Receiver<Self::Digest> {
        let checks = self.checks(consensus_context.clone());
        let span = info_span!(
            "marshal.deferred.propose.task",
            round = %consensus_context.round
        );
        let round = consensus_context.round;
        let (parent_view, parent_commitment) = consensus_context.parent;
        build::propose(
            self.context.as_ref(),
            &self.application,
            self.gates.clone(),
            consensus_context,
            checks,
            span,
            move || {
                info_span!(
                    "marshal.deferred.application.propose",
                    round = %round,
                    parent_view = parent_view.traced(),
                    parent = %parent_commitment
                )
            },
            |block, ()| ready((block.digest(), block)),
        )
    }

    #[allow(clippy::async_yields_async)]
    #[tracing::instrument(name = "marshal.deferred.verify", level = "info", skip_all, fields(round = %context.round, digest = %digest))]
    async fn verify(
        &mut self,
        context: Context<Self::Digest, S::PublicKey>,
        digest: Self::Digest,
    ) -> oneshot::Receiver<bool> {
        let marshal = self.marshal.clone();
        let marshaled = self.clone();
        let round = context.round;

        // Verification needs the full block but waits only for local delivery. Certification starts
        // recovery only when the block is not buffered. If a buffered block is evicted before
        // verification registers its wait, verification is left with neither the block nor an
        // active fetch. Register the wait before publishing the gate so it receives the buffered
        // block or is waiting when recovery delivers it.
        let block_request = marshal.subscribe_by_digest(digest, DigestFallback::Wait);
        let (task_tx, task_rx) = oneshot::channel();
        self.gates.insert(round, digest, task_rx);

        let (mut tx, rx) = oneshot::channel();
        let runtime_context = self
            .context
            .child("optimistic_verify")
            .with_attribute("round", round);
        runtime_context.spawn(move |_| {
            async move {
                // Start the parent fetch immediately: its commitment and certified
                // round are known from the consensus context, so it can proceed in
                // parallel with broadcast delivery of the candidate block.
                // Reproposals (digest == context.parent.1) skip parent validation
                // entirely, so they must not fetch: the "parent" is the candidate
                // itself, and candidate acquisition is deliberately local-only.
                let parent_request = (digest != context.parent.1).then(|| {
                    let (parent_view, parent_commitment) = context.parent;
                    marshal.subscribe_by_commitment(
                        parent_commitment,
                        CommitmentFallback::FetchByRound {
                            round: Round::new(context.epoch(), parent_view),
                        },
                    )
                });

                // Stop waiting for the block if consensus drops the verification request.
                let block = select! {
                    _ = tx.closed() => {
                        debug!(
                            reason = "consensus dropped receiver",
                            "skipping optimistic verification"
                        );
                        return;
                    },
                    result = block_request => match result {
                        Ok(block) => block,
                        Err(_) => {
                            debug!(
                                ?digest,
                                reason = "failed to fetch block for optimistic verification",
                                "skipping optimistic verification"
                            );
                            return;
                        }
                    },
                };

                // Shared pre-checks enforce:
                // - Block epoch membership.
                // - Re-proposal detection via `digest == context.parent.1`.
                //
                // Re-proposals return early and skip normal parent/height checks
                // because consensus settles their validity when certifying the view
                // that first carried the block, and parent-child checks would fail by
                // construction when parent == block.
                let Some(decision) = precheck_epoch_and_reproposal(
                    &marshaled.epocher,
                    &marshal,
                    &context,
                    digest,
                    block,
                )
                .await
                else {
                    return;
                };
                let block = match decision {
                    Decision::Complete(valid) => {
                        // `Complete` means either immediate rejection or successful
                        // re-proposal handling with no further ancestry validation.
                        //
                        // A rejection is safe to publish as a gate verdict because the
                        // precheck depends only on the block's height and the gate key's
                        // epoch, never on the declared parent. A conflicting header for
                        // the same `(round, digest)` cannot produce an honest
                        // notarization: reading the digest as a re-proposal requires it
                        // to be the recorded payload of an earlier view, so its embedded
                        // context fails the mismatch check under any normal header.
                        task_tx.send_lossy(GateOutcome::Ready(valid));
                        tx.send_lossy(valid);
                        return;
                    }
                    Decision::Continue(block) => block,
                };

                // `Continue` implies a non-reproposal, so the parent subscription
                // was started above.
                let parent_request =
                    parent_request.expect("non-reproposal has a parent subscription");

                // Before casting a notarize vote, ensure the block's embedded context matches
                // the consensus context.
                //
                // The notarize quorum is guaranteed to have at least f+1 honest validators who will
                // verify against this context, so a Byzantine proposer cannot embed a malicious
                // context. The other f honest validators who did not vote will later use the
                // block-embedded context to help finalize if Byzantine validators withhold their
                // finalize votes.
                if block.context() != context {
                    debug!(
                        ?context,
                        block_context = ?block.context(),
                        "block-embedded context does not match consensus context during optimistic verification"
                    );
                    task_tx.send_lossy(GateOutcome::Recover);
                    tx.send_lossy(false);
                    return;
                }

                // Optimistic verify returns immediately; the deferred_verify task
                // runs in the background and forwards its final verdict to
                // `task_tx` so `certify` observes the same result via the
                // synchronously-registered `task_rx`.
                //
                // Once the optimistic verdict is delivered, the certification
                // gate owns the deferred work. Nullification keeps that gate
                // alive, while finalization drops it.
                let deferred_rx = marshaled
                    .deferred_verify(context, block, parent_request, Stage::Verified);
                tx.send_lossy(true);
                gates::forward(task_tx, deferred_rx, Some).await;
            }
            .instrument(info_span!(
                "marshal.deferred.verify.optimistic",
                round = %round,
                digest = %digest
            ))
        });
        rx
    }
}

impl<E, S, A, B, ES> CertifiableAutomaton for Deferred<E, S, A, B, ES>
where
    E: Spawner + Metrics + Clock,
    S: Scheme,
    A: Application<
            E,
            Block = B,
            SigningScheme = S,
            Context = Context<B::Digest, S::PublicKey>,
            Input = (),
        >,
    B: CertifiableBlock<Context = <A as Application<E>>::Context> + Codec,
    ES: Epocher,
{
    /// Prepares a term-start proposal on an uncertified parent.
    ///
    /// Runs the same checks as [`Self::propose`], in the same order, and hands the application the
    /// fetched ancestry. When the checks find the epoch boundary block, the marshal re-proposes it
    /// without the application and answers [`Handoff::Stage`].
    #[allow(clippy::async_yields_async)]
    #[tracing::instrument(name = "marshal.deferred.prepare", level = "info", skip_all, fields(round = %consensus_context.round))]
    async fn prepare(
        &mut self,
        consensus_context: Context<Self::Digest, S::PublicKey>,
    ) -> oneshot::Receiver<Handoff<Self::Digest>> {
        let checks = self.checks(consensus_context.clone());
        let span = info_span!(
            "marshal.deferred.prepare.task",
            round = %consensus_context.round
        );
        let round = consensus_context.round;
        let (parent_view, parent_commitment) = consensus_context.parent;
        build::prepare(
            self.context.as_ref(),
            &self.application,
            self.gates.clone(),
            consensus_context,
            checks,
            span,
            move || {
                info_span!(
                    "marshal.deferred.application.prepare",
                    round = %round,
                    parent_view = parent_view.traced(),
                    parent = %parent_commitment
                )
            },
            |block, ()| ready((block.digest(), block)),
        )
    }

    #[allow(clippy::async_yields_async)]
    #[tracing::instrument(name = "marshal.deferred.certify", level = "info", skip_all, fields(round = %round, digest = %digest))]
    async fn certify(&mut self, round: Round, digest: Self::Digest) -> oneshot::Receiver<bool> {
        // Attempt to retrieve the existing certification gate task for this round/digest.
        let task = self.gates.claim(round, digest, |block, ack| {
            self.marshal.verified_deferred(round, block, ack)
        });
        if let Some(task) = task {
            return self.certify_from_existing_task(round, digest, task);
        }

        self.certify_from_embedded_context(round, digest)
    }
}

impl<E, S, A, B, ES> Relay for Deferred<E, S, A, B, ES>
where
    E: Send + Sync + 'static,
    S: Scheme,
    A: Application<E, Block = B, Context = Context<B::Digest, S::PublicKey>>,
    B: CertifiableBlock<Context = <A as Application<E>>::Context> + Codec,
    ES: Epocher,
{
    type Digest = B::Digest;
    type PublicKey = S::PublicKey;
    type Plan = Plan<S::PublicKey>;

    fn broadcast(&mut self, commitment: Self::Digest, plan: Plan<S::PublicKey>) -> Feedback {
        relay::broadcast(&self.gates, &self.marshal, commitment, plan)
    }
}

/// The wrapper is the consensus engine's reporter, as it is its automaton and relay: it forwards
/// every activity to marshal and first releases the state it keeps per round (certification
/// gates, staged proposals, and sent marks). A finalization releases its round and the rounds
/// below it. Any activity of a later epoch releases every earlier epoch, whose engine has been
/// retired, which covers finalized progress that marshal imported while no engine reported it.
/// The voter reports from the same task that requests the lock-in broadcast and certification,
/// so pruning is ordered with both.
impl<E, S, A, B, ES> Reporter for Deferred<E, S, A, B, ES>
where
    E: Send + Sync + 'static,
    S: Scheme,
    A: Application<E, Block = B, Context = Context<B::Digest, S::PublicKey>>,
    B: CertifiableBlock<Context = <A as Application<E>>::Context> + Codec,
    ES: Epocher,
{
    type Activity = Activity<S, B::Digest>;

    fn report(&mut self, activity: Self::Activity) -> Feedback {
        let retired = match &activity {
            Activity::Finalization(finalization) => finalization.round(),
            activity => Round::new(activity.epoch(), View::zero()),
        };
        self.gates.retain_after(retired);
        self.marshal.report(activity)
    }
}

#[cfg(test)]
mod tests {
    use super::Deferred;
    use crate::{
        Automaton, CertifiableAutomaton, Relay,
        marshal::{
            application::gates::Gates,
            mocks::{
                harness::{
                    B, BLOCKS_PER_EPOCH, Ctx, D, NAMESPACE, NUM_VALIDATORS, S, StandardHarness,
                    TestHarness, V, default_leader, make_raw_block,
                    setup_network_with_participants,
                },
                verifying::{GatedVerifyingApp, MockVerifyingApp},
            },
            standard::tests::ready,
        },
        simplex::{Plan, scheme::bls12381_threshold::vrf as bls12381_threshold_vrf},
        types::{Epoch, Epocher, FixedEpocher, Height, Round, View},
    };
    use commonware_broadcast::Broadcaster;
    use commonware_cryptography::{
        Digested, Digestible, Hasher as _,
        certificate::{ConstantProvider, mocks::Fixture},
        sha256::Sha256,
    };
    use commonware_macros::{select, test_traced};
    use commonware_runtime::{Clock, Runner, Supervisor as _, deterministic};
    use commonware_utils::{NZUsize, channel::fallible::OneshotExt};
    use std::time::Duration;

    #[test_traced("INFO")]
    fn test_certify_lower_view_after_higher_view() {
        let runner = deterministic::Runner::timed(Duration::from_secs(60));
        runner.start(|mut context| async move {
            let Fixture {
                participants,
                schemes,
                ..
            } = bls12381_threshold_vrf::fixture::<V, _>(&mut context, NAMESPACE, NUM_VALIDATORS);
            let mut oracle = setup_network_with_participants(
                context.child("network"),
                NZUsize!(1),
                participants.clone(),
                1024 * 1024,
            )
            .await;

            let me = participants[0].clone();

            let setup = StandardHarness::setup_validator(
                context.child("validator").with_attribute("index", 0),
                &mut oracle,
                me.clone(),
                ConstantProvider::new(schemes[0].clone()),
            )
            .await;
            let marshal = setup.mailbox;

            let genesis = make_raw_block(Sha256::hash(&[b""]), Height::zero(), 0);
            let mock_app: MockVerifyingApp<B, S> = MockVerifyingApp::new();

            let mut marshaled = Deferred::new(
                context.child("deferred"),
                mock_app,
                marshal.clone(),
                FixedEpocher::new(BLOCKS_PER_EPOCH),
            );

            // Create parent block at height 1
            let parent = make_raw_block(genesis.digest(), Height::new(1), 100);
            let parent_digest = parent.digest();

            assert!(
                marshal
                    .verified(
                        Round::new(Epoch::new(0), View::new(1)),
                        ready(parent.clone())
                    )
                    .await
            );

            // Block A at view 5 (height 2)
            let round_a = Round::new(Epoch::new(0), View::new(5));
            let context_a = Ctx {
                round: round_a,
                leader: me.clone(),
                parent: (View::new(1), parent_digest),
            };
            let block_a = B::new::<Sha256>(context_a.clone(), parent_digest, Height::new(2), 200);
            let commitment_a = block_a.digest();
            assert!(marshal.verified(round_a, ready(block_a.clone())).await);

            // Block B at view 10 (height 2, different block same height)
            let round_b = Round::new(Epoch::new(0), View::new(10));
            let context_b = Ctx {
                round: round_b,
                leader: me.clone(),
                parent: (View::new(1), parent_digest),
            };
            let block_b = B::new::<Sha256>(context_b.clone(), parent_digest, Height::new(2), 300);
            let commitment_b = block_b.digest();
            assert!(marshal.verified(round_b, ready(block_b.clone())).await);

            context.sleep(Duration::from_millis(10)).await;

            // Step 1: Verify block A at view 5
            let _ = marshaled.verify(context_a, commitment_a).await.await;

            // Step 2: Verify block B at view 10
            let _ = marshaled.verify(context_b, commitment_b).await.await;

            // Step 3: Certify block B at view 10 FIRST
            let certify_b = marshaled.certify(round_b, commitment_b).await;
            assert!(
                certify_b.await.unwrap(),
                "Block B certification should succeed"
            );

            // Step 4: Certify block A at view 5 and expect success
            let certify_a = marshaled.certify(round_a, commitment_a).await;

            select! {
                result = certify_a => {
                    assert!(result.unwrap(), "Block A certification should succeed");
                },
                _ = context.sleep(Duration::from_secs(5)) => {
                    panic!("Block A certification timed out");
                },
            }
        })
    }

    #[test_traced("WARN")]
    fn test_marshaled_rejects_unsupported_epoch() {
        #[derive(Clone)]
        struct LimitedEpocher {
            inner: FixedEpocher,
            max_epoch: u64,
        }

        impl Epocher for LimitedEpocher {
            fn containing(&self, height: Height) -> Option<crate::types::EpochInfo> {
                let bounds = self.inner.containing(height)?;
                if bounds.epoch().get() > self.max_epoch {
                    None
                } else {
                    Some(bounds)
                }
            }

            fn first(&self, epoch: Epoch) -> Option<Height> {
                if epoch.get() > self.max_epoch {
                    None
                } else {
                    self.inner.first(epoch)
                }
            }

            fn last(&self, epoch: Epoch) -> Option<Height> {
                if epoch.get() > self.max_epoch {
                    None
                } else {
                    self.inner.last(epoch)
                }
            }
        }

        let runner = deterministic::Runner::timed(Duration::from_secs(60));
        runner.start(|mut context| async move {
            let Fixture {
                participants,
                schemes,
                ..
            } = bls12381_threshold_vrf::fixture::<V, _>(&mut context, NAMESPACE, NUM_VALIDATORS);
            let mut oracle = setup_network_with_participants(
                context.child("network"),
                NZUsize!(1),
                participants.clone(),
                1024 * 1024,
            )
            .await;

            let me = participants[0].clone();

            let setup = StandardHarness::setup_validator(
                context.child("validator").with_attribute("index", 0),
                &mut oracle,
                me.clone(),
                ConstantProvider::new(schemes[0].clone()),
            )
            .await;
            let marshal = setup.mailbox;

            let genesis = make_raw_block(Sha256::hash(&[b""]), Height::zero(), 0);
            let mock_app: MockVerifyingApp<B, S> = MockVerifyingApp::new();
            let limited_epocher = LimitedEpocher {
                inner: FixedEpocher::new(BLOCKS_PER_EPOCH),
                max_epoch: 0,
            };

            let mut marshaled = Deferred::new(
                context.child("deferred"),
                mock_app,
                marshal.clone(),
                limited_epocher,
            );

            // Create a parent block at height 19 (last block in epoch 0, which is supported)
            let parent_ctx = Ctx {
                round: Round::new(Epoch::zero(), View::new(19)),
                leader: default_leader(),
                parent: (View::zero(), genesis.digest()),
            };
            let parent =
                B::new::<Sha256>(parent_ctx.clone(), genesis.digest(), Height::new(19), 1000);
            let parent_digest = parent.digest();

            assert!(
                marshal
                    .clone()
                    .verified(
                        Round::new(Epoch::zero(), View::new(19)),
                        ready(parent.clone())
                    )
                    .await
            );

            // Create a block at height 20 (first block in epoch 1, which is NOT supported)
            let unsupported_round = Round::new(Epoch::new(1), View::new(20));
            let unsupported_context = Ctx {
                round: unsupported_round,
                leader: me.clone(),
                parent: (View::new(19), parent_digest),
            };
            let block = B::new::<Sha256>(
                unsupported_context.clone(),
                parent_digest,
                Height::new(20),
                2000,
            );
            let block_commitment = block.digest();

            assert!(
                marshal
                    .clone()
                    .verified(unsupported_round, ready(block.clone()))
                    .await
            );

            context.sleep(Duration::from_millis(10)).await;

            // Call verify and wait for the result (verify returns optimistic result,
            // but also spawns deferred verification)
            let verify_result = marshaled
                .verify(unsupported_context, block_commitment)
                .await;

            // Wait for optimistic verify to complete so the certification gate task is registered
            let optimistic_result = verify_result.await;

            // The optimistic verify should return false because the block is in an unsupported epoch
            assert!(
                !optimistic_result.unwrap(),
                "Optimistic verify should reject block in unsupported epoch"
            );
        })
    }

    /// Test that marshaled rejects blocks when consensus context doesn't match block's embedded context.
    ///
    /// This tests that when verify() is called with a context that doesn't match what's embedded
    /// in the block, the verification should fail. A Byzantine proposer could broadcast a block
    /// with one embedded context but consensus could call verify() with a different context.
    #[test_traced("WARN")]
    fn test_marshaled_rejects_mismatched_context() {
        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!(1),
                participants.clone(),
                1024 * 1024,
            )
            .await;

            let me = participants[0].clone();

            let setup = StandardHarness::setup_validator(
                context.child("validator").with_attribute("index", 0),
                &mut oracle,
                me.clone(),
                ConstantProvider::new(schemes[0].clone()),
            )
            .await;
            let marshal = setup.mailbox;

            let genesis = make_raw_block(Sha256::hash(&[b""]), Height::zero(), 0);
            let mock_app: MockVerifyingApp<B, S> = MockVerifyingApp::new();

            let mut marshaled = Deferred::new(
                context.child("deferred"),
                mock_app,
                marshal.clone(),
                FixedEpocher::new(BLOCKS_PER_EPOCH),
            );

            // Create parent block at height 1 so the commitment is well-formed.
            let parent_ctx = Ctx {
                round: Round::new(Epoch::zero(), View::new(1)),
                leader: default_leader(),
                parent: (View::zero(), genesis.digest()),
            };
            let parent = B::new::<Sha256>(parent_ctx, genesis.digest(), Height::new(1), 100);
            let parent_commitment = parent.digest();

            assert!(
                marshal
                    .clone()
                    .verified(
                        Round::new(Epoch::zero(), View::new(1)),
                        ready(parent.clone())
                    )
                    .await
            );

            // Build a block with context A (embedded in the block).
            let round_a = Round::new(Epoch::zero(), View::new(2));
            let context_a = Ctx {
                round: round_a,
                leader: me.clone(),
                parent: (View::new(1), parent_commitment),
            };
            let block_a = B::new::<Sha256>(context_a, parent.digest(), Height::new(2), 200);
            let commitment_a = block_a.digest();
            assert!(marshal.verified(round_a, ready(block_a)).await);

            context.sleep(Duration::from_millis(10)).await;

            // Verify using a different consensus context B (hash mismatch).
            let round_b = Round::new(Epoch::zero(), View::new(3));
            let context_b = Ctx {
                round: round_b,
                leader: participants[1].clone(),
                parent: (View::new(1), parent_commitment),
            };

            let verify_rx = marshaled.verify(context_b, commitment_a).await;
            select! {
                result = verify_rx => {
                    assert!(
                        !result.unwrap(),
                        "mismatched context hash should be rejected"
                    );
                },
                _ = context.sleep(Duration::from_secs(5)) => {
                    panic!("verify should reject mismatched context hash promptly");
                },
            }
        })
    }

    /// Dropping the optimistic verify receiver before the block is available can close the
    /// synchronously-registered certification gate task. `certify` must recover through the
    /// embedded-context path instead of returning the closed task to consensus.
    #[test_traced("WARN")]
    fn test_deferred_certify_recovers_after_verify_receiver_drop() {
        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!(1),
                participants.clone(),
                1024 * 1024,
            )
            .await;

            let me = participants[0].clone();
            let setup = StandardHarness::setup_validator(
                context.child("validator").with_attribute("index", 0),
                &mut oracle,
                me.clone(),
                ConstantProvider::new(schemes[0].clone()),
            )
            .await;
            let marshal = setup.mailbox;

            let genesis = make_raw_block(Sha256::hash(&[b""]), Height::zero(), 0);
            let mock_app: MockVerifyingApp<B, S> = MockVerifyingApp::new();
            let mut marshaled = Deferred::new(
                context.child("deferred"),
                mock_app,
                marshal.clone(),
                FixedEpocher::new(BLOCKS_PER_EPOCH),
            );

            let round = Round::new(Epoch::zero(), View::new(1));
            let block_context = Ctx {
                round,
                leader: me,
                parent: (View::zero(), genesis.digest()),
            };
            let block =
                B::new::<Sha256>(block_context.clone(), genesis.digest(), Height::new(1), 100);
            let digest = block.digest();

            let verify_rx = marshaled.verify(block_context, digest).await;
            drop(verify_rx);

            // Give the optimistic task a chance to observe the dropped receiver while its
            // block subscription is still pending.
            context.sleep(Duration::from_millis(10)).await;

            assert!(marshal.verified(round, ready(block)).await);
            let certify_rx = marshaled.certify(round, digest).await;
            select! {
                result = certify_rx => {
                    assert!(
                        result.expect("certify result missing"),
                        "certify should recover after verify receiver drop"
                    );
                },
                _ = context.sleep(Duration::from_secs(5)) => {
                    panic!("certify should recover promptly after verify drop");
                },
            }
        });
    }

    /// The store request runs concurrently with `app.verify`, not after it: while
    /// gated application verification is still blocked, the block has already
    /// reached marshal and is locally queryable even though the sync handle may
    /// still be pending. Releasing verification then lets certification await
    /// the registered certification gate. Separate restart tests cover durable
    /// recovery after certification.
    #[test_traced("WARN")]
    fn test_deferred_store_overlaps_app_verify() {
        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!(1),
                participants.clone(),
                1024 * 1024,
            )
            .await;

            let me = participants[0].clone();

            let setup = StandardHarness::setup_validator(
                context.child("validator").with_attribute("index", 0),
                &mut oracle,
                me.clone(),
                ConstantProvider::new(schemes[0].clone()),
            )
            .await;
            let marshal = setup.mailbox;
            let buffer = setup.extra;

            let genesis = make_raw_block(Sha256::hash(&[b""]), Height::zero(), 0);
            let (mock_app, verify_started, release_verify): (GatedVerifyingApp<B, S>, _, _) =
                GatedVerifyingApp::new();
            let mut marshaled = Deferred::new(
                context.child("deferred"),
                mock_app,
                marshal.clone(),
                FixedEpocher::new(BLOCKS_PER_EPOCH),
            );

            // Seed parent and child via the buffer (in-memory only) so
            // `deferred_verify` can fetch them without going through the
            // persisted marshal path.
            let parent = make_raw_block(genesis.digest(), Height::new(1), 100);
            let parent_digest = parent.digest();

            let child_round = Round::new(Epoch::zero(), View::new(2));
            let child_ctx = Ctx {
                round: child_round,
                leader: me,
                parent: (View::new(1), parent_digest),
            };
            let child = B::new::<Sha256>(child_ctx.clone(), parent_digest, Height::new(2), 200);
            let child_digest = child.digest();

            assert!(
                buffer
                    .broadcast(commonware_p2p::Recipients::Some(vec![]), ready(parent))
                    .accepted(),
                "buffer broadcast for parent should be accepted"
            );
            assert!(
                buffer
                    .broadcast(commonware_p2p::Recipients::Some(vec![]), ready(child))
                    .accepted(),
                "buffer broadcast for child should be accepted"
            );

            // Kick off the optimistic verify, which spawns `deferred_verify`. Its gated
            // `app.verify` blocks until we release it.
            let optimistic_rx = marshaled.verify(child_ctx, child_digest).await;
            assert!(
                optimistic_rx
                    .await
                    .expect("optimistic verify should resolve"),
                "optimistic verify should accept the available block"
            );

            // Application verification is now blocked. The store request runs concurrently
            // with it, so the block is locally queryable even though verification has not
            // returned and the sync handle may still be pending.
            verify_started
                .await
                .expect("verify should reach the gated application");
            assert!(
                marshal.get_block(&child_digest).await.is_some(),
                "the store request runs concurrently with app.verify, so the block is locally queryable while verification is still gated"
            );

            // Releasing verification lets certification succeed (valid and durable).
            release_verify.send_lossy(());
            let certify_rx = marshaled.certify(child_round, child_digest).await;
            select! {
                result = certify_rx => {
                    assert!(
                        result.expect("certify result missing"),
                        "certify should succeed once verification passes"
                    );
                },
                _ = context.sleep(Duration::from_secs(5)) => {
                    panic!("certify should resolve after verification is released");
                },
            }
        });
    }

    /// A boundary re-proposal stores the parent block itself at the
    /// re-proposal round, under the parent's original embedded context. A
    /// leader that crashes after that relay broadcast fetches the stored
    /// parent by its digest on restart and re-proposes it, and the relay
    /// persist deduplicates against the pre-crash write.
    #[test_traced("WARN")]
    fn test_propose_reuses_reproposed_boundary_block_on_restart() {
        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!(1),
                participants.clone(),
                1024 * 1024,
            )
            .await;

            let me = participants[0].clone();
            let setup = StandardHarness::setup_validator(
                context.child("validator").with_attribute("index", 0),
                &mut oracle,
                me.clone(),
                ConstantProvider::new(schemes[0].clone()),
            )
            .await;
            let marshal = setup.mailbox;

            let genesis = make_raw_block(Sha256::hash(&[b""]), Height::zero(), 0);

            // Seed the boundary block at the re-proposal round, where the
            // pre-crash relay broadcast of the re-proposal persisted it.
            let boundary_height = Height::new(BLOCKS_PER_EPOCH.get() - 1);
            let boundary_round = Round::new(Epoch::zero(), View::new(boundary_height.get()));
            let boundary_block = B::new::<Sha256>(
                Ctx {
                    round: boundary_round,
                    leader: default_leader(),
                    parent: (View::zero(), genesis.digest()),
                },
                genesis.digest(),
                boundary_height,
                1900,
            );
            let boundary_digest = boundary_block.digest();
            let round = Round::new(Epoch::zero(), View::new(boundary_height.get() + 1));
            assert!(marshal.verified(round, ready(boundary_block)).await);

            let ctx = Ctx {
                round,
                leader: me.clone(),
                parent: (View::new(boundary_height.get()), boundary_digest),
            };

            // The app cannot build and its verification never completes, so
            // the assertions below hold only if the cached parent is
            // re-proposed as-is.
            let (mock_app, verify_started, _release_verify): (GatedVerifyingApp<B, S>, _, _) =
                GatedVerifyingApp::new();
            let mut marshaled = Deferred::new(
                context.child("deferred"),
                mock_app,
                marshal.clone(),
                FixedEpocher::new(BLOCKS_PER_EPOCH),
            );

            let digest_rx = marshaled.propose(ctx).await;
            let digest = digest_rx.await.expect("propose must return a digest");
            assert_eq!(
                digest, boundary_digest,
                "propose must re-propose the boundary block marshal already persisted for this round"
            );

            let _ = marshaled.broadcast(digest, Plan::Propose { round });
            let certify_rx = marshaled.certify(round, digest).await;
            select! {
                result = certify_rx => {
                    assert!(
                        result.expect("certify result missing"),
                        "re-proposed boundary block must certify through the relay handshake"
                    );
                },
                _ = verify_started => {
                    panic!("certifying a re-proposed boundary block must not run app verification");
                },
            }
        });
    }

    /// Regression: in deferred mode `propose` registers a certification gate that
    /// `certify` awaits. After the leader certifies its own proposal, the block must be
    /// durably recoverable across an unclean restart. This is the >= f+1 guarantee
    /// for the leader's own block.
    #[test_traced("WARN")]
    fn test_deferred_propose_then_certify_persists_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!(1),
                participants.clone(),
                1024 * 1024,
            )
            .await;

            let me = participants[0].clone();
            let setup = StandardHarness::setup_validator(
                context.child("validator").with_attribute("index", 0),
                &mut oracle,
                me.clone(),
                ConstantProvider::new(schemes[0].clone()),
            )
            .await;
            let marshal = setup.mailbox;
            let actor_handle = setup.actor_handle;

            let genesis = make_raw_block(Sha256::hash(&[b""]), Height::zero(), 0);

            // Seed the parent at its round so `propose` can fetch it locally.
            let parent_round = Round::new(Epoch::zero(), View::new(1));
            let parent_ctx = Ctx {
                round: parent_round,
                leader: default_leader(),
                parent: (View::zero(), genesis.digest()),
            };
            let parent = B::new::<Sha256>(parent_ctx, genesis.digest(), Height::new(1), 100);
            let parent_digest = parent.digest();
            assert!(marshal.verified(parent_round, ready(parent)).await);

            // The leader builds the child via `app.propose`.
            let round = Round::new(Epoch::zero(), View::new(2));
            let ctx = Ctx {
                round,
                leader: me.clone(),
                parent: (View::new(1), parent_digest),
            };
            let child = B::new::<Sha256>(ctx.clone(), parent_digest, Height::new(2), 200);
            let child_digest = child.digest();
            let mock_app: MockVerifyingApp<B, S> =
                MockVerifyingApp::new().with_propose_result(child);
            let mut marshaled = Deferred::new(
                context.child("deferred"),
                mock_app,
                marshal.clone(),
                FixedEpocher::new(BLOCKS_PER_EPOCH),
            );

            let digest = marshaled
                .propose(ctx)
                .await
                .await
                .expect("propose must return a digest");
            assert_eq!(
                digest, child_digest,
                "propose must return the built block's digest"
            );

            // The leader certifies its own proposal; this awaits the deferred propose sync handle.
            assert!(
                marshaled
                    .certify(round, child_digest)
                    .await
                    .await
                    .expect("certify result missing"),
                "certify must succeed for the leader's own proposal"
            );

            // After certify, the block must be durable across an unclean restart.
            actor_handle.abort();
            let _ = actor_handle.await;
            drop(marshaled);
            drop(marshal);

            let setup2 = StandardHarness::setup_validator(
                context
                    .child("validator_restart")
                    .with_attribute("index", 0),
                &mut oracle,
                me,
                ConstantProvider::new(schemes[0].clone()),
            )
            .await;
            let marshal2 = setup2.mailbox;

            assert!(
                marshal2.get_block(&child_digest).await.is_some(),
                "certify resolved true for the leader's own proposal so the block must be durable"
            );
        });
    }

    /// Shared scenario for the proposal-parent equivocation tests.
    ///
    /// The local validator certified the view-1 block but only nullified view 2,
    /// while the rest of the network notarized and certified the view-2 block.
    /// The view-3 leader builds on the view-2 block and broadcasts it, so the
    /// block is buffered locally but was never verified here. The equivocating
    /// context names the certified view-1 block as parent, which this
    /// validator's parent selection accepts (view 1 certified, view 2 nullified).
    struct EquivocationFixture {
        marshaled: Deferred<deterministic::Context, S, MockVerifyingApp<B, S>, B, FixedEpocher>,
        round: Round,
        digest: <B as Digestible>::Digest,
        embedded_ctx: Ctx,
        equivocating_ctx: Ctx,
        _extra: <StandardHarness as TestHarness>::ValidatorExtra,
    }

    async fn equivocation_fixture(
        context: &mut deterministic::Context,
        app: MockVerifyingApp<B, S>,
    ) -> EquivocationFixture {
        let Fixture {
            participants,
            schemes,
            ..
        } = bls12381_threshold_vrf::fixture::<V, _>(context, NAMESPACE, NUM_VALIDATORS);
        let mut oracle = setup_network_with_participants(
            context.child("network"),
            NZUsize!(1),
            participants.clone(),
            1024 * 1024,
        )
        .await;

        let me = participants[0].clone();
        let setup = StandardHarness::setup_validator(
            context.child("validator").with_attribute("index", 0),
            &mut oracle,
            me,
            ConstantProvider::new(schemes[0].clone()),
        )
        .await;
        let marshal = setup.mailbox;
        let buffer = setup.extra;

        let genesis = make_raw_block(Sha256::hash(&[b""]), Height::zero(), 0);
        let leader = participants[1].clone();

        // The view-1 block: the parent this validator last certified.
        let certified_round = Round::new(Epoch::zero(), View::new(1));
        let certified_ctx = Ctx {
            round: certified_round,
            leader: default_leader(),
            parent: (View::zero(), genesis.digest()),
        };
        let certified = B::new::<Sha256>(certified_ctx, genesis.digest(), Height::new(1), 100);
        let certified_digest = certified.digest();
        assert!(marshal.verified(certified_round, ready(certified)).await);

        // The view-2 block: notarized by the network but only nullified here,
        // so this validator never certified it.
        let notarized_round = Round::new(Epoch::zero(), View::new(2));
        let notarized_ctx = Ctx {
            round: notarized_round,
            leader: leader.clone(),
            parent: (View::new(1), certified_digest),
        };
        let notarized = B::new::<Sha256>(notarized_ctx, certified_digest, Height::new(2), 200);
        let notarized_digest = notarized.digest();
        assert!(marshal.verified(notarized_round, ready(notarized)).await);

        // The view-3 block builds on the view-2 block. The leader's broadcast
        // delivered it into the local buffer without a local verification.
        let round = Round::new(Epoch::zero(), View::new(3));
        let embedded_ctx = Ctx {
            round,
            leader: leader.clone(),
            parent: (View::new(2), notarized_digest),
        };
        let block = B::new::<Sha256>(embedded_ctx.clone(), notarized_digest, Height::new(3), 300);
        let digest = block.digest();
        assert!(
            buffer
                .broadcast(commonware_p2p::Recipients::Some(vec![]), ready(block))
                .accepted(),
            "buffer broadcast for the candidate should be accepted"
        );

        let equivocating_ctx = Ctx {
            round,
            leader,
            parent: (View::new(1), certified_digest),
        };

        let marshaled = Deferred::new(
            context.child("deferred"),
            app,
            marshal,
            FixedEpocher::new(BLOCKS_PER_EPOCH),
        );
        context.sleep(Duration::from_millis(10)).await;

        EquivocationFixture {
            marshaled,
            round,
            digest,
            embedded_ctx,
            equivocating_ctx,
            _extra: buffer,
        }
    }

    /// A leader can equivocate at the proposal layer: sign one proposal for a
    /// digest declaring the notarized view-2 parent (sent to the validators
    /// that certified view 2) and another declaring the certified view-1
    /// parent (sent to a validator that only nullified view 2). Both pass
    /// their recipients' parent selection and carry the same digest because
    /// they name the same block.
    ///
    /// Refusing to notarize the mismatched proposal is correct. That refusal
    /// must not outlive the proposal: once the honest notarization for
    /// `(round, digest)` arrives, certification must judge the block against
    /// its embedded context (defended by the notarizing quorum) and succeed.
    /// Adopting the verdict computed under the equivocating context wedges
    /// this validator in the view: the other honest validators have certified
    /// and advanced, leaving too few validators to form either a nullification
    /// or a finalization after the Byzantine validator stops participating.
    #[test_traced("WARN")]
    fn test_certify_not_poisoned_by_equivocating_parent_verify() {
        let runner = deterministic::Runner::timed(Duration::from_secs(30));
        runner.start(|mut context| async move {
            let mut fixture = equivocation_fixture(&mut context, MockVerifyingApp::new()).await;

            let verify_rx = fixture
                .marshaled
                .verify(fixture.equivocating_ctx.clone(), fixture.digest)
                .await;
            assert!(
                !verify_rx.await.expect("verify result missing"),
                "the equivocating proposal must not be notarized"
            );

            let certify_rx = fixture
                .marshaled
                .certify(fixture.round, fixture.digest)
                .await;
            select! {
                result = certify_rx => {
                    assert!(
                        result.expect("certify result missing"),
                        "certify of the notarized digest must not adopt the verdict computed under the equivocating context"
                    );
                },
                _ = context.sleep(Duration::from_secs(5)) => {
                    panic!("certify should resolve promptly");
                },
            }
        });
    }

    /// Control for the equivocation tests: a live application rejection under
    /// the matching context is a real verdict. Certification must keep
    /// honoring it, because deferred voting means a notarization can exist
    /// for an application-invalid block.
    #[test_traced("WARN")]
    fn test_certify_honors_application_rejection() {
        let runner = deterministic::Runner::timed(Duration::from_secs(30));
        runner.start(|mut context| async move {
            let mut fixture =
                equivocation_fixture(&mut context, MockVerifyingApp::with_verify_result(false))
                    .await;

            let verify_rx = fixture
                .marshaled
                .verify(fixture.embedded_ctx.clone(), fixture.digest)
                .await;
            assert!(
                verify_rx.await.expect("verify result missing"),
                "optimistic verify accepts an available block with a matching context"
            );

            let certify_rx = fixture
                .marshaled
                .certify(fixture.round, fixture.digest)
                .await;
            select! {
                result = certify_rx => {
                    assert!(
                        !result.expect("certify result missing"),
                        "certify must propagate the application rejection"
                    );
                },
                _ = context.sleep(Duration::from_secs(5)) => {
                    panic!("certify should resolve promptly");
                },
            }
        });
    }

    /// Without a registered gate (never verified locally, or the gate was lost
    /// to a restart), certification runs the application against the block's
    /// embedded context. A live rejection there must reach consensus too.
    #[test_traced("WARN")]
    fn test_certify_without_prior_verify_honors_application_rejection() {
        let runner = deterministic::Runner::timed(Duration::from_secs(30));
        runner.start(|mut context| async move {
            let mut fixture =
                equivocation_fixture(&mut context, MockVerifyingApp::with_verify_result(false))
                    .await;

            // No prior verify, so no gate exists and certify falls through to
            // the embedded-context path.
            let certify_rx = fixture
                .marshaled
                .certify(fixture.round, fixture.digest)
                .await;
            select! {
                result = certify_rx => {
                    assert!(
                        !result.expect("certify result missing"),
                        "certify must propagate the application rejection"
                    );
                },
                _ = context.sleep(Duration::from_secs(5)) => {
                    panic!("certify should resolve promptly");
                },
            }
        });
    }

    impl Deferred<deterministic::Context, S, MockVerifyingApp<B, S>, B, FixedEpocher> {
        /// Exposes the gates this wrapper prunes to the wrapper tests shared by the standard
        /// variants.
        pub(in crate::marshal::standard) const fn gates(&self) -> &Gates<D, Digested<B>> {
            &self.gates
        }
    }
}