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
//! Mailbox for the shard buffer engine.
use crate::{
CertifiableBlock,
marshal::{coding::types::CodedBlock, core::Retirement},
types::{Round, coding::Commitment},
};
use commonware_actor::mailbox::{Overflow, Policy, Sender};
use commonware_coding::Scheme as CodingScheme;
use commonware_cryptography::{Hasher, PublicKey};
use commonware_utils::channel::oneshot;
use std::{collections::VecDeque, sync::Arc};
/// A message that can be sent to the coding [`Engine`].
///
/// [`Engine`]: super::Engine
pub(crate) enum Message<B, C, H, P>
where
B: CertifiableBlock,
C: CodingScheme,
H: Hasher,
P: PublicKey,
{
/// A request to broadcast a proposed [`CodedBlock`] to all peers.
Proposed {
/// The erasure coded block.
block: Arc<CodedBlock<B, C, H>>,
/// The round in which the block was proposed.
round: Round,
},
/// A notification from consensus that a [`Commitment`] has been discovered.
Discovered {
/// The [`Commitment`] of the proposed block.
commitment: Commitment<B, C, H>,
/// The leader's public key.
leader: P,
/// The round in which the commitment was proposed.
round: Round,
},
/// A notification from consensus that a [`Commitment`] has been notarized.
///
/// This may arrive before the engine knows the round leader. It allows the
/// engine to reconstruct from sender-indexed gossip shards already buffered
/// for the commitment, but it does not satisfy assigned shard verification.
Notarized {
/// The [`Commitment`] of the notarized block.
commitment: Commitment<B, C, H>,
/// The round in which the commitment was notarized.
round: Round,
},
/// A request to get a reconstructed block, if available.
GetByCommitment {
/// The [`Commitment`] of the block to get.
commitment: Commitment<B, C, H>,
/// The response channel.
response: oneshot::Sender<Option<Arc<CodedBlock<B, C, H>>>>,
},
/// A request to get a reconstructed block by its digest, if available.
GetByDigest {
/// The digest of the block to get.
digest: B::Digest,
/// The response channel.
response: oneshot::Sender<Option<Arc<CodedBlock<B, C, H>>>>,
},
/// A request to open a subscription for assigned shard verification.
///
/// For participants, this resolves once the shard for the local participant
/// index has been verified. Reconstructing the full block from gossiped
/// shards does not resolve this subscription: that
/// block may still be used for later certification, but it is not enough
/// to claim the participant received the shard it is expected to echo.
///
/// For proposers, this resolves immediately after the locally built block
/// is cached because they trivially have all shards.
SubscribeAssignedShardVerified {
/// The block's commitment.
commitment: Commitment<B, C, H>,
/// The response channel.
response: oneshot::Sender<()>,
},
/// A request to open a subscription for the reconstruction of a [`CodedBlock`]
/// by its [`Commitment`].
SubscribeByCommitment {
/// The block's commitment.
commitment: Commitment<B, C, H>,
/// The response channel.
response: oneshot::Sender<Arc<CodedBlock<B, C, H>>>,
},
/// A request to open a subscription for the reconstruction of a [`CodedBlock`]
/// by its digest.
SubscribeByDigest {
/// The block's digest.
digest: B::Digest,
/// The response channel.
response: oneshot::Sender<Arc<CodedBlock<B, C, H>>>,
},
/// A request to retire cached blocks and reconstruction state after durable application
/// progress.
Retire {
/// The retirement to apply.
update: Retirement<Commitment<B, C, H>>,
},
}
impl<B, C, H, P> Message<B, C, H, P>
where
B: CertifiableBlock,
C: CodingScheme,
H: Hasher,
P: PublicKey,
{
pub(crate) fn response_closed(&self) -> bool {
match self {
Self::GetByCommitment { response, .. } | Self::GetByDigest { response, .. } => {
response.is_closed()
}
Self::SubscribeAssignedShardVerified { response, .. } => response.is_closed(),
Self::SubscribeByCommitment { response, .. }
| Self::SubscribeByDigest { response, .. } => response.is_closed(),
Self::Proposed { .. }
| Self::Discovered { .. }
| Self::Notarized { .. }
| Self::Retire { .. } => false,
}
}
}
pub(crate) struct Pending<B, C, H, P>(VecDeque<Message<B, C, H, P>>)
where
B: CertifiableBlock,
C: CodingScheme,
H: Hasher,
P: PublicKey;
impl<B, C, H, P> Default for Pending<B, C, H, P>
where
B: CertifiableBlock,
C: CodingScheme,
H: Hasher,
P: PublicKey,
{
fn default() -> Self {
Self(VecDeque::new())
}
}
impl<B, C, H, P> Overflow<Message<B, C, H, P>> for Pending<B, C, H, P>
where
B: CertifiableBlock,
C: CodingScheme,
H: Hasher,
P: PublicKey,
{
fn is_empty(&self) -> bool {
self.0.is_empty()
}
fn drain<F>(&mut self, mut push: F)
where
F: FnMut(Message<B, C, H, P>) -> Option<Message<B, C, H, P>>,
{
while let Some(message) = self.0.pop_front() {
if message.response_closed() {
continue;
}
if let Some(message) = push(message) {
self.0.push_front(message);
break;
}
}
}
}
/// Retains overflowed messages in FIFO order.
impl<B, C, H, P> Policy for Message<B, C, H, P>
where
B: CertifiableBlock,
C: CodingScheme,
H: Hasher,
P: PublicKey,
{
type Overflow = Pending<B, C, H, P>;
fn handle(overflow: &mut Self::Overflow, message: Self) {
if message.response_closed() {
return;
}
overflow.0.push_back(message);
}
}
/// A mailbox for sending messages to the [`Engine`].
///
/// [`Engine`]: super::Engine
pub struct Mailbox<B, C, H, P>
where
B: CertifiableBlock,
C: CodingScheme,
H: Hasher,
P: PublicKey,
{
pub(super) sender: Sender<Message<B, C, H, P>>,
}
impl<B, C, H, P> Clone for Mailbox<B, C, H, P>
where
B: CertifiableBlock,
C: CodingScheme,
H: Hasher,
P: PublicKey,
{
fn clone(&self) -> Self {
Self {
sender: self.sender.clone(),
}
}
}
impl<B, C, H, P> Mailbox<B, C, H, P>
where
B: CertifiableBlock,
C: CodingScheme,
H: Hasher,
P: PublicKey,
{
/// Create a new [`Mailbox`] with the given sender.
pub(crate) const fn new(sender: Sender<Message<B, C, H, P>>) -> Self {
Self { sender }
}
/// Broadcast a proposed erasure coded block's shards to the participants.
pub fn proposed(&self, round: Round, block: CodedBlock<B, C, H>) {
self.proposed_shared(round, Arc::new(block));
}
pub(crate) fn proposed_shared(&self, round: Round, block: Arc<CodedBlock<B, C, H>>) {
let _ = self.sender.enqueue(Message::Proposed { block, round });
}
/// Inform the engine of an externally proposed [`Commitment`].
///
/// `round` MUST come from a trusted consensus observation, and its epoch
/// MUST be validated for `commitment`. The engine classifies the commitment's
/// shards against that epoch's participant set, so an unvalidated epoch can
/// misclassify shards from honest peers.
pub fn discovered(&self, commitment: Commitment<B, C, H>, leader: P, round: Round) {
let _ = self.sender.enqueue(Message::Discovered {
commitment,
leader,
round,
});
}
/// Inform the engine that a [`Commitment`] was notarized.
///
/// `round` MUST come from a trusted consensus observation, and its epoch
/// MUST be validated for `commitment`.
///
/// This is the leaderless reconstruction signal used by certification. It
/// lets the engine drain sender-indexed gossip shards from its peer buffers
/// for the commitment. Leader-specific validation and assigned shard
/// verification still require a later [`Self::discovered`] call.
pub fn notarized(&self, commitment: Commitment<B, C, H>, round: Round) {
let _ = self
.sender
.enqueue(Message::Notarized { commitment, round });
}
/// Request a reconstructed block by its [`Commitment`].
pub async fn get(&self, commitment: Commitment<B, C, H>) -> Option<Arc<CodedBlock<B, C, H>>> {
let (response, receiver) = oneshot::channel();
let _ = self.sender.enqueue(Message::GetByCommitment {
commitment,
response,
});
receiver.await.ok().flatten()
}
/// Request a reconstructed block by its digest.
pub async fn get_by_digest(&self, digest: B::Digest) -> Option<Arc<CodedBlock<B, C, H>>> {
let (response, receiver) = oneshot::channel();
let _ = self
.sender
.enqueue(Message::GetByDigest { digest, response });
receiver.await.ok().flatten()
}
/// Subscribe to assigned shard verification for a commitment.
///
/// For participants, this resolves once the shard for the local participant
/// index has been verified. Reconstructing the full block from gossiped
/// shards does not resolve this subscription: that
/// block may still be used for later certification, but it is not enough
/// to claim the participant received the shard it is expected to echo.
///
/// For proposers, this resolves immediately after the locally built block
/// is cached because they trivially have all shards.
pub fn subscribe_assigned_shard_verified(
&self,
commitment: Commitment<B, C, H>,
) -> oneshot::Receiver<()> {
let (responder, receiver) = oneshot::channel();
let _ = self
.sender
.enqueue(Message::SubscribeAssignedShardVerified {
commitment,
response: responder,
});
receiver
}
/// Subscribe to the reconstruction of a [`CodedBlock`] by its [`Commitment`].
pub fn subscribe(
&self,
commitment: Commitment<B, C, H>,
) -> oneshot::Receiver<Arc<CodedBlock<B, C, H>>> {
let (responder, receiver) = oneshot::channel();
let _ = self.sender.enqueue(Message::SubscribeByCommitment {
commitment,
response: responder,
});
receiver
}
/// Subscribe to the reconstruction of a [`CodedBlock`] by its digest.
pub fn subscribe_by_digest(
&self,
digest: B::Digest,
) -> oneshot::Receiver<Arc<CodedBlock<B, C, H>>> {
let (responder, receiver) = oneshot::channel();
let _ = self.sender.enqueue(Message::SubscribeByDigest {
digest,
response: responder,
});
receiver
}
/// Retire cached blocks and reconstruction state after durable application progress.
///
/// Entries last observed at or before [`Retirement::round_floor`] are eligible for
/// retirement. Entries in [`Retirement::exact_retirements`] are eligible regardless of
/// observation round.
///
/// Assigned-shard subscriptions for retired state are closed. Exact-commitment subscriptions
/// close only for exact retirements. Other block subscriptions remain open for local ingress.
/// Digest subscriptions remain open, and later consensus notifications may recreate state.
pub fn retire(&self, update: Retirement<Commitment<B, C, H>>) {
let _ = self.sender.enqueue(Message::Retire { update });
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
marshal::{coding::types::coding_config_for_participants, mocks::block::EmptyBlock},
types::{Epoch, Height, View},
};
use commonware_coding::ReedSolomon;
use commonware_cryptography::{
Committable, Digest as _, Sha256, ed25519, sha256::Digest as Sha256Digest,
};
use commonware_parallel::Sequential;
type B = EmptyBlock<Sha256>;
type H = Sha256;
type C = ReedSolomon<H>;
type TestMessage = Message<B, C, H, ed25519::PublicKey>;
#[test]
fn policy_drains_fifo() {
let block = CodedBlock::<B, C, H>::new(
B::new(Sha256Digest::EMPTY, Height::new(1), 1),
coding_config_for_participants(4),
&Sequential,
);
let commitment = block.commitment();
let round = Round::new(Epoch::zero(), View::new(1));
let mut overflow = Pending::default();
<TestMessage as Policy>::handle(&mut overflow, Message::Notarized { commitment, round });
let (response, _get_rx) = oneshot::channel();
<TestMessage as Policy>::handle(
&mut overflow,
Message::GetByCommitment {
commitment,
response,
},
);
let mut drained = Vec::new();
overflow.drain(|message| {
drained.push(message);
None
});
assert_eq!(drained.len(), 2);
assert!(matches!(&drained[0], TestMessage::Notarized { .. }));
assert!(matches!(&drained[1], TestMessage::GetByCommitment { .. }));
}
}