1use consensus_config::{AuthorityIndex, Epoch, Stake};
5use consensus_types::block::{BlockRef, Round};
6use fastcrypto::error::FastCryptoError;
7use strum_macros::IntoStaticStr;
8use thiserror::Error;
9use typed_store::TypedStoreError;
10
11use crate::commit::{Commit, CommitIndex};
12
13#[derive(Clone, Debug, Error, IntoStaticStr)]
15pub enum ConsensusError {
16 #[error("Error deserializing block: {0}")]
17 MalformedBlock(bcs::Error),
18
19 #[error("Error deserializing commit: {0}")]
20 MalformedCommit(bcs::Error),
21
22 #[error("Error serializing: {0}")]
23 SerializationFailure(bcs::Error),
24
25 #[error("Block contains a transaction that is too large: {size} > {limit}")]
26 TransactionTooLarge { size: usize, limit: usize },
27
28 #[error("Block contains too many transactions: {count} > {limit}")]
29 TooManyTransactions { count: usize, limit: usize },
30
31 #[error("Block contains too many transaction bytes: {size} > {limit}")]
32 TooManyTransactionBytes { size: usize, limit: usize },
33
34 #[error("Unexpected block authority {0} from peer {1}")]
35 UnexpectedAuthority(AuthorityIndex, AuthorityIndex),
36
37 #[error("Block has wrong epoch: expected {expected}, actual {actual}")]
38 WrongEpoch { expected: Epoch, actual: Epoch },
39
40 #[error("Genesis blocks should only be generated from Committee!")]
41 UnexpectedGenesisBlock,
42
43 #[error("Genesis blocks should not be queried!")]
44 UnexpectedGenesisBlockRequested,
45
46 #[error(
47 "Expected {requested} but received {received} blocks returned from authority {authority}"
48 )]
49 UnexpectedNumberOfBlocksFetched {
50 authority: AuthorityIndex,
51 requested: usize,
52 received: usize,
53 },
54
55 #[error("Unexpected block returned while fetching missing blocks")]
56 UnexpectedFetchedBlock {
57 index: AuthorityIndex,
58 block_ref: BlockRef,
59 },
60
61 #[error(
62 "Unexpected block {block_ref} returned while fetching last own block from peer {index}"
63 )]
64 UnexpectedLastOwnBlock {
65 index: AuthorityIndex,
66 block_ref: BlockRef,
67 },
68
69 #[error(
70 "Too many blocks have been returned from authority {0} when requesting to fetch missing blocks"
71 )]
72 TooManyFetchedBlocksReturned(AuthorityIndex),
73
74 #[error("Too many authorities have been provided from authority {0}")]
75 TooManyAuthoritiesProvided(AuthorityIndex),
76
77 #[error(
78 "Provided size of highest accepted rounds parameter, {0}, is different than committee size, {1}"
79 )]
80 InvalidSizeOfHighestAcceptedRounds(usize, usize),
81
82 #[error("Invalid authority index: {index} > {max}")]
83 InvalidAuthorityIndex { index: AuthorityIndex, max: usize },
84
85 #[error("Failed to deserialize signature: {0}")]
86 MalformedSignature(FastCryptoError),
87
88 #[error("Failed to verify the block's signature: {0}")]
89 SignatureVerificationFailure(FastCryptoError),
90
91 #[error("Synchronizer for fetching blocks directly from {0} is saturated")]
92 SynchronizerSaturated(AuthorityIndex),
93
94 #[error("Block {block_ref:?} rejected: {reason}")]
95 BlockRejected { block_ref: BlockRef, reason: String },
96
97 #[error(
98 "Ancestor is in wrong position: block {block_authority}, ancestor {ancestor_authority}, position {position}"
99 )]
100 InvalidAncestorPosition {
101 block_authority: AuthorityIndex,
102 ancestor_authority: AuthorityIndex,
103 position: usize,
104 },
105
106 #[error("Ancestor's round ({ancestor}) should be lower than the block's round ({block})")]
107 InvalidAncestorRound { ancestor: Round, block: Round },
108
109 #[error("Ancestor {0} not found among genesis blocks!")]
110 InvalidGenesisAncestor(BlockRef),
111
112 #[error("Too many ancestors in the block: {0} > {1}")]
113 TooManyAncestors(usize, usize),
114
115 #[error("Ancestors from the same authority {0}")]
116 DuplicatedAncestorsAuthority(AuthorityIndex),
117
118 #[error("Insufficient stake from parents: {parent_stakes} < {quorum}")]
119 InsufficientParentStakes { parent_stakes: Stake, quorum: Stake },
120
121 #[error("Invalid transaction: {0}")]
122 InvalidTransaction(String),
123
124 #[error("Received no commit from peer {peer}")]
125 NoCommitReceived { peer: AuthorityIndex },
126
127 #[error(
128 "Received unexpected start commit from peer {peer}: requested {start}, received {commit:?}"
129 )]
130 UnexpectedStartCommit {
131 peer: AuthorityIndex,
132 start: CommitIndex,
133 commit: Box<Commit>,
134 },
135
136 #[error(
137 "Received unexpected commit sequence from peer {peer}: {prev_commit:?}, {curr_commit:?}"
138 )]
139 UnexpectedCommitSequence {
140 peer: AuthorityIndex,
141 prev_commit: Box<Commit>,
142 curr_commit: Box<Commit>,
143 },
144
145 #[error("Not enough votes ({stake}) on end commit from peer {peer}: {commit:?}")]
146 NotEnoughCommitVotes {
147 stake: Stake,
148 peer: AuthorityIndex,
149 commit: Box<Commit>,
150 },
151
152 #[error("Received unexpected block from peer {peer}: {requested:?} vs {received:?}")]
153 UnexpectedBlockForCommit {
154 peer: AuthorityIndex,
155 requested: BlockRef,
156 received: BlockRef,
157 },
158
159 #[error(
160 "Unexpected certified commit index and last committed index. Expected next commit index to be {expected_commit_index}, but found {commit_index}"
161 )]
162 UnexpectedCertifiedCommitIndex {
163 expected_commit_index: CommitIndex,
164 commit_index: CommitIndex,
165 },
166
167 #[error("RocksDB failure: {0}")]
168 RocksDBFailure(#[from] TypedStoreError),
169
170 #[error("Unknown network peer: {0}")]
171 UnknownNetworkPeer(String),
172
173 #[error("Peer {0} is disconnected.")]
174 PeerDisconnected(String),
175
176 #[error("Network config error: {0:?}")]
177 NetworkConfig(String),
178
179 #[error("Failed to connect as client: {0:?}")]
180 NetworkClientConnection(String),
181
182 #[error("Failed to send request: {0:?}")]
183 NetworkRequest(String),
184
185 #[error("Request timeout: {0:?}")]
186 NetworkRequestTimeout(String),
187
188 #[error("Consensus has shut down!")]
189 Shutdown,
190}
191
192impl ConsensusError {
193 pub fn name(&self) -> &'static str {
195 self.into()
196 }
197}
198
199pub type ConsensusResult<T> = Result<T, ConsensusError>;
200
201#[macro_export]
202macro_rules! bail {
203 ($e:expr) => {
204 return Err($e);
205 };
206}
207
208#[macro_export(local_inner_macros)]
209macro_rules! ensure {
210 ($cond:expr, $e:expr) => {
211 if !($cond) {
212 bail!($e);
213 }
214 };
215}
216
217#[cfg(test)]
218mod test {
219 use super::*;
220
221 #[test]
224 fn test_error_name() {
225 {
226 let error = ConsensusError::InvalidAncestorRound {
227 ancestor: 10,
228 block: 11,
229 };
230 let error: &'static str = error.into();
231
232 assert_eq!(error, "InvalidAncestorRound");
233 }
234
235 {
236 let error = ConsensusError::InvalidAuthorityIndex {
237 index: AuthorityIndex::new_for_test(3),
238 max: 10,
239 };
240 assert_eq!(error.name(), "InvalidAuthorityIndex");
241 }
242
243 {
244 let error = ConsensusError::InsufficientParentStakes {
245 parent_stakes: 5,
246 quorum: 20,
247 };
248 assert_eq!(error.name(), "InsufficientParentStakes");
249 }
250 }
251}