-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathengine.rs
More file actions
5385 lines (4797 loc) · 219 KB
/
engine.rs
File metadata and controls
5385 lines (4797 loc) · 219 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
//! Shard engine for erasure-coded block distribution and reconstruction.
//!
//! This module implements the core logic for distributing blocks as erasure-coded
//! shards and reconstructing blocks from received shards.
//!
//! # Overview
//!
//! The shard engine serves two primary functions:
//! 1. Broadcast: When a node proposes a block, the engine broadcasts
//! erasure-coded shards to all participants and to non-participants in
//! aggregate membership (peers in [`commonware_p2p::PeerSetUpdate::all`]
//! but not in the epoch participant list).
//! The leader sends each participant their indexed shard.
//! 2. Block Reconstruction: When a node receives shards from peers, the engine
//! validates them and reconstructs the original block once enough valid
//! shards are available. Both participants and non-participants can
//! reconstruct blocks: participants receive their own indexed shard from
//! the leader, while non-participants reconstruct from shards gossiped
//! by participants. All participants gossip their validated shard to peers.
//!
//! # Message Flow
//!
//! ```text
//! PROPOSER
//! |
//! | Proposed(block)
//! v
//! +------------------+
//! | Shard Engine |
//! +------------------+
//! |
//! broadcast_shards (each participant's indexed shard)
//! |
//! +--------------------+--------------------+
//! | | |
//! v v v
//! Participant 0 Participant 1 Participant N
//! | | |
//! | (receive shard | (receive shard |
//! | for own index) | for own index) |
//! v v v
//! +----------+ +----------+ +----------+
//! | Validate | | Validate | | Validate |
//! | (check) | | (check) | | (check) |
//! +----------+ +----------+ +----------+
//! | | |
//! +--------------------+--------------------+
//! |
//! (gossip validated shards)
//! |
//! +--------------------+--------------------+
//! | | |
//! v v v
//! Accumulate checked shards until minimum_shards reached
//! | | |
//! v v v
//! Batch verify pending shards at quorum
//! | | |
//! v v v
//! +-------------+ +-------------+ +-------------+
//! | Reconstruct | | Reconstruct | | Reconstruct |
//! | Block | | Block | | Block |
//! +-------------+ +-------------+ +-------------+
//! ```
//!
//! # Reconstruction State Machine
//!
//! For each [`Commitment`] with a known leader, nodes (both participants
//! and non-participants) maintain a [`ReconstructionState`]. Before leader
//! announcement, shards are buffered in bounded per-peer queues:
//!
//! ```text
//! +----------------------+
//! | AwaitingQuorum |
//! | - leader known |
//! | - leader's shard | <--- verified immediately on receipt
//! | verified eagerly |
//! | - other shards | <--- buffered in pending_shards
//! | buffered |
//! +----------------------+
//! |
//! | quorum met + batch validation passes
//! v
//! +----------------------+
//! | Ready |
//! | - checked shards |
//! | (frozen; no new |
//! | shards accepted) |
//! +----------------------+
//! |
//! | checked_shards.len() >= minimum_shards
//! v
//! +----------------------+
//! | Reconstruction |
//! | Attempt |
//! +----------------------+
//! |
//! +----+----+
//! | |
//! v v
//! Success Failure
//! | |
//! v v
//! Cache Remove
//! Block State
//! ```
//!
//! _Per-peer buffers are only kept for peers in `latest.primary`, matching [`commonware_broadcast::buffered`].
//! When a peer is no longer in `latest.primary`, all its buffered shards are evicted._
//!
//! # Peer Validation and Blocking Rules
//!
//! The engine enforces strict validation to prevent Byzantine attacks:
//!
//! - All shards MUST be sent by participants in the current epoch.
//! - If the sender is the leader: the shard index MUST match the recipient's
//! participant index (for participants) or the leader's index (for
//! non-participants).
//! - If the sender is not the leader: the shard index MUST match the sender's
//! participant index (each participant can only gossip their own shard).
//! - All shards MUST pass cryptographic verification against the commitment.
//! - Each shard index may only contribute ONE shard per commitment.
//! - Sending a second shard for the same index with different data
//! (equivocation) results in blocking. Exact duplicates are silently
//! ignored.
//!
//! Peers violating these rules are blocked via the [`Blocker`] trait.
//! Validation and blocking rules are applied while a commitment is actively
//! tracked in reconstruction state. Once a block is already reconstructed and
//! cached, additional shards for that commitment are ignored.
//!
//! _If the leader is not yet known, shards are buffered in fixed-size per-peer
//! queues until consensus signals the leader via [`Discovered`]. Once leader
//! is known, buffered shards for that commitment are ingested into the active
//! state machine._
//!
//! [`Discovered`]: super::Message::Discovered
use super::{
mailbox::{Mailbox, Message},
metrics::{Peer, ShardMetrics},
};
use crate::{
marshal::coding::{
types::{CodedBlock, Shard},
validation::{validate_reconstruction, ReconstructionError as InvariantError},
},
types::{coding::Commitment, Epoch, Round},
Block, CertifiableBlock, Heightable,
};
use commonware_codec::{Decode, Error as CodecError, Read};
use commonware_coding::{Config as CodingConfig, Scheme as CodingScheme};
use commonware_cryptography::{
certificate::{Provider, Scheme as CertificateScheme},
Committable, Digestible, Hasher, PublicKey,
};
use commonware_macros::select_loop;
use commonware_p2p::{
utils::codec::{WrappedBackgroundReceiver, WrappedSender},
Blocker, Provider as PeerProvider, Receiver, Recipients, Sender,
};
use commonware_parallel::Strategy;
use commonware_runtime::{
spawn_cell,
telemetry::metrics::{histogram::HistogramExt, status::GaugeExt},
BufferPooler, Clock, ContextCell, Handle, Metrics, Spawner,
};
use commonware_utils::{
bitmap::BitMap,
channel::{fallible::OneshotExt, mpsc, oneshot},
ordered::{Quorum, Set},
};
use rand::Rng;
use std::{
collections::{BTreeMap, VecDeque},
num::NonZeroUsize,
sync::Arc,
};
use thiserror::Error;
use tracing::{debug, warn};
/// An error that can occur during reconstruction of a [`CodedBlock`] from [`Shard`]s
#[derive(Debug, Error)]
pub enum Error<C: CodingScheme> {
/// An error occurred while recovering the encoded blob from the [`Shard`]s
#[error(transparent)]
Coding(C::Error),
/// An error occurred while decoding the reconstructed blob into a [`CodedBlock`]
#[error(transparent)]
Codec(#[from] CodecError),
/// The reconstructed block's digest does not match the commitment's block digest
#[error("block digest mismatch: reconstructed block does not match commitment digest")]
DigestMismatch,
/// The reconstructed block's config does not match the commitment's coding config
#[error("block config mismatch: reconstructed config does not match commitment config")]
ConfigMismatch,
/// The reconstructed block's embedded context does not match the commitment context digest
#[error("block context mismatch: reconstructed context does not match commitment context")]
ContextMismatch,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum BlockSubscriptionKey<D> {
Commitment(Commitment),
Digest(D),
}
/// Configuration for the [`Engine`].
pub struct Config<P, S, X, D, C, H, B, T>
where
P: PublicKey,
S: Provider<Scope = Epoch>,
X: Blocker<PublicKey = P>,
D: PeerProvider<PublicKey = P>,
C: CodingScheme,
H: Hasher,
B: CertifiableBlock,
T: Strategy,
{
/// The scheme provider.
pub scheme_provider: S,
/// The peer blocker.
pub blocker: X,
/// [`Read`] configuration for decoding [`Shard`]s.
pub shard_codec_cfg: <Shard<C, H> as Read>::Cfg,
/// [`commonware_codec::Read`] configuration for decoding blocks.
pub block_codec_cfg: B::Cfg,
/// The strategy used for parallel computation.
pub strategy: T,
/// The size of the mailbox buffer.
pub mailbox_size: usize,
/// Number of shards to buffer per peer.
///
/// Shards for commitments without a reconstruction state are buffered per
/// peer in a fixed-size ring to bound memory under Byzantine spam. These
/// shards are only ingested when consensus provides a leader via
/// [`Discovered`](super::Message::Discovered).
///
/// The worst-case total memory usage for the set of shard buffers is
/// `num_participants * peer_buffer_size * max_shard_size`.
pub peer_buffer_size: NonZeroUsize,
/// Capacity of the channel between the background receiver and the engine.
///
/// The background receiver decodes incoming network messages in a separate
/// task and forwards them to the engine over an `mpsc` channel with this
/// capacity.
pub background_channel_capacity: usize,
/// Provider for peer set information. Pre-leader shards are buffered per
/// peer only while that peer appears in the
/// [`commonware_p2p::PeerSetUpdate::latest`] primary set, matching
/// [`commonware_broadcast::buffered::Engine`]. Broadcast delivery uses the
/// aggregate [`commonware_p2p::PeerSetUpdate::all`] union.
pub peer_provider: D,
}
/// A network layer for broadcasting and receiving [`CodedBlock`]s as [`Shard`]s.
///
/// When enough [`Shard`]s are present in the mailbox, the [`Engine`] may facilitate
/// reconstruction of the original [`CodedBlock`] and notify any subscribers waiting for it.
pub struct Engine<E, S, X, D, C, H, B, P, T>
where
E: BufferPooler + Rng + Spawner + Metrics + Clock,
S: Provider<Scope = Epoch>,
S::Scheme: CertificateScheme<PublicKey = P>,
X: Blocker,
D: PeerProvider<PublicKey = P>,
C: CodingScheme,
H: Hasher,
B: CertifiableBlock,
P: PublicKey,
T: Strategy,
{
/// Context held by the actor.
context: ContextCell<E>,
/// Receiver for incoming messages to the actor.
mailbox: mpsc::Receiver<Message<B, C, H, P>>,
/// The scheme provider.
scheme_provider: S,
/// The peer blocker.
blocker: X,
/// [`Read`] configuration for decoding [`Shard`]s.
shard_codec_cfg: <Shard<C, H> as Read>::Cfg,
/// [`Read`] configuration for decoding [`CodedBlock`]s.
block_codec_cfg: B::Cfg,
/// The strategy used for parallel shard verification.
strategy: T,
/// A map of [`Commitment`]s to [`ReconstructionState`]s.
state: BTreeMap<Commitment, ReconstructionState<P, C, H>>,
/// Per-peer ring buffers for shards received before leader announcement.
///
/// Empty buffers are retained for active peers and only evicted when the
/// peer leaves `latest.primary`.
peer_buffers: BTreeMap<P, VecDeque<Shard<C, H>>>,
/// Maximum buffered pre-leader shards per peer.
peer_buffer_size: NonZeroUsize,
/// Provider for peer set information.
peer_provider: D,
/// Latest union of peer membership from the peer set subscription
/// ([`commonware_p2p::PeerSetUpdate::all`]).
aggregate_peers: Set<P>,
/// Latest primary peers allowed to retain pre-leader shard buffers.
latest_primary_peers: Set<P>,
/// Capacity of the background receiver channel.
background_channel_capacity: usize,
/// An ephemeral cache of reconstructed blocks, keyed by commitment.
///
/// These blocks are evicted after a durability signal from the marshal.
/// Wrapped in [`Arc`] to enable cheap cloning when serving multiple subscribers.
reconstructed_blocks: BTreeMap<Commitment, Arc<CodedBlock<B, C, H>>>,
/// Open subscriptions for assigned shard verification for the keyed
/// [`Commitment`].
///
/// For participants, readiness is satisfied once the leader-delivered
/// shard for the local participant index has been verified. Block
/// reconstruction from peer gossip is tracked separately and does not
/// satisfy this readiness condition.
///
/// Proposers are a special case: they satisfy readiness once their local
/// proposal is cached because they already hold all shards.
assigned_shard_verified_subscriptions: BTreeMap<Commitment, Vec<oneshot::Sender<()>>>,
/// Open subscriptions for the reconstruction of a [`CodedBlock`] with
/// the keyed [`Commitment`].
#[allow(clippy::type_complexity)]
block_subscriptions:
BTreeMap<BlockSubscriptionKey<B::Digest>, Vec<oneshot::Sender<Arc<CodedBlock<B, C, H>>>>>,
/// Metrics for the shard engine.
metrics: ShardMetrics,
}
impl<E, S, X, D, C, H, B, P, T> Engine<E, S, X, D, C, H, B, P, T>
where
E: BufferPooler + Rng + Spawner + Metrics + Clock,
S: Provider<Scope = Epoch>,
S::Scheme: CertificateScheme<PublicKey = P>,
X: Blocker<PublicKey = P>,
D: PeerProvider<PublicKey = P>,
C: CodingScheme,
H: Hasher,
B: CertifiableBlock,
P: PublicKey,
T: Strategy,
{
/// Create a new [`Engine`] with the given configuration.
pub fn new(context: E, config: Config<P, S, X, D, C, H, B, T>) -> (Self, Mailbox<B, C, H, P>) {
let metrics = ShardMetrics::new(&context);
let (sender, mailbox) = mpsc::channel(config.mailbox_size);
(
Self {
context: ContextCell::new(context),
mailbox,
scheme_provider: config.scheme_provider,
blocker: config.blocker,
shard_codec_cfg: config.shard_codec_cfg,
block_codec_cfg: config.block_codec_cfg,
strategy: config.strategy,
state: BTreeMap::new(),
peer_buffers: BTreeMap::new(),
peer_buffer_size: config.peer_buffer_size,
peer_provider: config.peer_provider,
aggregate_peers: Set::default(),
latest_primary_peers: Set::default(),
background_channel_capacity: config.background_channel_capacity,
reconstructed_blocks: BTreeMap::new(),
assigned_shard_verified_subscriptions: BTreeMap::new(),
block_subscriptions: BTreeMap::new(),
metrics,
},
Mailbox::new(sender),
)
}
/// Start the engine.
pub fn start(
mut self,
network: (impl Sender<PublicKey = P>, impl Receiver<PublicKey = P>),
) -> Handle<()> {
spawn_cell!(self.context, self.run(network))
}
/// Run the shard engine's event loop.
async fn run(
mut self,
(sender, receiver): (impl Sender<PublicKey = P>, impl Receiver<PublicKey = P>),
) {
let mut sender = WrappedSender::<_, Shard<C, H>>::new(
self.context.network_buffer_pool().clone(),
sender,
);
let (receiver_service, mut receiver): (_, mpsc::Receiver<(P, Shard<C, H>)>) =
WrappedBackgroundReceiver::new(
self.context.with_label("shard_ingress"),
receiver,
self.shard_codec_cfg.clone(),
self.blocker.clone(),
self.background_channel_capacity,
&self.strategy,
);
// Keep the handle alive to prevent the background receiver from being aborted.
let _receiver_handle = receiver_service.start();
let mut peer_set_subscription = self.peer_provider.subscribe().await;
select_loop! {
self.context,
on_start => {
let _ = self
.metrics
.reconstruction_states_count
.try_set(self.state.len());
let _ = self
.metrics
.reconstructed_blocks_cache_count
.try_set(self.reconstructed_blocks.len());
// Clean up closed subscriptions.
self.block_subscriptions.retain(|_, subscribers| {
subscribers.retain(|tx| !tx.is_closed());
!subscribers.is_empty()
});
self.assigned_shard_verified_subscriptions
.retain(|_, subscribers| {
subscribers.retain(|tx| !tx.is_closed());
!subscribers.is_empty()
});
},
on_stopped => {
debug!("received shutdown signal, stopping shard engine");
},
Some(update) = peer_set_subscription.recv() else {
debug!("peer set subscription closed");
return;
} => {
let all_peers = update.all.union();
self.update_latest_primary_peers(update.latest.primary);
self.aggregate_peers = all_peers;
},
Some(message) = self.mailbox.recv() else {
debug!("shard mailbox closed, stopping shard engine");
return;
} => match message {
Message::Proposed { block, round, ack } => {
self.broadcast_shards(&mut sender, round, block).await;
ack.send_lossy(());
}
Message::Discovered {
commitment,
leader,
round,
} => {
self.handle_external_proposal(&mut sender, commitment, leader, round)
.await;
}
Message::GetByCommitment {
commitment,
response,
} => {
let block = self.reconstructed_blocks.get(&commitment).cloned();
response.send_lossy(block);
}
Message::GetByDigest { digest, response } => {
let block = self
.reconstructed_blocks
.iter()
.find_map(|(_, b)| (b.digest() == digest).then_some(b))
.cloned();
response.send_lossy(block);
}
Message::SubscribeAssignedShardVerified {
commitment,
response,
} => {
self.handle_assigned_shard_verified_subscription(commitment, response);
}
Message::SubscribeByCommitment {
commitment,
response,
} => {
self.handle_block_subscription(
BlockSubscriptionKey::Commitment(commitment),
response,
);
}
Message::SubscribeByDigest { digest, response } => {
self.handle_block_subscription(BlockSubscriptionKey::Digest(digest), response);
}
Message::Prune { through } => {
self.prune(through);
}
},
Some((peer, shard)) = receiver.recv() else {
debug!("receiver closed, stopping shard engine");
return;
} => {
// Track shard receipt per peer.
self.metrics
.shards_received
.get_or_create(&Peer::new(&peer))
.inc();
let commitment = shard.commitment();
if !self.should_handle_network_shard(commitment) {
continue;
}
if let Some(state) = self.state.get_mut(&commitment) {
let round = state.round();
let Some(scheme) = self.scheme_provider.scoped(round.epoch()) else {
warn!(%commitment, "no scheme for epoch, ignoring shard");
continue;
};
let progressed = state
.on_network_shard(
peer,
shard,
InsertCtx::new(scheme.as_ref(), &self.strategy),
&mut self.blocker,
)
.await;
if progressed {
self.try_advance(&mut sender, commitment).await;
}
} else {
self.buffer_peer_shard(peer, shard);
}
},
}
}
/// Returns whether an incoming network shard should still be processed.
///
/// Shards for reconstructed commitments are normally ignored. The only
/// exception is the late leader-delivered shard for the assigned index,
/// which we still accept so we can notify readiness and gossip it to
/// slower peers.
fn should_handle_network_shard(&self, commitment: Commitment) -> bool {
if self.reconstructed_blocks.contains_key(&commitment) {
return self
.state
.get(&commitment)
.is_some_and(|s| !s.is_assigned_shard_verified());
}
true
}
/// Attempts to reconstruct a [`CodedBlock`] from the checked [`Shard`]s present in the
/// [`ReconstructionState`].
///
/// # Returns
/// - `Ok(Some(block))` if reconstruction was successful or the block was already reconstructed.
/// - `Ok(None)` if reconstruction could not be attempted due to insufficient checked shards.
/// - `Err(_)` if reconstruction was attempted but failed.
#[allow(clippy::type_complexity)]
fn try_reconstruct(
&mut self,
commitment: Commitment,
) -> Result<Option<Arc<CodedBlock<B, C, H>>>, Error<C>> {
if let Some(block) = self.reconstructed_blocks.get(&commitment) {
return Ok(Some(Arc::clone(block)));
}
let Some(state) = self.state.get_mut(&commitment) else {
return Ok(None);
};
if state.checked_shards().len() < usize::from(commitment.config().minimum_shards.get()) {
debug!(%commitment, "not enough checked shards to reconstruct block");
return Ok(None);
}
// Attempt to reconstruct the encoded blob
let start = self.context.current();
let blob = C::decode(
&commitment.config(),
&commitment.root(),
state.checked_shards().iter(),
&self.strategy,
)
.map_err(Error::Coding)?;
self.metrics
.erasure_decode_duration
.observe_between(start, self.context.current());
// Attempt to decode the block from the encoded blob
let (inner, config): (B, CodingConfig) =
Decode::decode_cfg(&mut blob.as_slice(), &(self.block_codec_cfg.clone(), ()))?;
match validate_reconstruction::<H, _>(&inner, config, commitment) {
Ok(()) => {}
Err(InvariantError::BlockDigest) => {
return Err(Error::DigestMismatch);
}
Err(InvariantError::CodingConfig) => {
warn!(
%commitment,
expected_config = ?commitment.config(),
actual_config = ?config,
"reconstructed block config does not match commitment config, but digest matches"
);
return Err(Error::ConfigMismatch);
}
Err(InvariantError::ContextDigest(expected, actual)) => {
warn!(
%commitment,
expected_context_digest = ?expected,
actual_context_digest = ?actual,
"reconstructed block context digest does not match commitment context digest"
);
return Err(Error::ContextMismatch);
}
}
// Construct a coding block with a _trusted_ commitment. `S::decode` verified the blob's
// integrity against the commitment, so shards can be lazily re-constructed if need be.
let block = Arc::new(CodedBlock::new_trusted(inner, commitment));
self.cache_block(Arc::clone(&block));
self.metrics.blocks_reconstructed_total.inc();
Ok(Some(block))
}
/// Handles leader announcements for a commitment and advances reconstruction.
async fn handle_external_proposal<Sr: Sender<PublicKey = P>>(
&mut self,
sender: &mut WrappedSender<Sr, Shard<C, H>>,
commitment: Commitment,
leader: P,
round: Round,
) {
if self.reconstructed_blocks.contains_key(&commitment) {
return;
}
let Some(scheme) = self.scheme_provider.scoped(round.epoch()) else {
warn!(%commitment, "no scheme for epoch, ignoring external proposal");
return;
};
let participants = scheme.participants();
if participants.index(&leader).is_none() {
warn!(?leader, %commitment, "leader update for non-participant, ignoring");
return;
}
if let Some(state) = self.state.get(&commitment) {
if state.leader() != &leader {
warn!(
existing = ?state.leader(),
?leader,
%commitment,
"conflicting leader update, ignoring"
);
}
return;
}
let participants_len =
u64::try_from(participants.len()).expect("participant count impossibly out of bounds");
self.state.insert(
commitment,
ReconstructionState::new(leader, round, participants_len),
);
let buffered_progress = self.ingest_buffered_shards(commitment).await;
if buffered_progress {
self.try_advance(sender, commitment).await;
}
}
/// Buffer a shard from a peer until a leader is known.
fn buffer_peer_shard(&mut self, peer: P, shard: Shard<C, H>) {
if self.latest_primary_peers.position(&peer).is_none() {
debug!(
?peer,
"pre-leader shard from peer outside latest.primary not buffered"
);
return;
}
let queue = self.peer_buffers.entry(peer).or_default();
if queue.len() >= self.peer_buffer_size.get() {
let _ = queue.pop_front();
}
queue.push_back(shard);
}
fn update_latest_primary_peers(&mut self, peers: Set<P>) {
self.peer_buffers
.retain(|peer, _| peers.position(peer).is_some());
self.latest_primary_peers = peers;
}
/// Ingest buffered pre-leader shards for a commitment into active state.
async fn ingest_buffered_shards(&mut self, commitment: Commitment) -> bool {
let mut buffered = Vec::new();
for (peer, queue) in self.peer_buffers.iter_mut() {
let mut i = 0;
while i < queue.len() {
if queue[i].commitment() != commitment {
i += 1;
continue;
}
let shard = queue.swap_remove_back(i).expect("index is valid");
buffered.push((peer.clone(), shard));
}
}
let Some(state) = self.state.get_mut(&commitment) else {
return false;
};
let round = state.round();
let Some(scheme) = self.scheme_provider.scoped(round.epoch()) else {
warn!(%commitment, "no scheme for epoch, dropping buffered shards");
return false;
};
// Ingest buffered shards into the active reconstruction state. Batch verification
// will be triggered if there are enough shards to meet the quorum threshold.
let mut progressed = false;
let ctx = InsertCtx::new(scheme.as_ref(), &self.strategy);
for (peer, shard) in buffered {
progressed |= state
.on_network_shard(peer, shard, ctx, &mut self.blocker)
.await;
}
progressed
}
/// Cache a block and notify all subscribers waiting on it.
fn cache_block(&mut self, block: Arc<CodedBlock<B, C, H>>) {
let commitment = block.commitment();
self.reconstructed_blocks
.insert(commitment, Arc::clone(&block));
self.notify_block_subscribers(block);
}
/// Broadcasts the shards of a [`CodedBlock`] and caches the block.
///
/// - Participants receive the shard matching their participant index.
/// - Non-participants in aggregate membership receive the leader's shard.
async fn broadcast_shards<Sr: Sender<PublicKey = P>>(
&mut self,
sender: &mut WrappedSender<Sr, Shard<C, H>>,
round: Round,
mut block: CodedBlock<B, C, H>,
) {
let commitment = block.commitment();
let Some(scheme) = self.scheme_provider.scoped(round.epoch()) else {
warn!(%commitment, "no scheme available, cannot broadcast shards");
return;
};
let participants = scheme.participants();
let Some(me) = scheme.me() else {
warn!(
%commitment,
"cannot broadcast shards: local proposer is not a participant"
);
return;
};
let shard_count = block.shards(&self.strategy).len();
if shard_count != participants.len() {
warn!(
%commitment,
shard_count,
participants = participants.len(),
"cannot broadcast shards: participant/shard count mismatch"
);
return;
}
let my_index = me.get() as usize;
let leader_shard = block
.shard(my_index as u16)
.expect("proposer's shard must exist");
// Broadcast each participant their corresponding shard.
for (index, peer) in participants.iter().enumerate() {
if index == my_index {
continue;
}
let Some(shard) = block.shard(index as u16) else {
warn!(
%commitment,
index,
"cannot broadcast shards: missing shard for participant index"
);
return;
};
let _ = sender
.send(Recipients::One(peer.clone()), shard, true)
.await;
}
// Send the leader's shard to peers in aggregate membership who are not participants.
let non_participants: Vec<P> = self
.aggregate_peers
.iter()
.filter(|peer| participants.index(peer).is_none())
.cloned()
.collect();
if !non_participants.is_empty() {
let _ = sender
.send(Recipients::Some(non_participants), leader_shard, true)
.await;
}
// Cache the block so we don't have to reconstruct it again.
let block = Arc::new(block);
self.cache_block(block);
// Local proposals bypass reconstruction, so shard subscribers waiting
// for "our valid shard arrived" still need a notification.
self.notify_assigned_shard_verified_subscribers(commitment);
debug!(?commitment, "broadcasted shards");
}
/// Gossips a validated [`Shard`] using [`commonware_p2p::Recipients::All`].
async fn broadcast_shard<Sr: Sender<PublicKey = P>>(
&mut self,
sender: &mut WrappedSender<Sr, Shard<C, H>>,
shard: Shard<C, H>,
) {
let commitment = shard.commitment();
if let Ok(peers) = sender.send(Recipients::All, shard, true).await {
debug!(
?commitment,
peers = peers.len(),
"broadcasted shard to all peers"
);
}
}
/// Broadcasts any pending validated shard for the given commitment and attempts
/// reconstruction. If reconstruction succeeds or fails, the state is cleaned
/// up and subscribers are notified.
async fn try_advance<Sr: Sender<PublicKey = P>>(
&mut self,
sender: &mut WrappedSender<Sr, Shard<C, H>>,
commitment: Commitment,
) {
if let Some(state) = self.state.get_mut(&commitment) {
match state.take_pending_action() {
Some(AssignedShardVerifiedAction::Broadcast(shard)) => {
self.broadcast_shard(sender, shard).await;
self.notify_assigned_shard_verified_subscribers(commitment);
}
Some(AssignedShardVerifiedAction::NotifyOnly) => {
self.notify_assigned_shard_verified_subscribers(commitment);
}
None => {}
}
}
match self.try_reconstruct(commitment) {
Ok(Some(block)) => {
// Do not prune other reconstruction state here. A Byzantine
// leader can equivocate by proposing multiple commitments in
// the same round, so more than one block may be reconstructed
// for a given round. Pruning is deferred to `prune()`, which
// is called once a commitment is finalized.
debug!(
%commitment,
parent = %block.parent(),
height = %block.height(),
"successfully reconstructed block from shards"
);
}
Ok(None) => {
debug!(%commitment, "not enough checked shards to reconstruct block");
}
Err(err) => {
warn!(%commitment, ?err, "failed to reconstruct block from checked shards");
self.state.remove(&commitment);
self.drop_subscriptions(commitment);
self.metrics.reconstruction_failures_total.inc();
}
}
}
/// Handles the registry of an assigned shard verification subscription.
///
/// For participants this is tied to verification of the leader-delivered
/// shard for the local index, not to generic block reconstruction.
fn handle_assigned_shard_verified_subscription(
&mut self,
commitment: Commitment,
response: oneshot::Sender<()>,
) {
// Answer immediately if our own shard has been verified.
let has_shard = self
.state
.get(&commitment)
.is_some_and(|state| state.is_assigned_shard_verified());
if has_shard {
response.send_lossy(());
return;
}
// When there is no reconstruction state but the block is already in
// the cache, the local node was the proposer. Proposers trivially
// have all shards, so resolve immediately.
if !self.state.contains_key(&commitment)
&& self.reconstructed_blocks.contains_key(&commitment)
{
response.send_lossy(());
return;
}
self.assigned_shard_verified_subscriptions
.entry(commitment)
.or_default()
.push(response);
}
/// Handles the registry of a block subscription.
fn handle_block_subscription(
&mut self,
key: BlockSubscriptionKey<B::Digest>,
response: oneshot::Sender<Arc<CodedBlock<B, C, H>>>,
) {
let block = match key {
BlockSubscriptionKey::Commitment(commitment) => {
self.reconstructed_blocks.get(&commitment)
}
BlockSubscriptionKey::Digest(digest) => self
.reconstructed_blocks
.iter()
.find_map(|(_, block)| (block.digest() == digest).then_some(block)),
};
// Answer immediately if we have the block cached.
if let Some(block) = block {
response.send_lossy(Arc::clone(block));
return;
}
self.block_subscriptions
.entry(key)
.or_default()
.push(response);
}
/// Notifies and cleans up any subscriptions waiting for assigned shard
/// verification.
fn notify_assigned_shard_verified_subscribers(&mut self, commitment: Commitment) {
if let Some(mut subscribers) = self
.assigned_shard_verified_subscriptions
.remove(&commitment)
{
for subscriber in subscribers.drain(..) {
subscriber.send_lossy(());
}
}
}
/// Notifies and cleans up any subscriptions for a reconstructed block.
fn notify_block_subscribers(&mut self, block: Arc<CodedBlock<B, C, H>>) {
let commitment = block.commitment();
let digest = block.digest();
// Notify by-commitment subscribers.
if let Some(mut subscribers) = self
.block_subscriptions
.remove(&BlockSubscriptionKey::Commitment(commitment))
{
for subscriber in subscribers.drain(..) {
subscriber.send_lossy(Arc::clone(&block));
}
}
// Notify by-digest subscribers.
if let Some(mut subscribers) = self
.block_subscriptions
.remove(&BlockSubscriptionKey::Digest(digest))
{
for subscriber in subscribers.drain(..) {
subscriber.send_lossy(Arc::clone(&block));
}