-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathactor.rs
More file actions
2165 lines (2024 loc) · 85.2 KB
/
actor.rs
File metadata and controls
2165 lines (2024 loc) · 85.2 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::{
acks::{PendingAck, PendingAcks},
cache,
delivery::PendingVerification,
floor::Floor,
mailbox::{CommitmentFallback, Mailbox, Message},
subscriptions::{Key as SubscriptionKey, KeyFor as SubscriptionKeyFor, Subscriptions},
variant::OptionalBuffer,
Buffer, Variant,
};
use crate::{
marshal::{
resolver::handler::{self, Annotation, Key, Request},
store::{Blocks, Certificates},
Config, Identifier as BlockID, Start, Update,
},
simplex::{
scheme::Scheme,
types::{verify_certificates, Finalization, Notarization, Subject},
},
types::{Epoch, Epocher, Height, Round, ViewDelta},
Block, Epochable, Heightable, Reporter,
};
use bytes::Bytes;
use commonware_actor::mailbox;
use commonware_codec::{Decode, Encode, Read};
use commonware_cryptography::{
certificate::{Provider, Scheme as CertificateScheme},
Digestible,
};
use commonware_macros::select_loop;
use commonware_p2p::Recipients;
use commonware_parallel::Strategy;
use commonware_resolver::{Delivery, Resolver};
use commonware_runtime::{
spawn_cell,
telemetry::metrics::{Gauge, GaugeExt, MetricsExt as _},
BufferPooler, Clock, ContextCell, Handle, Metrics, Spawner, Storage,
};
use commonware_storage::{
archive::Identifier as ArchiveID,
metadata::{self, Metadata},
};
use commonware_utils::{
acknowledgement::Exact,
channel::{fallible::OneshotExt, oneshot},
futures::AbortablePool,
sequence::U64,
Acknowledgement, BoxedError,
};
use futures::{future::join_all, try_join};
use rand_core::CryptoRngCore;
use std::{collections::BTreeMap, future::Future, num::NonZeroUsize, sync::Arc};
use tracing::{debug, warn};
/// The key used to store the last processed height in the metadata store.
const LATEST_KEY: U64 = U64::new(0xFF);
// Resolver request keys are expressed in the variant commitment type, which
// may differ from the block digest for coded variants.
type ResolverRequestFor<V> = Key<<V as Variant>::Commitment>;
// A resolver delivery plus the peer-validity response channel. Local
// annotations on the delivery decide how accepted data is used.
struct ResolverDelivery<V: Variant> {
delivery: Delivery<ResolverRequestFor<V>, Annotation>,
value: Bytes,
response: oneshot::Sender<bool>,
}
/// The [Actor] is responsible for receiving uncertified blocks from the broadcast mechanism,
/// receiving notarizations and finalizations from consensus, and reconstructing a total order
/// of blocks.
///
/// The actor is designed to be used in a view-based model. Each view corresponds to a
/// potential block in the chain. The actor will only finalize a block if it has a
/// corresponding finalization.
///
/// The actor also provides a backfill mechanism for missing blocks. If the actor receives a
/// finalization for a block that is ahead of its current view, it will request the missing blocks
/// from its peers. This ensures that the actor can catch up to the rest of the network if it falls
/// behind.
pub struct Actor<E, V, P, FC, FB, ES, T, A = Exact>
where
E: BufferPooler + CryptoRngCore + Spawner + Metrics + Clock + Storage,
V: Variant,
P: Provider<Scope = Epoch, Scheme: Scheme<V::Commitment>>,
FC: Certificates<
BlockDigest = <V::Block as Digestible>::Digest,
Commitment = V::Commitment,
Scheme = P::Scheme,
>,
FB: Blocks<Block = V::StoredBlock>,
ES: Epocher,
T: Strategy,
A: Acknowledgement,
{
// ---------- Context ----------
context: ContextCell<E>,
// ---------- Message Passing ----------
// Mailbox
mailbox: mailbox::Receiver<Message<P::Scheme, V>>,
// ---------- Configuration ----------
// Provider for epoch-specific signing schemes
provider: P,
// Epoch configuration
epocher: ES,
// Minimum number of views to retain temporary data after the application processes a block
view_retention_timeout: ViewDelta,
// Maximum number of blocks to repair at once
max_repair: NonZeroUsize,
// Codec configuration for block type
block_codec_config: <V::ApplicationBlock as Read>::Cfg,
// Strategy for parallel operations
strategy: T,
// ---------- State ----------
// Last proposed block
last_proposed_block: Option<(Round, V::Commitment, V::Block)>,
// Current processed floor and any pending floor update
floor: Floor<P::Scheme, V::Commitment>,
// Pending application acknowledgements
pending_acks: PendingAcks<V, A>,
// Highest known finalized height
tip: Height,
// Outstanding subscriptions for blocks
block_subscriptions: Subscriptions<V>,
// ---------- Storage ----------
// Prunable cache
cache: cache::Manager<E, V, P::Scheme>,
// Metadata tracking application progress
application_metadata: Metadata<E, U64, Height>,
// Finalizations stored by height
finalizations_by_height: FC,
// Finalized blocks stored by height
finalized_blocks: FB,
// ---------- Metrics ----------
// Latest height metric
finalized_height: Gauge,
// Latest processed height
processed_height: Gauge,
}
impl<E, V, P, FC, FB, ES, T, A> Actor<E, V, P, FC, FB, ES, T, A>
where
E: BufferPooler + CryptoRngCore + Spawner + Metrics + Clock + Storage,
V: Variant,
P: Provider<Scope = Epoch, Scheme: Scheme<V::Commitment>>,
FC: Certificates<
BlockDigest = <V::Block as Digestible>::Digest,
Commitment = V::Commitment,
Scheme = P::Scheme,
>,
FB: Blocks<Block = V::StoredBlock>,
ES: Epocher,
T: Strategy,
A: Acknowledgement,
{
/// Create a new application actor.
pub async fn init(
context: E,
finalizations_by_height: FC,
mut finalized_blocks: FB,
config: Config<P, ES, T, V::ApplicationBlock, V::Block, V::Commitment>,
) -> (Self, Mailbox<P::Scheme, V>, Height) {
// Initialize cache
let prunable_config = cache::Config {
partition_prefix: format!("{}-cache", config.partition_prefix),
prunable_items_per_section: config.prunable_items_per_section,
replay_buffer: config.replay_buffer,
key_write_buffer: config.key_write_buffer,
value_write_buffer: config.value_write_buffer,
key_page_cache: config.page_cache.clone(),
};
let cache = cache::Manager::init(
context.child("cache"),
prunable_config,
config.block_codec_config.clone(),
)
.await;
// Initialize metadata tracking application progress
let application_metadata = Metadata::init(
context.child("application_metadata"),
metadata::Config {
partition: format!("{}-application-metadata", config.partition_prefix),
codec_config: (),
},
)
.await
.expect("failed to initialize application metadata");
let last_processed_height = application_metadata
.get(&LATEST_KEY)
.copied()
.unwrap_or(Height::zero());
// Genesis is a local anchor. A floor finalization is verified and
// resolved after `run` receives the resolver and buffer.
let pending_floor_anchor = match config.start {
Start::Genesis(anchor) => {
assert_eq!(
anchor.height(),
Height::zero(),
"genesis anchor must be at height zero"
);
Self::ensure_genesis_anchor(&mut finalized_blocks, anchor, last_processed_height)
.await;
None
}
Start::Floor(finalization) => Some(finalization),
};
let last_processed_round =
Self::latest_processed_round(&finalizations_by_height, last_processed_height).await;
// Create metrics
let finalized_height = context.gauge("finalized_height", "Finalized height of application");
let processed_height = context.gauge("processed_height", "Processed height of application");
let _ = processed_height.try_set(last_processed_height.get());
let floor = pending_floor_anchor.map_or_else(
|| Floor::resolved(last_processed_height, last_processed_round),
|finalization| {
Floor::awaiting_anchor(last_processed_height, last_processed_round, finalization)
},
);
// Initialize mailbox
let (sender, mailbox) = mailbox::new(context.child("mailbox"), config.mailbox_size);
(
Self {
context: ContextCell::new(context),
mailbox,
provider: config.provider,
epocher: config.epocher,
view_retention_timeout: config.view_retention_timeout,
max_repair: config.max_repair,
block_codec_config: config.block_codec_config,
strategy: config.strategy,
last_proposed_block: None,
floor,
pending_acks: PendingAcks::new(config.max_pending_acks.get()),
tip: Height::zero(),
block_subscriptions: Subscriptions::new(),
cache,
application_metadata,
finalizations_by_height,
finalized_blocks,
finalized_height,
processed_height,
},
Mailbox::new(sender),
last_processed_height,
)
}
async fn ensure_genesis_anchor(
finalized_blocks: &mut FB,
anchor: V::Block,
last_processed_height: Height,
) {
let anchor_height = anchor.height();
let anchor_commitment = V::commitment(&anchor);
match finalized_blocks
.get(ArchiveID::Index(anchor_height.get()))
.await
{
Ok(Some(stored)) => {
let stored: V::Block = stored.into();
assert_eq!(
stored.height(),
anchor_height,
"stored genesis block height mismatch"
);
assert!(
V::commitment(&stored) == anchor_commitment,
"stored genesis block does not match configured anchor"
);
}
Ok(None) => {
if anchor_height < last_processed_height {
warn!(
height = %anchor_height,
existing = %last_processed_height,
"ignoring stale anchor"
);
return;
}
finalized_blocks
.put(anchor.into())
.await
.expect("failed to store startup anchor");
finalized_blocks
.sync()
.await
.expect("failed to sync startup anchor");
debug!(height = %anchor_height, "stored genesis block");
}
Err(err) => panic!("failed to check startup anchor: {err}"),
}
}
/// Start the actor.
pub fn start<R, Buf>(
mut self,
application: impl Reporter<Activity = Update<V::ApplicationBlock, A>>,
buffer: Option<Buf>,
resolver: (handler::Receiver<V::Commitment>, R),
) -> Handle<()>
where
R: Resolver<
Key = ResolverRequestFor<V>,
Subscriber = Annotation,
PublicKey = <P::Scheme as CertificateScheme>::PublicKey,
>,
Buf: Buffer<V, PublicKey = <P::Scheme as CertificateScheme>::PublicKey>,
{
let buffer = OptionalBuffer::new(buffer);
spawn_cell!(self.context, self.run(application, buffer, resolver))
}
/// Run the application actor.
async fn run<R, Buf>(
mut self,
mut application: impl Reporter<Activity = Update<V::ApplicationBlock, A>>,
mut buffer: OptionalBuffer<V, Buf>,
(mut resolver_rx, mut resolver): (handler::Receiver<V::Commitment>, R),
) where
R: Resolver<
Key = ResolverRequestFor<V>,
Subscriber = Annotation,
PublicKey = <P::Scheme as CertificateScheme>::PublicKey,
>,
Buf: Buffer<V, PublicKey = <P::Scheme as CertificateScheme>::PublicKey>,
{
// Create a local pool for waiter futures.
let mut waiters = AbortablePool::<Result<V::Block, SubscriptionKeyFor<V>>>::default();
// Get tip and send to application
let tip = self.get_latest().await;
if let Some((height, digest, round)) = tip {
application.report(Update::Tip(round, height, digest));
self.tip = height;
let _ = self.finalized_height.try_set(height.get());
}
// Load persisted cache epochs so find_block can discover blocks
// written before the last shutdown.
self.cache.load_persisted_epochs().await;
// A configured floor follows the same path as `SetFloor`: verify it,
// then apply a local anchor or fetch the anchor block.
if let Some(finalization) = self.floor.take_pending_anchor() {
self.install_floor(
finalization,
false,
&mut resolver,
&mut buffer,
&mut application,
)
.await;
}
// Attempt to repair any gaps in the finalized blocks archive, if there are any.
if self
.try_repair_gaps(&mut buffer, &mut resolver, &mut application)
.await
{
self.sync_finalized().await;
}
// Attempt to dispatch the next finalized block to the application, if it is ready.
self.try_dispatch_blocks(&mut application).await;
select_loop! {
self.context,
on_start => {
// Remove any dropped subscribers. If all subscribers dropped, abort the waiter.
self.block_subscriptions.retain_open();
},
on_stopped => {
debug!("context shutdown, stopping marshal");
},
// Handle waiter completions first
Ok(completion) = waiters.next_completed() else continue => match completion {
Ok(block) => self.block_subscriptions.notify(&block),
Err(key) => {
match key {
SubscriptionKey::Digest(digest) => {
debug!(
?digest,
"buffer subscription closed, canceling local subscribers"
);
}
SubscriptionKey::Commitment(commitment) => {
debug!(
?commitment,
"buffer subscription closed, canceling local subscribers"
);
}
}
self.block_subscriptions.remove(&key);
}
},
// Handle application acknowledgements (drain all ready acks, sync once)
result = self.pending_acks.current() => {
self.handle_ack(result, &mut application, &mut buffer, &mut resolver)
.await;
},
// Handle consensus inputs before backfill or resolver traffic
Some(message) = self.mailbox.recv() else {
debug!("mailbox closed, shutting down");
break;
} => {
self.handle_mailbox_message(
message,
&mut resolver,
&mut waiters,
&mut buffer,
&mut application,
)
.await;
},
// Handle resolver messages last (batched up to max_repair, sync once)
Some(message) = resolver_rx.recv() else {
debug!("handler closed, shutting down");
return;
} => {
self.handle_resolver_message(
message,
&mut resolver_rx,
&mut resolver,
&mut buffer,
&mut application,
)
.await;
},
}
}
/// Handles one ready application acknowledgement and drains any queued acks
/// that are already complete.
async fn handle_ack<Buf, R>(
&mut self,
result: <A::Waiter as Future>::Output,
application: &mut impl Reporter<Activity = Update<V::ApplicationBlock, A>>,
buffer: &mut OptionalBuffer<V, Buf>,
resolver: &mut R,
) where
Buf: Buffer<V>,
R: Resolver<
Key = ResolverRequestFor<V>,
Subscriber = Annotation,
PublicKey = <P::Scheme as CertificateScheme>::PublicKey,
>,
{
// Start with the ack that woke this `select_loop!` arm.
let mut pending = Some(self.pending_acks.complete_current(result));
let last_acked_commitment = loop {
let (height, commitment, result) = pending.take().expect("pending ack must exist");
match result {
Ok(()) => {
// Apply in-memory progress updates for this acknowledged
// block. The metadata sync below makes drained updates durable.
self.update_processed_height(height, resolver);
self.update_processed_round(height, resolver).await;
}
Err(e) => {
// Ack failures are fatal for marshal/application coordination.
panic!("application did not acknowledge block at height {height}: {e:?}");
}
}
// Opportunistically drain any additional already-ready acks so we
// can persist one metadata sync for the whole batch below.
match self.pending_acks.pop_ready() {
Some(next) => pending = Some(next),
None => break commitment,
}
};
// Persist buffered processed-height updates once after draining all ready acks.
self.application_metadata
.sync()
.await
.expect("failed to sync application progress");
// Anything below the last acknowledged commitment is safe for the
// buffer to prune.
buffer.finalized(last_acked_commitment);
// Refill the application dispatch pipeline.
self.try_dispatch_blocks(application).await;
}
/// Handles a single mailbox message from local consensus/application callers.
async fn handle_mailbox_message<Buf, R>(
&mut self,
message: Message<P::Scheme, V>,
resolver: &mut R,
waiters: &mut AbortablePool<Result<V::Block, SubscriptionKeyFor<V>>>,
buffer: &mut OptionalBuffer<V, Buf>,
application: &mut impl Reporter<Activity = Update<V::ApplicationBlock, A>>,
) where
Buf: Buffer<V, PublicKey = <P::Scheme as CertificateScheme>::PublicKey>,
R: Resolver<
Key = ResolverRequestFor<V>,
Subscriber = Annotation,
PublicKey = <P::Scheme as CertificateScheme>::PublicKey,
>,
{
if message.response_closed() {
return;
}
match message {
Message::GetInfo {
identifier,
response,
} => {
let info = match identifier {
// TODO: Instead of pulling out the entire block, determine the
// height directly from the archive by mapping the digest to
// the index, which is the same as the height.
BlockID::Digest(digest) => self
.finalized_blocks
.get(ArchiveID::Key(&digest))
.await
.ok()
.flatten()
.map(|b| (b.height(), digest)),
BlockID::Height(height) => self.get_info_by_height(height).await,
BlockID::Latest => self.get_latest().await.map(|(h, d, _)| (h, d)),
};
response.send_lossy(info);
}
Message::GetVerified { round, response } => {
let block = self.cache.get_verified(round).await.map(Into::into);
response.send_lossy(block);
}
Message::Forward {
round,
commitment,
recipients,
} => {
if matches!(&recipients, Recipients::Some(peers) if peers.is_empty()) {
return;
}
let block = match self.take_proposed(round, commitment) {
Some(block) => block,
None => {
let Some(block) = self.find_block_by_commitment(buffer, commitment).await
else {
debug!(?commitment, "block not found for forwarding");
return;
};
block
}
};
buffer.send(round, block, recipients);
}
Message::Proposed { round, block, ack } => {
// If the round has already been pruned by tip advancement,
// `cache_verified` is a no-op because the round is below
// the retention floor (and no longer is required by consensus
// to make progress).
self.cache_verified(round, block.digest(), block.clone())
.await;
self.apply_floor_anchor(&block, buffer, application, resolver)
.await;
// Retain the block in memory so the subsequent `Forward` can
// broadcast it without reloading from storage. An older retained
// proposal (if any) is overwritten.
let commitment = V::commitment(&block);
self.last_proposed_block = Some((round, commitment, block));
ack.expect("durable ack present").send_lossy(());
}
Message::Verified { round, block, ack } => {
// If the round has already been pruned by tip advancement,
// `cache_verified` is a no-op because the round is below
// the retention floor (and no longer is required by consensus
// to make progress).
self.cache_verified(round, block.digest(), block.clone())
.await;
self.apply_floor_anchor(&block, buffer, application, resolver)
.await;
ack.expect("durable ack present").send_lossy(());
}
Message::Certified { round, block, ack } => {
// If the round has already been pruned by tip advancement,
// `cache_block` is a no-op because the round is below
// the retention floor (and no longer is required by consensus
// to make progress).
self.cache_block(round, block.digest(), block.clone()).await;
self.apply_floor_anchor(&block, buffer, application, resolver)
.await;
ack.expect("durable ack present").send_lossy(());
}
Message::Notarization { notarization } => {
let round = notarization.round();
let commitment = notarization.proposal.payload;
let digest = V::commitment_to_inner(commitment);
// Cache notarization by round.
self.cache
.put_notarization(round, digest, notarization.clone())
.await;
// A notarization alone is not enough to fetch missing proposal
// data. If the block is not locally available, remember the
// certificate and wait for a later finalization/repair path.
if let Some(block) = self.find_block_by_commitment(buffer, commitment).await {
self.cache_block(round, digest, block.clone()).await;
self.apply_floor_anchor(&block, buffer, application, resolver)
.await;
} else {
debug!(?round, "notarized block unavailable locally");
}
}
Message::Finalization { finalization } => {
let round = finalization.round();
let commitment = finalization.proposal.payload;
let digest = V::commitment_to_inner(commitment);
// Cache finalization by round.
self.cache
.put_finalization(round, digest, finalization.clone())
.await;
// Search for the finalized block locally, otherwise fetch it remotely.
if let Some(block) = self.find_block_by_commitment(buffer, commitment).await {
// The anchor path stores the floor block and finalization,
// advances floors, prunes below them, and resumes dispatch.
if self
.apply_floor_anchor(&block, buffer, application, resolver)
.await
{
return;
}
let height = block.height();
self.update_processed_round_floor(height, round, resolver)
.await;
if self
.store_finalization(height, digest, block, Some(finalization), application)
.await
{
// If a floor anchor is pending, repair and dispatch are
// no-ops until the anchor block is stored.
self.try_repair_gaps(buffer, resolver, application).await;
self.sync_finalized().await;
self.try_dispatch_blocks(application).await;
debug!(?round, %height, "finalized block stored");
}
} else {
// The finalization carries a round and commitment, but not a
// height. Keep the request round-bound until the block is decoded.
debug!(?round, ?commitment, "finalized block missing");
self.floor
.fetch_if_permitted(
resolver,
Request::finalized_block_by_round(commitment, round),
)
.ignore();
}
}
Message::GetBlock {
identifier,
response,
} => match identifier {
BlockID::Digest(digest) => {
let result = self.find_block_by_digest(buffer, digest).await;
response.send_lossy(result);
}
BlockID::Height(height) => {
let result = self.get_finalized_block(height).await;
response.send_lossy(result);
}
BlockID::Latest => {
let block = match self.get_latest().await {
Some((_, digest, _)) => self.find_block_by_digest(buffer, digest).await,
None => None,
};
response.send_lossy(block);
}
},
Message::GetFinalization { height, response } => {
let finalization = self.get_finalization_by_height(height).await;
response.send_lossy(finalization);
}
Message::GetProcessedHeight { response } => {
response.send_lossy(self.floor.processed_height());
}
Message::HintFinalized { height, targets } => {
// Skip if finalization is already available locally.
if self.get_finalization_by_height(height).await.is_some() {
return;
}
self.floor
.fetch_targeted_if_permitted(resolver, Request::finalized(height), targets)
.ignore();
}
Message::SubscribeByDigest {
digest,
fallback,
response,
} => {
self.handle_subscribe(
fallback.into(),
SubscriptionKey::Digest(digest),
response,
resolver,
waiters,
buffer,
)
.await;
}
Message::SubscribeByCommitment {
commitment,
fallback,
response,
} => {
self.handle_subscribe(
fallback,
SubscriptionKey::Commitment(commitment),
response,
resolver,
waiters,
buffer,
)
.await;
}
Message::HintNotarized { round, commitment } => {
if self
.find_block_by_commitment(buffer, commitment)
.await
.is_none()
{
self.floor
.fetch_if_permitted(resolver, Request::notarized(round))
.ignore();
}
}
Message::SetFloor { finalization } => {
self.install_floor(finalization, true, resolver, buffer, application)
.await;
}
Message::Prune { height } => {
// Only allow pruning at or below the current floor.
if height > self.floor.processed_height() {
warn!(%height, floor = %self.floor.processed_height(), "prune height above floor, ignoring");
return;
}
self.prune_finalized_archives(height)
.await
.expect("failed to prune finalized archives");
// Intentionally keep existing block subscriptions alive. Canceling
// waiters can have catastrophic consequences because actors do not
// retry subscriptions on failed channels.
}
}
}
/// Handles a batch of resolver messages, syncing finalized archives once if
/// any accepted delivery buffered a write.
async fn handle_resolver_message<Buf, R>(
&mut self,
message: handler::Message<V::Commitment>,
resolver_rx: &mut handler::Receiver<V::Commitment>,
resolver: &mut R,
buffer: &mut OptionalBuffer<V, Buf>,
application: &mut impl Reporter<Activity = Update<V::ApplicationBlock, A>>,
) where
Buf: Buffer<V, PublicKey = <P::Scheme as CertificateScheme>::PublicKey>,
R: Resolver<
Key = ResolverRequestFor<V>,
Subscriber = Annotation,
PublicKey = <P::Scheme as CertificateScheme>::PublicKey,
>,
{
let mut needs_sync = false;
let mut handled = false;
let mut produces = Vec::new();
let mut delivers = Vec::new();
// Drain up to max_repair resolver messages. Block deliveries are handled
// immediately, certificate-bearing deliveries are batched for verification,
// and produce responses wait until repair has had a chance to fill gaps.
for msg in std::iter::once(message)
.chain(std::iter::from_fn(|| resolver_rx.try_recv().ok()))
.take(self.max_repair.get())
{
if msg.response_closed() {
continue;
}
handled = true;
match msg {
handler::Message::Produce { key, response } => {
produces.push((key, response));
}
handler::Message::Deliver {
delivery,
value,
response,
} => {
needs_sync |= self
.handle_deliver(
ResolverDelivery {
delivery,
value,
response,
},
&mut delivers,
buffer,
application,
resolver,
)
.await;
}
}
}
if !handled {
return;
}
// Batch verify and process all certificate-bearing deliveries.
needs_sync |= self
.verify_delivered(delivers, buffer, application, resolver)
.await;
// Attempt to fill gaps before handling produce requests so we can serve
// data received earlier in the same batch.
needs_sync |= self.try_repair_gaps(buffer, resolver, application).await;
if needs_sync {
// Sync archives before responding to peers so accepted repair data is
// durable before this node serves it.
self.sync_finalized().await;
self.try_dispatch_blocks(application).await;
}
// Handle produce requests in parallel.
join_all(
produces
.into_iter()
.map(|(key, response)| self.handle_produce(key, response, buffer)),
)
.await;
}
/// Handle a produce request from a remote peer.
async fn handle_produce<Buf: Buffer<V>>(
&self,
key: ResolverRequestFor<V>,
response: oneshot::Sender<Bytes>,
buffer: &OptionalBuffer<V, Buf>,
) {
match key {
Key::Block(commitment) => {
let Some(block) = self.find_block_by_commitment(buffer, commitment).await else {
debug!(?commitment, "block missing on request");
return;
};
response.send_lossy(block.encode());
}
Key::Finalized { height } => {
let Some(finalization) = self.get_finalization_by_height(height).await else {
debug!(%height, "finalization missing on request");
return;
};
let Some(block) = self.get_finalized_block(height).await else {
debug!(%height, "finalized block missing on request");
return;
};
response.send_lossy((finalization, block).encode());
}
Key::Notarized { round } => {
let Some(notarization) = self.cache.get_notarization(round).await else {
debug!(?round, "notarization missing on request");
return;
};
let commitment = notarization.proposal.payload;
let Some(block) = self.find_block_by_commitment(buffer, commitment).await else {
debug!(?commitment, "block missing on request");
return;
};
response.send_lossy((notarization, block).encode());
}
}
}
/// Handle a local subscription request for a block.
async fn handle_subscribe<Buf: Buffer<V>>(
&mut self,
fallback: CommitmentFallback,
key: SubscriptionKeyFor<V>,
response: oneshot::Sender<V::Block>,
resolver: &mut impl Resolver<
Key = ResolverRequestFor<V>,
Subscriber = Annotation,
PublicKey = <P::Scheme as CertificateScheme>::PublicKey,
>,
waiters: &mut AbortablePool<Result<V::Block, SubscriptionKeyFor<V>>>,
buffer: &mut OptionalBuffer<V, Buf>,
) {
let digest = match key {
SubscriptionKey::Digest(digest) => digest,
SubscriptionKey::Commitment(commitment) => V::commitment_to_inner(commitment),
};
// Check for block locally.
let block = match key {
SubscriptionKey::Digest(digest) => self.find_block_by_digest(buffer, digest).await,
SubscriptionKey::Commitment(commitment) => {
self.find_block_by_commitment(buffer, commitment).await
}
};
if let Some(block) = block {
response.send_lossy(block);
return;
}
// We don't have the block locally. Local-only waits reach this point
// without a round or height, so they only register a subscriber below.
//
// Round-based fetching is for notarized proposal lookups whose height is
// not known before the request. Height-based fetching is only for callers
// that already have a validated pruning height.
match fallback {
CommitmentFallback::FetchByRound { round } => {
// Fetch the notarized proposal for this round. The response
// must include a certificate so the commitment is tied to the
// certified round context. The decoded block is heightable, but
// that height is not known soon enough to key, coalesce, or prune
// the in-flight resolver request.
if self
.floor
.fetch_if_permitted(resolver, Request::notarized(round))
.denied()
{
return;
}
debug!(?round, ?digest, "requested block missing");
}
CommitmentFallback::FetchByCommitment { height } => {
let commitment = match key {
SubscriptionKey::Commitment(commitment) => commitment,
SubscriptionKey::Digest(_) => {
unreachable!("digest subscriptions cannot request commitment fallback")
}
};
// This path is only for accepted ancestry or finalized repair,
// never for a candidate block's immediate parent.
if self
.floor
.fetch_if_permitted(resolver, Request::certified_block(commitment, height))
.denied()
{
return;
}
debug!(%height, ?commitment, ?digest, "requested certified ancestry block missing");
}
CommitmentFallback::Wait => {}
}
let round = match fallback {
CommitmentFallback::FetchByRound { round } => Some(round),
CommitmentFallback::Wait | CommitmentFallback::FetchByCommitment { .. } => None,
};
// Register subscriber.
match key {
SubscriptionKey::Digest(digest) => {
debug!(?round, ?digest, "registering subscriber");
}
SubscriptionKey::Commitment(commitment) => {
debug!(?round, ?commitment, ?digest, "registering subscriber");
}
}
self.block_subscriptions
.insert(key, response, waiters, buffer);
}
/// Verifies and installs a floor, fetching the anchor block if needed.
async fn install_floor<Buf, R>(
&mut self,
finalization: Finalization<P::Scheme, V::Commitment>,
skip_if_superseded: bool,
resolver: &mut R,
buffer: &mut OptionalBuffer<V, Buf>,
application: &mut impl Reporter<Activity = Update<V::ApplicationBlock, A>>,