-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathmailbox.rs
More file actions
1544 lines (1417 loc) · 56.1 KB
/
mailbox.rs
File metadata and controls
1544 lines (1417 loc) · 56.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use super::Variant;
use crate::{
marshal::{
ancestry::{AncestorStream, Ancestry, BlockProvider},
Identifier,
},
simplex::types::{Activity, Finalization, Notarization},
types::{Height, Round},
Reporter,
};
use commonware_actor::{
mailbox::{Overflow, Policy, Sender},
Feedback,
};
use commonware_cryptography::{certificate::Scheme, Digestible};
use commonware_p2p::Recipients;
use commonware_utils::{channel::oneshot, vec::NonEmptyVec};
use std::collections::{btree_map::Entry, BTreeMap, VecDeque};
/// Messages sent to the marshal [Actor](super::Actor).
///
/// These messages are sent from the consensus engine and other parts of the
/// system to drive the state of the marshal.
pub(crate) enum Message<S: Scheme, V: Variant> {
/// A request to retrieve the `(height, digest)` of a block by its identifier.
/// The block must be finalized; returns `None` if the block is not finalized.
GetInfo {
/// The identifier of the block to get the information of.
identifier: Identifier<<V::Block as Digestible>::Digest>,
/// A channel to send the retrieved `(height, digest)`.
response: oneshot::Sender<Option<(Height, <V::Block as Digestible>::Digest)>>,
},
/// A request to retrieve a block by its identifier.
///
/// Requesting by [Identifier::Height] or [Identifier::Latest] will only return finalized
/// blocks, whereas requesting by [Identifier::Digest] may return non-finalized
/// or even unverified blocks.
GetBlock {
/// The identifier of the block to retrieve.
identifier: Identifier<<V::Block as Digestible>::Digest>,
/// A channel to send the retrieved block.
response: oneshot::Sender<Option<V::Block>>,
},
/// A request to retrieve a finalization by height.
GetFinalization {
/// The height of the finalization to retrieve.
height: Height,
/// A channel to send the retrieved finalization.
response: oneshot::Sender<Option<Finalization<S, V::Commitment>>>,
},
/// A request to retrieve the latest processed height.
GetProcessedHeight {
/// A channel to send the latest processed height.
response: oneshot::Sender<Height>,
},
/// A hint that a finalized block may be available at a given height.
///
/// This triggers a network fetch if the finalization is not available locally.
/// This is fire-and-forget: the finalization will be stored in marshal and
/// delivered via the normal finalization flow when available.
///
/// The height must be covered by both the epocher and the provider. If the
/// epocher cannot map the height to an epoch, or the provider cannot supply
/// a scheme for that epoch, the hint is silently dropped.
///
/// Targets are required because this is typically called when a peer claims to
/// be ahead. If a target returns invalid data, the resolver will block them.
/// Sending this message multiple times with different targets adds to the
/// target set.
HintFinalized {
/// The height of the finalization to fetch.
height: Height,
/// Target peers to fetch from. Added to any existing targets for this height.
targets: NonEmptyVec<S::PublicKey>,
},
/// A request to subscribe to a block by its digest.
SubscribeByDigest {
/// The digest of the block to retrieve.
digest: <V::Block as Digestible>::Digest,
/// How marshal should behave if the block is missing locally.
fallback: DigestFallback,
/// A channel to send the retrieved block.
response: oneshot::Sender<V::Block>,
},
/// A request to subscribe to a block by its commitment.
SubscribeByCommitment {
/// The commitment of the block to retrieve.
commitment: V::Commitment,
/// How marshal should behave if the block is missing locally.
fallback: CommitmentFallback,
/// A channel to send the retrieved block.
response: oneshot::Sender<V::Block>,
},
/// A hint to fetch a notarized block by round without adding another local subscriber.
///
/// `commitment` is used as a locality check: if the block is already
/// available locally, the fetch is skipped.
HintNotarized {
/// The notarized round to request.
round: Round,
/// The commitment used to short-circuit if the block is already local.
commitment: V::Commitment,
},
/// A request to retrieve the verified block previously persisted for `round`.
GetVerified {
/// The round to query.
round: Round,
/// A channel to send the retrieved block, if any.
response: oneshot::Sender<Option<V::Block>>,
},
/// A request to forward a block to a set of recipients.
Forward {
/// The round in which the block was proposed.
round: Round,
/// The commitment of the block to forward.
commitment: V::Commitment,
/// The recipients to forward the block to.
recipients: Recipients<S::PublicKey>,
},
/// A notification that a block has been locally proposed by this node.
Proposed {
/// The round in which the block was proposed.
round: Round,
/// The proposed block.
block: V::Block,
/// A channel signaled once the block is durably stored.
ack: Option<oneshot::Sender<()>>,
},
/// A notification that a block has been verified by the application.
Verified {
/// The round in which the block was verified.
round: Round,
/// The verified block.
block: V::Block,
/// A channel signaled once the block is durably stored.
ack: Option<oneshot::Sender<()>>,
},
/// A notification that a block has been certified by the application.
Certified {
/// The round in which the block was certified.
round: Round,
/// The certified block.
block: V::Block,
/// A channel signaled once the block is durably stored.
ack: Option<oneshot::Sender<()>>,
},
/// Attempts to set the sync starting point from an already-processed finalization.
///
/// If the verified finalization advances marshal's current floor, marshal
/// anchors on its block, prunes below it, then syncs and delivers blocks
/// starting at the floor height + 1. Stale or superseded floors may be
/// ignored.
///
/// To prune data without changing the sync starting point, use
/// [Message::Prune] instead.
SetFloor {
/// The candidate floor finalization, verified by the actor before use.
finalization: Finalization<S, V::Commitment>,
},
/// Requests pruning finalized blocks and certificates below the given height.
///
/// Unlike [Message::SetFloor], this does not affect the sync starting
/// point. Requests above marshal's current floor are ignored.
Prune {
/// The minimum height to keep (blocks below this are pruned).
height: Height,
},
/// A notarization from the consensus engine.
Notarization {
/// The notarization.
notarization: Notarization<S, V::Commitment>,
},
/// A finalization from the consensus engine.
Finalization {
/// The finalization.
finalization: Finalization<S, V::Commitment>,
},
}
/// How a digest-keyed block subscription should behave when the block is missing locally.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DigestFallback {
/// Wait for local availability only.
Wait,
/// Request the notarized proposal for `round` from peers.
///
/// Use this only when the caller has a trusted round for the digest. Digest-keyed
/// subscriptions intentionally cannot request exact commitment fetches.
FetchByRound { round: Round },
}
impl From<DigestFallback> for CommitmentFallback {
fn from(fallback: DigestFallback) -> Self {
match fallback {
DigestFallback::Wait => Self::Wait,
DigestFallback::FetchByRound { round } => Self::FetchByRound { round },
}
}
}
/// How a commitment-keyed block subscription should behave when the block is missing locally.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CommitmentFallback {
/// Wait for local availability only.
///
/// Use this for pending candidate proposal data before notarization.
Wait,
/// Request the notarized proposal for `round` from peers.
///
/// Use this when the caller knows a trusted notarized or certified round and
/// commitment but not the proposal height, such as proposal construction,
/// verification of a known child, or certification of a notarized candidate. Do not infer
/// height from the finalized tip or another block: proposals may build on
/// a certified parent that is not finalized locally yet, and an unverified
/// child may lie about its height.
///
/// The returned block is heightable once decoded, but that is too late for
/// the in-flight resolver key or pruning bound.
FetchByRound { round: Round },
/// Request the exact commitment from peers and prune the request at
/// `height`.
///
/// Use this only when no certified parent round is available and the caller
/// has a locally validated pruning bound, such as repairing a finalized gap
/// or walking an accepted ancestry stream. Do not use it for a candidate's
/// immediate parent when the consensus context supplies the parent round.
///
/// The height is not sent to peers. It is a local pruning hint for request
/// retention, not part of response validity: a fetched block is delivered
/// if its commitment matches, and certified storage uses the decoded block
/// height.
FetchByCommitment { height: Height },
}
impl<S: Scheme, V: Variant> Message<S, V> {
fn stale(&self, current: Option<Height>) -> bool {
match self {
// Height-targeted reads below the floor can never be served
Self::GetInfo {
identifier: Identifier::Height(height),
..
}
| Self::GetBlock {
identifier: Identifier::Height(height),
..
}
| Self::GetFinalization { height, .. } => Some(*height) < current,
// Hints only inform the actor about heights strictly above the floor
Self::HintFinalized { height, .. } => Some(*height) <= current,
// Durability acks cannot be dropped: callers depend on them
Self::Proposed { .. } | Self::Verified { .. } | Self::Certified { .. } => false,
// Digest and latest lookups are not bound to a specific height
Self::GetBlock {
identifier: Identifier::Digest(_) | Identifier::Latest,
..
}
| Self::GetInfo {
identifier: Identifier::Digest(_) | Identifier::Latest,
..
}
| Self::GetProcessedHeight { .. } => false,
Self::HintNotarized { .. } => false,
Self::SubscribeByDigest { .. }
| Self::SubscribeByCommitment { .. }
| Self::GetVerified { .. }
| Self::Forward { .. }
| Self::SetFloor { .. }
| Self::Prune { .. }
| Self::Notarization { .. }
| Self::Finalization { .. } => false,
}
}
pub(crate) fn response_closed(&self) -> bool {
match self {
Self::GetInfo { response, .. } => response.is_closed(),
Self::GetBlock { response, .. } | Self::GetVerified { response, .. } => {
response.is_closed()
}
Self::GetFinalization { response, .. } => response.is_closed(),
Self::GetProcessedHeight { response } => response.is_closed(),
Self::SubscribeByDigest { response, .. }
| Self::SubscribeByCommitment { response, .. } => response.is_closed(),
Self::HintNotarized { .. } => false,
Self::HintFinalized { .. }
| Self::Forward { .. }
| Self::Proposed { .. }
| Self::Verified { .. }
| Self::Certified { .. }
| Self::SetFloor { .. }
| Self::Prune { .. }
| Self::Notarization { .. }
| Self::Finalization { .. } => false,
}
}
}
pub(crate) struct Pending<S: Scheme, V: Variant> {
floor: Option<Finalization<S, V::Commitment>>,
prune: Option<Height>,
hints: BTreeMap<Height, NonEmptyVec<S::PublicKey>>,
messages: VecDeque<PendingMessage<S, V>>,
}
enum PendingMessage<S: Scheme, V: Variant> {
Message(Message<S, V>),
HintFinalized(Height),
}
impl<S: Scheme, V: Variant> Default for Pending<S, V> {
fn default() -> Self {
Self {
floor: None,
prune: None,
hints: BTreeMap::new(),
messages: VecDeque::new(),
}
}
}
impl<S: Scheme, V: Variant> Pending<S, V> {
// Only prune advances are usable for height staleness checks. A pending
// floor finalization does not carry the block height until the block is decoded.
const fn height(&self) -> Option<Height> {
self.prune
}
fn retain(&mut self) {
let current = self.height();
self.hints.retain(|height, _| Some(*height) > current);
let hints = &self.hints;
self.messages.retain(|message| match message {
PendingMessage::Message(message) => {
!message.response_closed() && !message.stale(current)
}
PendingMessage::HintFinalized(height) => hints.contains_key(height),
});
}
fn set_floor(&mut self, finalization: Finalization<S, V::Commitment>) {
let round = finalization.round();
if self
.floor
.as_ref()
.is_some_and(|floor| floor.round() >= round)
{
return;
}
self.floor = Some(finalization);
}
fn prune(&mut self, height: Height) {
let current = self.height();
let prune = Some(height);
if self.prune >= prune {
return;
}
self.prune = self.prune.max(prune);
if self.height() > current {
self.retain();
}
}
fn extend_hint_targets(
pending: &mut NonEmptyVec<S::PublicKey>,
targets: NonEmptyVec<S::PublicKey>,
) {
for target in targets {
if !pending.contains(&target) {
pending.push(target);
}
}
}
fn hint_finalized(&mut self, height: Height, targets: NonEmptyVec<S::PublicKey>) {
// The finalized height is already covered by the floor or prune point.
let current = self.height();
if current.is_some_and(|current| height <= current) {
return;
}
match self.hints.entry(height) {
Entry::Vacant(entry) => {
entry.insert(targets);
self.messages
.push_back(PendingMessage::HintFinalized(height));
}
Entry::Occupied(mut entry) => {
Self::extend_hint_targets(entry.get_mut(), targets);
}
}
}
fn restore_hint(&mut self, height: Height, targets: NonEmptyVec<S::PublicKey>) {
match self.hints.entry(height) {
Entry::Vacant(entry) => {
entry.insert(targets);
}
Entry::Occupied(mut entry) => {
Self::extend_hint_targets(entry.get_mut(), targets);
}
}
self.messages
.push_front(PendingMessage::HintFinalized(height));
}
fn drain_one<F>(&mut self, message: Message<S, V>, push: &mut F) -> bool
where
F: FnMut(Message<S, V>) -> Option<Message<S, V>>,
{
// Receiver accepted; the message is consumed
let Some(message) = push(message) else {
return true;
};
// Receiver rejected; restore so the next drain retries from the same point
match message {
Message::SetFloor { finalization } => self.set_floor(finalization),
Message::Prune { height } => self.prune(height),
Message::HintFinalized { height, targets } => self.restore_hint(height, targets),
message => self.messages.push_front(PendingMessage::Message(message)),
}
false
}
}
impl<S: Scheme, V: Variant> Overflow<Message<S, V>> for Pending<S, V> {
fn is_empty(&self) -> bool {
self.floor.is_none()
&& self.prune.is_none()
&& self.hints.is_empty()
&& self.messages.is_empty()
}
fn drain<F>(&mut self, mut push: F)
where
F: FnMut(Message<S, V>) -> Option<Message<S, V>>,
{
// Drain floor and prune first so the actor advances its floor before
// it sees the height-bounded reads that follow
if let Some(finalization) = self.floor.take() {
if !self.drain_one(Message::SetFloor { finalization }, &mut push) {
return;
}
}
if let Some(height) = self.prune.take() {
if !self.drain_one(Message::Prune { height }, &mut push) {
return;
}
}
// Drain the remaining queued messages in FIFO order
while let Some(pending) = self.messages.pop_front() {
match pending {
PendingMessage::Message(message) => {
if message.response_closed() {
continue;
}
if !self.drain_one(message, &mut push) {
break;
}
}
PendingMessage::HintFinalized(hint_height) => {
let Some(targets) = self.hints.remove(&hint_height) else {
continue;
};
let message = Message::HintFinalized {
height: hint_height,
targets,
};
if !self.drain_one(message, &mut push) {
break;
}
}
}
}
}
}
impl<S: Scheme, V: Variant> Policy for Message<S, V> {
type Overflow = Pending<S, V>;
fn handle(overflow: &mut Self::Overflow, message: Self) -> bool {
// A closed responder cannot be served
if message.response_closed() {
return true;
}
match message {
// Coalesce hints: a single entry per height with a unioned target set
Self::HintFinalized { height, targets } => {
overflow.hint_finalized(height, targets);
}
// Floors collapse to the highest round seen; prune collapses to
// the highest height seen.
Self::SetFloor { finalization } => {
overflow.set_floor(finalization);
}
Self::Prune { height } => {
overflow.prune(height);
}
// Queue if the new message is still useful
message => {
if message.stale(overflow.height()) {
return true;
}
overflow
.messages
.push_back(PendingMessage::Message(message));
}
}
true
}
}
/// A mailbox for sending messages to the marshal [Actor](super::Actor).
#[derive(Clone)]
pub struct Mailbox<S: Scheme, V: Variant> {
sender: Sender<Message<S, V>>,
}
impl<S: Scheme, V: Variant> Mailbox<S, V> {
/// Creates a new mailbox.
pub(crate) const fn new(sender: Sender<Message<S, V>>) -> Self {
Self { sender }
}
/// Create an ancestor stream that fetches missing parents by commitment.
///
/// This stream is always a fetching stream. Callers must only use it after
/// they already have a block that is safe to verify, certify, build on, or
/// repair from. From that point, every parent walked by the stream is part of
/// a certified ancestry chain, and the stream can derive each missing
/// parent's height from its child before issuing a height-bound request.
///
/// Do not use this to wait for pending candidate proposal data.
pub(crate) fn ancestor_stream<I>(
&self,
initial: I,
) -> impl Ancestry<V::ApplicationBlock> + use<S, V, I>
where
Self: BlockProvider<Block = V::ApplicationBlock>,
I: IntoIterator<Item = V::Block>,
{
AncestorStream::new(self.clone(), initial.into_iter().map(V::into_inner))
}
/// Retrieve `(height, digest)` for a finalized block by height, digest, or latest.
pub async fn get_info(
&self,
identifier: impl Into<Identifier<<V::Block as Digestible>::Digest>>,
) -> Option<(Height, <V::Block as Digestible>::Digest)> {
let identifier = identifier.into();
let (response, receiver) = oneshot::channel();
let _ = self.sender.enqueue(Message::GetInfo {
identifier,
response,
});
receiver.await.ok().flatten()
}
/// A best-effort attempt to retrieve a given block from local
/// storage. It is not an indication to go fetch the block from the network.
pub async fn get_block(
&self,
identifier: impl Into<Identifier<<V::Block as Digestible>::Digest>>,
) -> Option<V::Block> {
let identifier = identifier.into();
let (response, receiver) = oneshot::channel();
let _ = self.sender.enqueue(Message::GetBlock {
identifier,
response,
});
receiver.await.ok().flatten()
}
/// A best-effort attempt to retrieve a given [Finalization] from local
/// storage. It is not an indication to go fetch the [Finalization] from the network.
pub async fn get_finalization(&self, height: Height) -> Option<Finalization<S, V::Commitment>> {
let (response, receiver) = oneshot::channel();
let _ = self
.sender
.enqueue(Message::GetFinalization { height, response });
receiver.await.ok().flatten()
}
/// Retrieve the latest processed height.
pub async fn get_processed_height(&self) -> Option<Height> {
let (response, receiver) = oneshot::channel();
let _ = self
.sender
.enqueue(Message::GetProcessedHeight { response });
receiver.await.ok()
}
/// Hints that a finalized block may be available at the given height.
///
/// This method will request the finalization from the network via the resolver
/// if it is not available locally.
///
/// Targets are required because this is typically called when a peer claims to be
/// ahead. By targeting only those peers, we limit who we ask. If a target returns
/// invalid data, they will be blocked by the resolver. If targets don't respond
/// or return "no data", they effectively rate-limit themselves.
///
/// Calling this multiple times for the same height with different targets will
/// add to the target set if there is an ongoing fetch, allowing more peers to be tried.
///
/// This is fire-and-forget: the finalization will be stored in marshal and delivered
/// via the normal finalization flow when available.
///
/// The height must be covered by both the epocher and the provider. If the
/// epocher cannot map the height to an epoch, or the provider cannot supply
/// a scheme for that epoch, the hint is silently dropped.
pub fn hint_finalized(&self, height: Height, targets: NonEmptyVec<S::PublicKey>) {
let _ = self
.sender
.enqueue(Message::HintFinalized { height, targets });
}
/// Subscribe to a block by its digest.
///
/// If the block is found available locally, the block will be returned immediately.
///
/// If the block is not available locally, the subscription will be registered and the caller
/// will be notified when the block is available. If the block is not finalized, it's possible
/// that it may never become available.
///
/// The `fallback` parameter controls whether marshal also asks peers for the missing block.
/// Digest-keyed subscriptions only support waiting locally or fetching by round.
///
/// The oneshot receiver should be dropped to cancel the subscription.
pub fn subscribe_by_digest(
&self,
digest: <V::Block as Digestible>::Digest,
fallback: DigestFallback,
) -> oneshot::Receiver<V::Block> {
let (tx, rx) = oneshot::channel();
let _ = self.sender.enqueue(Message::SubscribeByDigest {
digest,
fallback,
response: tx,
});
rx
}
/// Subscribe to a block by its commitment.
///
/// If the block is found available locally, the block will be returned immediately.
///
/// If the block is not available locally, the subscription will be registered and the caller
/// will be notified when the block is available. If the block is not finalized, it's possible
/// that it may never become available.
///
/// The `fallback` parameter controls whether marshal also asks peers for the missing block.
///
/// The oneshot receiver should be dropped to cancel the subscription.
pub fn subscribe_by_commitment(
&self,
commitment: V::Commitment,
fallback: CommitmentFallback,
) -> oneshot::Receiver<V::Block> {
let (tx, rx) = oneshot::channel();
let _ = self.sender.enqueue(Message::SubscribeByCommitment {
fallback,
commitment,
response: tx,
});
rx
}
/// Hint that peers may have the block notarized at `round`.
///
/// This issues a round-bound resolver request without registering a new
/// block subscriber. The `commitment` is only used to skip the request when
/// the block is already available locally.
///
/// This is useful when a local-only waiter already exists and later
/// certification makes a network fetch by notarized round valid.
pub fn hint_notarized(&self, round: Round, commitment: V::Commitment) {
let _ = self
.sender
.enqueue(Message::HintNotarized { round, commitment });
}
/// Returns a stream over the ancestry of a given block, leading up to genesis.
///
/// This stream may fetch missing parents because callers should only request
/// ancestry for data they already have locally and are willing to build on,
/// verify, certify, or repair from. It is not a candidate fetch path.
///
/// If the starting block is not found, `None` is returned.
pub async fn ancestry(
&self,
(fallback, start_digest): (DigestFallback, <V::Block as Digestible>::Digest),
) -> Option<impl Ancestry<V::ApplicationBlock> + use<S, V>>
where
Self: BlockProvider<Block = V::ApplicationBlock>,
{
let receiver = self.subscribe_by_digest(start_digest, fallback);
receiver
.await
.ok()
.map(|block| self.ancestor_stream([block]))
}
/// Returns the verified block previously persisted for `round`, if any.
pub async fn get_verified(&self, round: Round) -> Option<V::Block> {
let (response, receiver) = oneshot::channel();
let _ = self
.sender
.enqueue(Message::GetVerified { round, response });
receiver.await.ok().flatten()
}
/// Notifies the actor that a block has been locally proposed.
///
/// Returns after the block is durably persisted.
#[must_use = "callers must consider block durability before proceeding"]
pub async fn proposed(&self, round: Round, block: V::Block) -> bool {
let (ack, receiver) = oneshot::channel();
let _ = self.sender.enqueue(Message::Proposed {
round,
block,
ack: Some(ack),
});
receiver.await.is_ok()
}
/// Notifies the actor that a block has been verified.
///
/// Returns after the block is durably persisted.
#[must_use = "callers must consider block durability before proceeding"]
pub async fn verified(&self, round: Round, block: V::Block) -> bool {
let (ack, receiver) = oneshot::channel();
let _ = self.sender.enqueue(Message::Verified {
round,
block,
ack: Some(ack),
});
receiver.await.is_ok()
}
/// Notifies the actor that a block has been certified.
///
/// Returns after the block is durably persisted.
#[must_use = "callers must consider block durability before proceeding"]
pub async fn certified(&self, round: Round, block: V::Block) -> bool {
let (ack, receiver) = oneshot::channel();
let _ = self.sender.enqueue(Message::Certified {
round,
block,
ack: Some(ack),
});
receiver.await.is_ok()
}
/// Attempts to set the sync starting point from an already-processed finalization.
///
/// If the verified finalization advances marshal's current floor, marshal
/// anchors on its block, prunes below it, then syncs and delivers blocks
/// starting at the floor height + 1. Stale or superseded floors may be
/// ignored.
///
/// To prune data without changing the sync starting point, use
/// [Self::prune] instead.
/// Use [`crate::marshal::Config::start`] to provide the startup anchor.
pub fn set_floor(&self, finalization: Finalization<S, V::Commitment>) {
let _ = self.sender.enqueue(Message::SetFloor { finalization });
}
/// Requests pruning finalized blocks and certificates below the given height.
///
/// Unlike [Self::set_floor], this does not affect the sync starting point.
/// Requests above marshal's current floor are ignored.
pub fn prune(&self, height: Height) {
let _ = self.sender.enqueue(Message::Prune { height });
}
/// Forward a block to a set of recipients.
pub fn forward(
&self,
round: Round,
commitment: V::Commitment,
recipients: Recipients<S::PublicKey>,
) -> Feedback {
self.sender.enqueue(Message::Forward {
round,
commitment,
recipients,
})
}
}
impl<S: Scheme, V: Variant> Reporter for Mailbox<S, V> {
type Activity = Activity<S, V::Commitment>;
fn report(&mut self, activity: Self::Activity) -> Feedback {
let message = match activity {
Activity::Notarization(notarization) => Message::Notarization { notarization },
Activity::Finalization(finalization) => Message::Finalization { finalization },
_ => return Feedback::Ok,
};
self.sender.enqueue(message)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
marshal::{mocks::harness, standard::Standard},
simplex::{scheme::bls12381_threshold::vrf as bls12381_threshold_vrf, types::Proposal},
types::{Epoch, View},
Heightable,
};
use commonware_cryptography::{
certificate::mocks::Fixture, ed25519::PrivateKey, Digest as _, Signer as _,
};
use commonware_utils::{channel::oneshot::error::TryRecvError, test_rng_seeded};
type TestMessage = Message<harness::S, Standard<harness::B>>;
type TestPending = Pending<harness::S, Standard<harness::B>>;
fn public_key(seed: u64) -> harness::K {
PrivateKey::from_seed(seed).public_key()
}
fn round(height: u64) -> Round {
Round::new(Epoch::zero(), View::new(height))
}
fn block(height: u64) -> harness::B {
harness::make_raw_block(harness::D::EMPTY, Height::new(height), height)
}
fn commitment(height: u64) -> harness::D {
<Standard<harness::B> as Variant>::commitment(&block(height))
}
fn finalization(height: u64) -> Finalization<harness::S, harness::D> {
let mut rng = test_rng_seeded(height);
let Fixture { schemes, .. } = bls12381_threshold_vrf::fixture::<harness::V, _>(
&mut rng,
harness::NAMESPACE,
harness::NUM_VALIDATORS,
);
let proposal = Proposal::new(round(height), View::zero(), commitment(height));
<harness::StandardHarness as harness::TestHarness>::make_finalization(
proposal,
&schemes,
harness::QUORUM,
)
}
fn get_info(height: u64) -> (TestMessage, oneshot::Receiver<Option<(Height, harness::D)>>) {
let (response, receiver) = oneshot::channel();
(
TestMessage::GetInfo {
identifier: Identifier::Height(Height::new(height)),
response,
},
receiver,
)
}
fn proposed(height: u64) -> (TestMessage, oneshot::Receiver<()>) {
let (ack, receiver) = oneshot::channel();
(
TestMessage::Proposed {
round: round(height),
block: block(height),
ack: Some(ack),
},
receiver,
)
}
fn verified(height: u64) -> (TestMessage, oneshot::Receiver<()>) {
let (ack, receiver) = oneshot::channel();
(
TestMessage::Verified {
round: round(height),
block: block(height),
ack: Some(ack),
},
receiver,
)
}
fn certified(height: u64) -> (TestMessage, oneshot::Receiver<()>) {
let (ack, receiver) = oneshot::channel();
(
TestMessage::Certified {
round: round(height),
block: block(height),
ack: Some(ack),
},
receiver,
)
}
fn get_block(height: u64) -> (TestMessage, oneshot::Receiver<Option<harness::B>>) {
let (response, receiver) = oneshot::channel();
(
TestMessage::GetBlock {
identifier: Identifier::Height(Height::new(height)),
response,
},
receiver,
)
}
fn get_finalization(
height: u64,
) -> (
TestMessage,
oneshot::Receiver<Option<Finalization<harness::S, harness::D>>>,
) {
let (response, receiver) = oneshot::channel();
(
TestMessage::GetFinalization {
height: Height::new(height),
response,
},
receiver,
)
}
fn subscribe_by_digest(height: u64) -> (TestMessage, oneshot::Receiver<harness::B>) {
let (response, receiver) = oneshot::channel();
(
TestMessage::SubscribeByDigest {
digest: block(height).digest(),
fallback: DigestFallback::FetchByRound {
round: round(height),
},
response,
},
receiver,
)
}
fn subscribe_by_commitment_message(
height: u64,
fallback: CommitmentFallback,
) -> (TestMessage, oneshot::Receiver<harness::B>) {
let (response, receiver) = oneshot::channel();
(
TestMessage::SubscribeByCommitment {
commitment: commitment(height),
fallback,
response,
},
receiver,
)
}
fn hint_finalized(height: u64, target: harness::K) -> TestMessage {
TestMessage::HintFinalized {
height: Height::new(height),
targets: NonEmptyVec::new(target),
}
}
fn set_floor(height: u64) -> TestMessage {
TestMessage::SetFloor {
finalization: finalization(height),
}
}
fn prune(height: u64) -> TestMessage {
TestMessage::Prune {
height: Height::new(height),
}
}
fn pending() -> TestPending {
TestPending::default()
}
fn drain(overflow: &mut TestPending) -> VecDeque<TestMessage> {
let mut drained = VecDeque::new();
overflow.drain(|message| {
drained.push_back(message);
None
});
drained
}
fn has_get_info(overflow: &TestPending, height: u64) -> bool {
overflow.messages.iter().any(|message| {
matches!(
message,
PendingMessage::Message(TestMessage::GetInfo {
identifier: Identifier::Height(found),
response,
..