tendermint_consensus/blockchain.rs
1use core::{future::Future, num::NonZero};
2
3use crate::{Validator, SignatureScheme, ValidatorSet, CommitFor, SlashReasonFor};
4
5/// A block's number.
6///
7/// The genesis block is considered to have number `0` where following blocks' numbers increase
8/// incrementally by one.
9///
10/// As this library never works with the genesis block, as it's constant and does not undergo the
11/// consensus process, this library represents block numbers via [`NonZero`]. This is complete to
12/// all block numbers this library has to consider.
13#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
14#[cfg_attr(feature = "alloc", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
15#[repr(transparent)]
16pub struct BlockNumber(pub(crate) NonZero<u64>);
17impl BlockNumber {
18 pub(crate) const ONE: Self = Self(NonZero::new(1).unwrap());
19}
20impl From<BlockNumber> for u64 {
21 fn from(block_number: BlockNumber) -> Self {
22 u64::from(block_number.0)
23 }
24}
25impl From<NonZero<u64>> for BlockNumber {
26 fn from(block_number: NonZero<u64>) -> Self {
27 Self(block_number)
28 }
29}
30/// A round's number.
31///
32/// Tendermint describes this as starting from `0`, yet we start it from `1`. This has two
33/// benefits:
34/// 1) It allows representing `None` (our representation of what the paper describes as `-1`) as
35/// `0`, saving a byte in memory and encoding
36/// 2) It slightly simplifies calculating timeouts
37#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
38#[cfg_attr(feature = "alloc", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
39#[repr(transparent)]
40pub struct RoundNumber(pub(crate) NonZero<u64>);
41impl RoundNumber {
42 pub(crate) const ONE: Self = Self(NonZero::new(1).unwrap());
43}
44impl From<RoundNumber> for u64 {
45 fn from(round_number: RoundNumber) -> Self {
46 u64::from(round_number.0)
47 }
48}
49impl From<NonZero<u64>> for RoundNumber {
50 fn from(round_number: NonZero<u64>) -> Self {
51 Self(round_number)
52 }
53}
54
55/// A representation of a block's hash.
56///
57/// This is effectively a trait alias where a potential representation of a block's hash is any
58/// type which satisfies all of these bounds, and this is implemented for all such types.
59///
60/// The [`borsh::BorshSerialize`] implementation MUST be infallible if the underlying writer is
61/// infallible. The [`borsh::BorshDeserialize`] implementation MUST be infallible if it is
62/// value which was successfully serialized, from a well-formed reader.
63pub trait BlockHash: Clone + Copy + PartialEq + Eq + AsRef<[u8]> {}
64impl<H: Clone + Copy + PartialEq + Eq + AsRef<[u8]>> BlockHash for H {}
65
66/// The block was invalid.
67#[derive(Clone, Copy, Debug)]
68pub enum InvalidBlock {
69 /// This block is fatally invalid.
70 ///
71 /// If a block proposal is received, yet the block is considered fatally invalid, the proposal
72 /// will be dropped as if not received. The block proposal will not be voted for and received
73 /// votes will be unrecognized.
74 ///
75 /// Note this only affects block _proposals_, not blocks synced with their commits.
76 Fatal,
77
78 /// The block is temporally invalid.
79 ///
80 /// If a block proposal is received, yet the block is solely considered temporally invalid, the
81 /// proposal will still be stored. The block proposal will not be voted for, but received votes
82 /// will still be recognized, enabling participation in forming a commit, potentially adding this
83 /// block despite its temporal invalidity (due to a supermajority of validators voting for it).
84 Temporal,
85}
86
87/// A view over the application layer's block.
88///
89/// The [`borsh::BorshSerialize`] implementation MUST be infallible if the underlying writer is
90/// infallible. The [`borsh::BorshDeserialize`] implementation MUST be infallible if it is
91/// deserializing a value which was successfully serialized, from a well-formed reader.
92pub trait Block: Clone {
93 // The type representing a block's hash.
94 ///
95 /// The `AsRef<[u8]>` implementation MUST return a slice with a consistent length for _any_
96 /// value, meaning it's _constant_.
97 ///
98 /// The [`borsh::BorshSerialize`] implementation MUST be infallible if the underlying writer is
99 /// infallible. The [`borsh::BorshDeserialize`] implementation MUST be infallible if it is
100 /// deserializing a value which was successfully serialized, from a well-formed reader.
101 type Hash: BlockHash;
102
103 /// The block's proposal hash.
104 ///
105 /// This MUST be cryptographically binding to the entirety of the block.
106 ///
107 /// This MUST always return the same hash for a value upon each call.
108 fn proposal_hash(&self) -> Self::Hash;
109
110 /// The hash of the block's semantics.
111 ///
112 /// This is used for commits, allowing commits to not bind to signature data, enabling
113 /// optimizations.
114 ///
115 /// This MUST be cryptographically binding to the entirety of the block's semantics.
116 ///
117 /// For two blocks, `b1` and `b2`, `b1 == b2` MUST equal
118 /// `b1.semantic_hash() == b2.semantic_hash()`, except with negligible probability (per the
119 /// binding property).
120 ///
121 /// This MUST always return the same hash for a value upon each call.
122 fn semantic_hash(&self) -> Self::Hash;
123}
124
125/// A view of the application layer's blockchain.
126pub trait Blockchain {
127 /// The type used to identify validators.
128 ///
129 /// It is RECOMMENDED to use [`u16`] to identify validators.
130 type Validator: Validator;
131 /// The type used to define the validator set.
132 type ValidatorSet: ?Sized + ValidatorSet<Validator = Self::Validator>;
133 /// The signature scheme used by validators.
134 type SignatureScheme: ?Sized + SignatureScheme<Validator = Self::Validator>;
135
136 /// The type used to represent the genesis of this blockchain.
137 ///
138 /// This DOES NOT need to satisfy any cryptographic binding properties and is solely used for
139 /// domain-separation purposes. The slice this may be taken as a reference to MUST be consistent
140 /// across calls and MUST have a length less than or equal to [`u8::MAX`].
141 type Genesis: AsRef<[u8]>;
142
143 /// The block type.
144 type Block: Block;
145
146 /// The future for a block proposal.
147 ///
148 /// This allows the proposal to not be _immediately_ ready, such as if the blockchain is still
149 /// syncing, where this future will be occasionally polled (likely infrequently) for if the
150 /// proposal is ready. It is RECOMMENDED to literally instantiate it with
151 /// [`futures_channel::oneshot::Receiver`] or similar.
152 /*
153 TODO: Remove this `Unpin` bound. While the application can trivially satisfy it with a
154 `Pin<Box<_>>` wrapper, it shouldn't be necessary to expose.
155 */
156 type BlockProposal: Unpin + Future<Output = Self::Block>;
157
158 /// The genesis ID for this blockchain.
159 ///
160 /// This MUST be consistent for the lifetime of this blockchain and unique across blockchains.
161 fn genesis(&self) -> &Self::Genesis;
162
163 /// The validator set's definition.
164 ///
165 /// This MUST be consistent for the lifetime of this blockchain.
166 fn validator_set(&self) -> &Self::ValidatorSet;
167
168 /// The signature scheme for this blockchain.
169 fn signature_scheme(&self) -> &Self::SignatureScheme;
170
171 /// Validate a block.
172 ///
173 /// This SHOULD NOT cause any mutations to the blockchain. This solely validates a potential
174 /// candidate with minimal context passed and no call pattern guaranteed. The proposer is
175 /// specified in case the blockchain wishes to record a slash for this block, if it is
176 /// fundamentally invalid.
177 ///
178 /// This DOES NOT have to be cancel-safe.
179 // TODO: Don't just provide the proposer, but enough to build evidence sufficient to convince
180 // someone else (the signed proposal message)?
181 fn validate(
182 &mut self,
183 proposer: Self::Validator,
184 block: &Self::Block,
185 ) -> impl Send + Future<Output = Result<(), InvalidBlock>>;
186
187 /// Add a block, returning a future for the proposal for the next block.
188 ///
189 /// It's possible a block, which was never validated or even failed validation, may be passed
190 /// here if a supermajority of validators did consider it valid and created a verified commit for
191 /// it. This deviates from the paper which will have a local node refuse to decide on a block it
192 /// considers invalid. This library acknowledges the validators did decide on it, leaving
193 /// handling of it to the application layer, and outside of this scope. If this block is invalid,
194 /// it's a break in the assumptions required for Tendermint's soundness.
195 ///
196 /// The proposal for the next block is returned as a [`Future`]. This allows the proposal to not
197 /// be ready _yet_, such as if the blockchain is still syncing, where this future will be
198 /// occasionally polled (likely infrequently) for if the proposal is ready. It likely SHOULD be
199 /// literally instantiated with [`futures_channel::oneshot::Receiver`] or similar.
200 ///
201 /// This MAY be called multiple times if the process reboots before the Tendermint process
202 /// commits its advanced state. The underlying blockchain MUST be able to handle being asked to
203 /// add a block which it already added.
204 ///
205 /// This DOES NOT have to be cancel-safe.
206 fn add_block(
207 &mut self,
208 block: Self::Block,
209 commit: CommitFor<Self>,
210 ) -> impl Send + Future<Output = Self::BlockProposal>;
211
212 /// Record a missed proposal.
213 ///
214 /// This is a non-`async` function as this is expected to be implemented in a non-blocking
215 /// fashion as to not hold up the consensus process.
216 ///
217 /// A missed proposal is LIKELY something which should cause the validator to be slashed.
218 /// However, there is no evidence for a missed proposal as it may have never been sent, or may
219 /// have simply not been received by the local view (which may be the one faulty). For this
220 /// reason, it's explicitly distinguished from a slash.
221 // TODO: `&mut self`?
222 fn missed_proposal(&self, proposer: Self::Validator);
223
224 /// Slash a validator.
225 ///
226 /// This is a non-`async` function as this is expected to be implemented in a non-blocking
227 /// fashion as to not hold up the consensus process.
228 ///
229 /// The actual recording of this slash and its interpretation is left entirely to the application
230 /// layer. All slashes have the necessary evidence and can be verified by this library.
231 fn slash(&mut self, validator: Self::Validator, slash_reason: SlashReasonFor<Self>);
232}