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
#![cfg_attr(docsrs, feature(doc_cfg))]
#![doc = include_str!("../README.md")]
#![deny(missing_docs)]
#![no_std]
use core::{
pin::Pin,
task::{Poll, Context},
num::NonZero,
time::Duration,
};
extern crate alloc;
use alloc::boxed::Box;
extern crate std;
use std::collections::HashMap;
use futures_core::stream::{Stream as _, FusedStream as _};
use zeroize::Zeroizing;
use ciphersuite::Ciphersuite;
use dalek_ff_group::Ristretto;
use serai_db::{Transaction as _, Db};
use ::tendermint::{Signer as _, Network};
mod read_write;
pub use read_write::*;
/// The specification and implementation of a Merkle tree.
pub mod merkle;
use merkle::*;
/// The functionality for transactions.
pub mod transaction;
use transaction::{Signed, TransactionKind};
pub use transaction::Transaction;
/// The functionality for blocks.
pub mod block;
pub use block::Block;
pub mod mempool;
use mempool::{MempoolError, MempoolNetwork, Mempool, MempoolConsumer};
mod blockchain;
use blockchain::{Reader, Blockchain};
mod tendermint;
use tendermint::{SignatureScheme, Tendermint};
pub use tendermint::{AggregateSignature, Commit, Slash};
mod or;
/// A Tendermint consensus message for a Tributary.
pub type Message<T> =
::tendermint::Message<[u8; 32], [u8; 64], AggregateSignature, ReadWriteAsBorsh<Block<T>>>;
struct AsyncAddToMempool<T> {
transaction: T,
bypass_rate_limit: bool,
response: async_channel::Sender<Result<(), MempoolError>>,
}
pin_project_lite::pin_project! {
struct MempoolFuture<D: Db, T: Transaction, MN: MempoolNetwork<T>> {
db: D,
#[pin]
mempool: Mempool<D, T, MN>,
#[pin]
mempool_recv: async_channel::Receiver<AsyncAddToMempool<T>>,
}
}
impl<D: Db, T: Transaction, MN: MempoolNetwork<T>> Future for MempoolFuture<D, T, MN> {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut projection = self.project();
let _: Poll<()> = projection.mempool.as_mut().poll(cx);
if (!projection.mempool_recv.is_terminated()) &&
let Poll::Ready(Some(AsyncAddToMempool { transaction, bypass_rate_limit, response })) =
projection.mempool_recv.poll_next(cx)
{
let mut txn = projection.db.txn();
let result = projection.mempool.add(&mut txn, transaction, bypass_rate_limit);
txn.commit();
let _ = response.try_send(result);
}
Poll::Pending
}
}
pin_project_lite::pin_project! {
/// An instanced Tributary.
///
/// This is a collection of futures which MUST be polled in order for the Tributary to make
/// progress. It may be directly polled, acting as a single-threaded sequential executor for each
/// of the contained futures, or unrolled via its `IntoIterator` implementation, allowing the
/// futures to be individually spawned on an executor.
pub struct Tributary<
D: Db,
T: Transaction,
MN: MempoolNetwork<T>,
Tendermint = (),
Loop = (),
> {
#[pin]
tendermint: Tendermint,
#[pin]
mempool: MempoolFuture<D, T, MN>,
#[pin]
inner_loop: Loop,
}
}
impl<
D: Db,
T: Transaction,
MN: MempoolNetwork<T>,
Tendermint: Future<Output = ()>,
Loop: Future<Output = ()>,
> Future for Tributary<D, T, MN, Tendermint, Loop>
{
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let projection = self.project();
let _: Poll<()> = projection.tendermint.poll(cx);
let _: Poll<()> = projection.mempool.poll(cx);
let _: Poll<()> = projection.inner_loop.poll(cx);
Poll::Pending
}
}
impl<
D: 'static + Send + for<'db> Db<Transaction<'db>: Send>,
T: 'static + Send + Transaction,
MN: 'static + Send + MempoolNetwork<T>,
Tendermint: 'static + Send + Future<Output = ()>,
Loop: 'static + Send + Future<Output = ()>,
> IntoIterator for Tributary<D, T, MN, Tendermint, Loop>
{
type Item = Pin<Box<dyn Send + Future<Output = ()>>>;
type IntoIter = <[Self::Item; 3] as IntoIterator>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
let Self { tendermint, mempool, inner_loop } = self;
let tendermint: Self::Item = Box::pin(tendermint);
let mempool = Box::pin(mempool);
let inner_loop = Box::pin(inner_loop);
[tendermint, mempool, inner_loop].into_iter()
}
}
/// An error when instantiating the Tributary.
#[derive(Debug)]
pub enum TributaryError {
/// The (target) block time wasn't representable.
UnrepresentableBlockTime,
/// The provided key didn't correspond to a validator.
NotValidator,
}
/// An error when syncing a block.
pub enum SyncError {
/// The block was syntactically invalid.
InvalidBlock(block::SyntacticError),
/// The commit was invalid.
InvalidCommit,
}
/// A handle to an instanced Tributary.
#[derive(Clone)]
pub struct TributaryHandle<D: Db, T: Transaction> {
db: D,
genesis: [u8; 32],
block_time: Duration,
validator_set: crate::tendermint::ValidatorSet,
signature_scheme: SignatureScheme,
validator: [u8; 32],
blocks_behind: async_channel::Sender<async_channel::Sender<u64>>,
sync: async_channel::Sender<(Block<T>, crate::tendermint::Commit)>,
message: async_channel::Sender<Message<T>>,
mempool: async_channel::Sender<AsyncAddToMempool<T>>,
censure: async_channel::Sender<([u8; 32], async_channel::Sender<()>)>,
next_block_notification: async_channel::Sender<async_channel::Sender<()>>,
}
impl<
D: Send + Sync + for<'db> Db<Transaction<'db>: Send>,
T: Send + Sync + Transaction,
MN: MempoolNetwork<T>,
> Tributary<D, T, MN>
{
/// Instance a Tributary.
///
/// This MUST be the only Tributary instanced with this `genesis` value. It will be reloaded from
/// the database if prior instanced. For further context on the limitations of this, please refer
/// to the limitations placed upon [`::tendermint::Tendermint`].
///
/// The `genesis` argument will be expanded to a 32-byte genesis by prefixing 16 `0`s.
///
/// `genesis_time` is expressed in milliseconds since the epoch and used to limit the minimum
/// time blocks may be published with. This prevents a malicious supermajority from backdating
/// blocks, allowing flooding the honest minority with valid blocks which still respect the
/// minimum spacing between blocks. It is optional as it is not strictly required, but it is
/// practically required for resilience against a dishonest supermajority (who can compromise the
/// integrity of the Tributary in general). Whatever value is set, it MUST be consistent across
/// participants AND reboots.
///
/// `validators` represents the validators present in the Tributary (keyed by their Ristretto
/// public keys, valued by their weight in the consensus process). It MUST be a valid value for
/// the [`::tendermint::ValidatorSet`] trait.
///
/// `key` is the validator's Ristretto private key. It MUST be consistent across reboots.
///
/// `mempool_rate_limit` is the maximum amount of transactions each validator may have pending
/// within the mempool. It MAY be locally configured independently of other validators. It does
/// not apply to provided nor unsigned transactions which are privileged within the Tributary.
#[expect(clippy::too_many_arguments)]
pub async fn new<
N: Send
+ Sync
+ Network<[u8; 32], [u8; 64], AggregateSignature, ReadWriteAsBorsh<Block<T>>, Sleep: Send>,
>(
db: D,
genesis: [u8; 16],
genesis_time: Option<u64>,
validators: HashMap<[u8; 32], NonZero<u16>>,
tendermint_network: N,
mempool_network: MN,
key: Zeroizing<<Ristretto as Ciphersuite>::F>,
mempool_rate_limit: usize,
) -> Result<
(
Tributary<D, T, MN, impl Send + Future<Output = ()>, impl Send + Future<Output = ()>>,
TributaryHandle<D, T>,
),
TributaryError,
> {
/*
Expand the 16-byte genesis DST into a 32-byte 'hash'.
This isn't considered a hash, solely an element in the same 32-byte domain as a hash
(allowing it to be specified as the 'parent' for the first actual block on the blockchain).
Tendermint allows the genesis to be an arbitrary DST value but the Tributary requires it not
collide with an actual block's hash. The following expansion sets the first 16 bytes to `0`,
meaning a collision would require 128 bits of effort (as the security of the rest of the
cryptography in the Tributary requires).
*/
let genesis = {
let mut genesis_32 = [0; 32];
genesis_32[16 ..].copy_from_slice(&genesis);
genesis_32
};
let genesis_time = genesis_time.unwrap_or(0);
let target_block_time =
N::target_block_time().ok_or(TributaryError::UnrepresentableBlockTime)?;
// TODO: This is the maximum of the bound internal to the `tendermint-consensus` library
let (sync_send, sync_recv) =
async_channel::bounded::<(Block<T>, crate::tendermint::Commit)>(64);
let (message_send, message_recv) = async_channel::bounded::<
::tendermint::MessageFor<Tendermint<D, T, MempoolConsumer<T>, N>>,
>(2 * validators.len());
let (mempool_send, mempool_recv) =
async_channel::bounded::<AsyncAddToMempool<T>>(mempool_rate_limit.max(8));
let (censure_send, censure_recv) =
async_channel::bounded::<([u8; 32], async_channel::Sender<()>)>(validators.len());
let (mempool, mempool_consumer) = Mempool::new(
db.clone(),
genesis,
validators.keys().copied(),
mempool_network,
censure_recv,
mempool_rate_limit,
);
let (blocks_behind_send, blocks_behind_recv) =
async_channel::bounded::<async_channel::Sender<u64>>(1);
let signature_scheme = SignatureScheme::new(genesis, validators.len());
let signer = signature_scheme.signer(key);
let validator = signer.validator();
if !validators.contains_key(&validator) {
Err(TributaryError::NotValidator)?;
}
let (validator_set, next_block_notification, (mut tendermint_handle, tendermint)) = {
let blockchain =
Blockchain::new(&db, genesis, genesis_time, validators, signature_scheme.clone());
let (tip, minimum_next_block_time) = {
let tip = blockchain.tip(&db);
let target_block_time = u64::try_from(target_block_time.as_millis())
.map_err(|_| TributaryError::UnrepresentableBlockTime)?;
let minimum_next_block_time = tip
.as_ref()
.map(|tip| tip.time().checked_add(target_block_time))
.unwrap_or(Some(genesis_time));
let tip = tip.map(|block| block.hash()).unwrap_or(genesis);
(tip, minimum_next_block_time)
};
/*
In practice, this is bounded by the amount of handles which simultaneously exist,
preventing concerns with its memory usage. If the caller did cause this channel to be an
effective DoS, it'd be because they've already created an amount of handles which are an
effective DoS.
*/
let (next_block_notification_send, next_block_notification_recv) =
async_channel::unbounded::<async_channel::Sender<()>>();
let mut tendermint = Tendermint::<_, _, _, N>::new(
db.clone(),
genesis,
blockchain,
next_block_notification_recv,
mempool_consumer,
);
let validator_set = {
use ::tendermint::Blockchain as _;
tendermint.validator_set().clone()
};
let proposal = tendermint.block_proposal(tip, minimum_next_block_time, 0);
(
validator_set,
next_block_notification_send,
::tendermint::Tendermint::process(
tendermint,
signer,
db.clone(),
tendermint_network,
proposal,
)
.await,
)
};
let inner_loop = async move {
loop {
if let Err(::tendermint::ProcessTerminated) = match (or::Or {
f1: or::Or { f1: sync_recv.recv(), f2: message_recv.recv() },
f2: blocks_behind_recv.recv(),
})
.await
{
or::Either::L(or::Either::L(Ok((block, commit)))) => {
tendermint_handle.sync(ReadWriteAsBorsh(block), commit).await
}
or::Either::L(or::Either::R(Ok(message))) => tendermint_handle.message(message).await,
or::Either::R(Ok(blocks_behind)) => {
// Ignore the error in case the future was cancelled
let _ = blocks_behind.try_send({
let observed_block_number = u64::from(tendermint_handle.observed_block_number());
let block_number = u64::from(tendermint_handle.block_number());
observed_block_number.saturating_sub(block_number)
});
Ok(())
}
// If all of the handles were dropped, we consider the process terminated
or::Either::L(or::Either::L(Err(_)) | or::Either::R(Err(_))) | or::Either::R(Err(_)) => {
Err(::tendermint::ProcessTerminated)
}
} {
// TODO: Never
core::future::pending::<()>().await;
}
}
};
Ok((
Tributary {
tendermint,
mempool: MempoolFuture { db: db.clone(), mempool, mempool_recv },
inner_loop,
},
TributaryHandle {
db,
genesis,
block_time: target_block_time,
validator_set,
signature_scheme,
validator,
blocks_behind: blocks_behind_send,
sync: sync_send,
message: message_send,
mempool: mempool_send,
censure: censure_send,
next_block_notification,
},
))
}
}
impl<D: Db, T: Transaction> TributaryHandle<D, T> {
/// The Tributary's genesis.
pub fn genesis(&self) -> [u8; 32] {
self.genesis
}
/// The Tributary's target block time.
pub fn block_time(&self) -> Duration {
self.block_time
}
/// The Tributary's tip block.
///
/// This is read from the database and is accordingly the last _committed_ block.
pub fn tip(&self) -> Option<[u8; 32]> {
Reader::<T>::tip(&self.db, self.genesis)
}
/// The amount of blocks the local Tributary is missing in comparison to the current consensus
/// efforts.
///
/// This is derivative of [`::tendermint::TendermintHandle::observed_block_number`], a method
/// which allows the local process to observe the block validators are obtaining consensus over.
/// It is not intended to be an explicit counter of the amount of blocks to explicitly sync,
/// solely a hint.
pub async fn blocks_behind(&self) -> u64 {
let (send, recv) = async_channel::bounded(1);
let _ = self.blocks_behind.send(send).await;
match recv.recv().await {
Ok(blocks_behind) => blocks_behind,
Err(_) => core::future::pending().await,
}
}
/// A block on the Tributary, identified by its hash.
///
/// This returns `None` if the block wasn't committed on this Tributary.
pub fn block(&self, hash: [u8; 32]) -> Option<Block<T>> {
Reader::<T>::block(&self.db, self.genesis, hash)
}
/// The commit for a block on the Tributary.
///
/// This returns `None` if no commit was saved for this block.
pub fn commit(&self, block: [u8; 32]) -> Option<crate::tendermint::Commit> {
crate::tendermint::db_commit(&self.db, self.genesis, block)
}
/// The block after a block on the Tributary.
///
/// This returns `None` if either:
/// - The parent block (identified by its hash) wasn't committed on this Tributary
/// - It has no child block committed on the Tributary
pub fn block_after(&self, parent: [u8; 32]) -> Option<[u8; 32]> {
Reader::<T>::block_after(&self.db, self.genesis, parent)
}
/// The hashes of locally provided transactions.
pub fn locally_provided_transactions(
&self,
scope: &'static str,
start: u64,
) -> impl Iterator<Item = [u8; 32]> {
mempool::ProvidedReader::<T>::locally_provided(&self.db, self.genesis, scope, start)
}
/// Handle a consensus message.
///
/// This will return once the message has been queued to be handled, offering no inspection
/// into when that queue is consumed or if the queued message was valid.
pub async fn message(&self, message: Message<T>) {
/*
Queueing into an open channel (with no observability into when the queue is consumed from) is
considered equivalent to not queueing into a closed channel (a queue which will never be
consumed from). All values are still handled in order, without omission, whenever (or if
ever) handled. This lets us igore any error here.
*/
let _ = self.message.send(message).await;
}
/// Explicitly sync a block.
///
/// This is intended to be used when a Tributary is behind, unable to simply observe blocks as
/// they're produced by the consensus process.
///
/// The block's _syntax_ and the commit is immediately validated. Therefore, this block is either
/// valid, semantically invalid, or ephemerally invalid. Assuming honest behavior, this block
/// will be semantically valid (due to the commit by a supermajority of validators finalizing
/// it) though. This assumption allows simplifying that this function either returns an error or:
/// 1) The block was already added
/// 2) The block is not ready to be added (due to missing parent blocks)
/// 3) The block will be added
///
/// This function only queues the block to be added (if verified to be syntactically valid, with
/// a valid commit). This function offers no inspection into when that queue is consumed or if
/// the queued block was entirely valid.
pub async fn sync(
&self,
block: Block<T>,
commit: crate::tendermint::Commit,
) -> Result<(), SyncError> {
if !commit.verify(&self.validator_set, &self.signature_scheme, &self.genesis, block.hash()) {
Err(SyncError::InvalidCommit)?;
}
let () = block.verify_syntax(self.genesis).map_err(SyncError::InvalidBlock)?;
/*
Queueing into an open channel (with no observability into when the queue is consumed from) is
considered equivalent to not queueing into a closed channel (a queue which will never be
consumed from). All values are still handled in order, without omission, whenever (or if
ever) handled. This lets us igore any error here.
*/
let _ = self.sync.send((block, commit)).await;
Ok(())
}
/// Publish a transaction into the Tributary's mempool.
///
/// This is used to publish a transaction, regardless of its kind. `Provided` transactions are
/// intended to only be provided by the local node however, meaning the caller MUST check the
/// kind of a transaction and its origin _before_ calling this method.
///
/// The mempool's rate limit will be bypassed if the transaction's signer is the Tributary's
/// validator, ensuring the local validator can publish their own transactions without needing to
/// implement an additional buffer.
pub async fn transaction(&self, transaction: T) -> Result<(), MempoolError> {
let bypass_rate_limit =
if let TransactionKind::Signed { signed: Signed { signer, .. }, .. } = transaction.kind() {
signer == self.validator
} else {
true
};
let (response_send, response_recv) = async_channel::bounded(1);
let _ = self
.mempool
.send(AsyncAddToMempool { transaction, bypass_rate_limit, response: response_send })
.await;
match response_recv.recv().await {
Ok(result) => result,
/*
If the channel was closed, the mempool was dropped, and this publication won't occur.
We yield `Pending` infinitely to reflect how this publication will never be ready. While
the alternative would to be return an error, we presume that applications won't drop the
mempool, letting us simplify the API a bit.
*/
Err(_) => core::future::pending().await,
}
}
/// Censure a validator.
///
/// This will prevent voting for block proposals from this validator and not populate their
/// transactions within the mempool. It only applies to the local view and doesn't have to
/// performed in any synchrony with other validators.
pub async fn censure(&self, validator: [u8; 32]) {
let (censured_send, censured_recv) = async_channel::bounded::<()>(1);
let _ = self.censure.send((validator, censured_send)).await;
match censured_recv.recv().await {
Ok(()) => {}
/*
If the channel was closed, this validator won't have the censure applied, so this function
should never return (signifying the censure was applied).
We _could_ also propagate an error to signify the Tributary is no longer running, but it
isn't worth the API complexity.
*/
Err(_) => core::future::pending().await,
}
}
/// A future which resolves when the next block is added to the Tributary.
pub fn next_block_notification(&self) -> impl Send + Future<Output = ()> {
let (next_block_notification_send, next_block_notification_recv) =
async_channel::bounded::<()>(1);
let _ = self.next_block_notification.try_send(next_block_notification_send);
async move {
match next_block_notification_recv.recv().await {
Ok(()) => {}
/*
If the channel was closed, there won't be any more blocks added, so this notification
should never resolve.
We _could_ also propagate an error to signify the Tributary is no longer running, but it
isn't worth the API complexity.
*/
Err(_) => core::future::pending().await,
}
}
}
}