1use std::{array::TryFromSliceError, convert::Infallible};
9
10use chrono::{DateTime, Utc};
11use thiserror::Error;
12
13use zcash_protocol::value::BalanceError;
14use zebra_chain::{
15 amount, block, ironwood, orchard,
16 parameters::subsidy::SubsidyError,
17 sapling, sprout,
18 transparent::{self, MIN_TRANSPARENT_COINBASE_MATURITY},
19};
20use zebra_state::ValidateContextError;
21
22use crate::{
23 block::MAX_BLOCK_SIGOPS,
24 transaction::check::{MAX_STANDARD_SCRIPTSIG_SIZE, MAX_STANDARD_TX_SIGOPS},
25 BoxError,
26};
27
28#[cfg(any(test, feature = "proptest-impl"))]
29use proptest_derive::Arbitrary;
30
31#[cfg(test)]
32mod tests;
33
34const MAX_EXPIRY_HEIGHT: block::Height = block::Height::MAX_EXPIRY_HEIGHT;
36
37#[derive(Error, Clone, Debug, PartialEq, Eq)]
39#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
40#[allow(missing_docs)]
41pub enum TransactionError {
42 #[error("first transaction must be coinbase")]
43 CoinbasePosition,
44
45 #[error("coinbase input found in non-coinbase transaction")]
46 CoinbaseAfterFirst,
47
48 #[error("coinbase transaction MUST NOT have any JoinSplit descriptions")]
49 CoinbaseHasJoinSplit,
50
51 #[error("coinbase transaction MUST NOT have any Spend descriptions")]
52 CoinbaseHasSpend,
53
54 #[error("coinbase transaction MUST NOT have any Output descriptions pre-Heartwood")]
55 CoinbaseHasOutputPreHeartwood,
56
57 #[error("coinbase transaction MUST NOT have the EnableSpendsOrchard flag set")]
58 CoinbaseHasEnableSpendsOrchard,
59
60 #[error("coinbase transaction MUST NOT have the EnableSpendsIronwood flag set")]
61 CoinbaseHasEnableSpendsIronwood,
62
63 #[error("coinbase transaction MUST have an empty Orchard component (no Orchard actions) from NU6.3 onward")]
64 CoinbaseHasOrchardActions,
65
66 #[error("Orchard transaction MUST NOT have the EnableCrossAddress flag set")]
67 OrchardHasEnableCrossAddress,
68
69 #[error("coinbase transaction Sapling or Orchard outputs MUST be decryptable with an all-zero outgoing viewing key")]
70 CoinbaseOutputsNotDecryptable,
71
72 #[error("coinbase inputs MUST NOT exist in mempool")]
73 CoinbaseInMempool,
74
75 #[error("non-coinbase transactions MUST NOT have coinbase inputs")]
76 NonCoinbaseHasCoinbaseInput,
77
78 #[error("the tx is not coinbase, but it should be")]
79 NotCoinbase,
80
81 #[error("transaction is locked until after block height {}", _0.0)]
82 LockedUntilAfterBlockHeight(block::Height),
83
84 #[error("transaction is locked until after block time {0}")]
85 #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
86 LockedUntilAfterBlockTime(DateTime<Utc>),
87
88 #[error(
89 "coinbase expiry {expiry_height:?} must be the same as the block {block_height:?} \
90 after NU5 activation, failing transaction: {transaction_hash:?}"
91 )]
92 CoinbaseExpiryBlockHeight {
93 expiry_height: Option<zebra_chain::block::Height>,
94 block_height: zebra_chain::block::Height,
95 transaction_hash: zebra_chain::transaction::Hash,
96 },
97
98 #[error("could not construct coinbase tx: {0}")]
99 CoinbaseConstruction(String),
100
101 #[error(
102 "expiry {expiry_height:?} must be less than the maximum {MAX_EXPIRY_HEIGHT:?} \
103 coinbase: {is_coinbase}, block: {block_height:?}, failing transaction: {transaction_hash:?}"
104 )]
105 MaximumExpiryHeight {
106 expiry_height: zebra_chain::block::Height,
107 is_coinbase: bool,
108 block_height: zebra_chain::block::Height,
109 transaction_hash: zebra_chain::transaction::Hash,
110 },
111
112 #[error(
113 "transaction must not be mined at a block {block_height:?} \
114 greater than its expiry {expiry_height:?}, failing transaction {transaction_hash:?}"
115 )]
116 ExpiredTransaction {
117 expiry_height: zebra_chain::block::Height,
118 block_height: zebra_chain::block::Height,
119 transaction_hash: zebra_chain::transaction::Hash,
120 },
121
122 #[error("coinbase transaction failed subsidy validation: {0}")]
123 #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
124 Subsidy(#[from] SubsidyError),
125
126 #[error("transaction version number MUST be >= 4")]
127 WrongVersion,
128
129 #[error("transaction version {0} not supported by the network upgrade {1:?}")]
130 UnsupportedByNetworkUpgrade(u32, zebra_chain::parameters::NetworkUpgrade),
131
132 #[error("must have at least one input: transparent, shielded spend, or joinsplit")]
133 NoInputs,
134
135 #[error("must have at least one output: transparent, shielded output, or joinsplit")]
136 NoOutputs,
137
138 #[error("if there are no Spends or Outputs, the value balance MUST be 0.")]
139 BadBalance,
140
141 #[error("could not verify a transparent script: {0}")]
142 #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
143 Script(#[from] zebra_script::Error),
144
145 #[error("spend description cv and rk MUST NOT be of small order")]
146 SmallOrder,
147
148 #[error("spend proof MUST be valid given a primary input formed from the other fields except spendAuthSig: {0}")]
151 Groth16(String),
152
153 #[error("Groth16 proof is malformed: {0}")]
155 MalformedGroth16(String),
156
157 #[error(
158 "Sprout joinSplitSig MUST represent a valid signature under joinSplitPubKey of dataToBeSigned: {0}"
159 )]
160 #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
161 Ed25519(#[from] zebra_chain::primitives::ed25519::Error),
162
163 #[error("Sapling bindingSig MUST represent a valid signature under the transaction binding validating key bvk of SigHash: {0}")]
164 #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
165 RedJubjub(zebra_chain::primitives::redjubjub::Error),
166
167 #[error("Orchard bindingSig MUST represent a valid signature under the transaction binding validating key bvk of SigHash: {0}")]
168 #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
169 RedPallas(zebra_chain::primitives::reddsa::Error),
170
171 #[error("Sapling proof or signature verification failed")]
172 SaplingVerificationFailed,
173
174 #[error("Orchard or Ironwood Halo2 proof verification failed")]
175 Halo2VerificationFailed,
176
177 #[error("could not convert an asynchronous verification error: {0}")]
178 InternalDowncastError(String),
179
180 #[error("either vpub_old or vpub_new must be zero")]
181 BothVPubsNonZero,
182
183 #[error("adding to the sprout pool is disabled after Canopy")]
184 DisabledAddToSproutPool,
185
186 #[error("the Orchard value balance must be non-negative from NU6.3 onward")]
187 NegativeOrchardValueBalance,
188
189 #[error("could not calculate the transaction fee")]
190 IncorrectFee,
191
192 #[error("transparent double-spend: {_0:?} is spent twice")]
193 DuplicateTransparentSpend(transparent::OutPoint),
194
195 #[error("sprout double-spend: duplicate nullifier: {_0:?}")]
196 DuplicateSproutNullifier(sprout::Nullifier),
197
198 #[error("sapling double-spend: duplicate nullifier: {_0:?}")]
199 DuplicateSaplingNullifier(sapling::Nullifier),
200
201 #[error("orchard double-spend: duplicate nullifier: {_0:?}")]
202 DuplicateOrchardNullifier(orchard::Nullifier),
203
204 #[error("ironwood double-spend: duplicate nullifier: {_0:?}")]
205 DuplicateIronwoodNullifier(ironwood::Nullifier),
206
207 #[error("must have at least one active orchard flag")]
208 NotEnoughOrchardFlags,
209
210 #[error("must have at least one active ironwood flag")]
211 NotEnoughIronwoodFlags,
212
213 #[error("could not find transparent input UTXO in the best chain or mempool")]
214 TransparentInputNotFound,
215
216 #[error("could not contextually validate transaction on best chain: {0}")]
217 #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
218 ValidateContextError(Box<ValidateContextError>),
220
221 #[error("could not validate mempool transaction lock time on best chain: {0}")]
222 #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
223 ValidateMempoolLockTimeError(String),
225
226 #[error(
227 "immature transparent coinbase spend: \
228 attempt to spend {outpoint:?} at {spend_height:?}, \
229 but spends are invalid before {min_spend_height:?}, \
230 which is {MIN_TRANSPARENT_COINBASE_MATURITY:?} blocks \
231 after it was created at {created_height:?}"
232 )]
233 #[non_exhaustive]
234 ImmatureTransparentCoinbaseSpend {
235 outpoint: transparent::OutPoint,
236 spend_height: block::Height,
237 min_spend_height: block::Height,
238 created_height: block::Height,
239 },
240
241 #[error(
242 "unshielded transparent coinbase spend: {outpoint:?} \
243 must be spent in a transaction which only has shielded outputs"
244 )]
245 #[non_exhaustive]
246 UnshieldedTransparentCoinbaseSpend {
247 outpoint: transparent::OutPoint,
248 min_spend_height: block::Height,
249 },
250
251 #[error(
252 "failed to verify ZIP-317 transaction rules, transaction was not inserted to mempool: {0}"
253 )]
254 #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
255 Zip317(#[from] zebra_chain::transaction::zip317::Error),
256
257 #[error(
260 "mempool transaction has {count} {pool}, exceeding the next block's ZIP 218 limit of {limit}"
261 )]
262 #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
263 TooManyShieldedActions {
264 pool: &'static str,
265 count: usize,
266 limit: usize,
267 },
268
269 #[error(
272 "mempool transaction input {input_index} has a {size} byte scriptSig, \
273 above the {MAX_STANDARD_SCRIPTSIG_SIZE} byte standardness limit"
274 )]
275 NonStandardScriptSigSize { input_index: usize, size: usize },
276
277 #[error("mempool transaction input {input_index} has a non-push-only scriptSig")]
278 NonStandardScriptSigNotPushOnly { input_index: usize },
279
280 #[error("mempool transaction has non-standard transparent inputs")]
281 NonStandardInputs,
282
283 #[error(
285 "mempool transaction has {sigops} signature operations, \
286 above the {MAX_STANDARD_TX_SIGOPS} standardness limit"
287 )]
288 NonStandardSigops {
289 sigops: u32,
291 },
292
293 #[error("transaction uses an incorrect consensus branch id")]
294 WrongConsensusBranchId,
295
296 #[error("wrong tx format: tx version is ≥ 5, but `nConsensusBranchId` is missing")]
297 MissingConsensusBranchId,
298
299 #[error("input/output error")]
300 Io(String),
301
302 #[error("failed to convert a slice")]
303 TryFromSlice(String),
304
305 #[error("invalid amount")]
306 Amount(String),
307
308 #[error("invalid balance")]
309 Balance(String),
310
311 #[error("Orchard proof has a non-canonical size")]
312 OrchardProofSize,
313
314 #[error("Ironwood proof has a non-canonical size")]
315 IronwoodProofSize,
316
317 #[error("unexpected error")]
318 Other(String),
319}
320
321impl From<ValidateContextError> for TransactionError {
322 fn from(err: ValidateContextError) -> Self {
323 TransactionError::ValidateContextError(Box::new(err))
324 }
325}
326
327impl From<zcash_transparent::builder::Error> for TransactionError {
328 fn from(err: zcash_transparent::builder::Error) -> Self {
329 TransactionError::CoinbaseConstruction(err.to_string())
330 }
331}
332
333impl From<zcash_primitives::transaction::builder::Error<Infallible>> for TransactionError {
334 fn from(err: zcash_primitives::transaction::builder::Error<Infallible>) -> Self {
335 TransactionError::CoinbaseConstruction(err.to_string())
336 }
337}
338
339impl From<BalanceError> for TransactionError {
340 fn from(err: BalanceError) -> Self {
341 TransactionError::Balance(err.to_string())
342 }
343}
344
345impl From<libzcash_script::Error> for TransactionError {
346 fn from(err: libzcash_script::Error) -> Self {
347 TransactionError::Script(zebra_script::Error::from(err))
348 }
349}
350
351impl From<std::io::Error> for TransactionError {
352 fn from(err: std::io::Error) -> Self {
353 TransactionError::Io(err.to_string())
354 }
355}
356
357impl From<TryFromSliceError> for TransactionError {
358 fn from(err: TryFromSliceError) -> Self {
359 TransactionError::TryFromSlice(err.to_string())
360 }
361}
362
363impl From<amount::Error> for TransactionError {
364 fn from(err: amount::Error) -> Self {
365 TransactionError::Amount(err.to_string())
366 }
367}
368
369impl From<BoxError> for TransactionError {
371 fn from(mut err: BoxError) -> Self {
372 match err.downcast::<zebra_script::Error>() {
381 Ok(e) => return TransactionError::Script(*e),
382 Err(e) => err = e,
383 }
384
385 match err.downcast::<zebra_chain::primitives::ed25519::Error>() {
386 Ok(e) => return TransactionError::Ed25519(*e),
387 Err(e) => err = e,
388 }
389
390 match err.downcast::<zebra_chain::primitives::redjubjub::Error>() {
391 Ok(e) => return TransactionError::RedJubjub(*e),
392 Err(e) => err = e,
393 }
394
395 match err.downcast::<zebra_chain::primitives::reddsa::Error>() {
396 Ok(e) => return TransactionError::RedPallas(*e),
397 Err(e) => err = e,
398 }
399
400 match err.downcast::<ValidateContextError>() {
401 Ok(e) => return (*e).into(),
402 Err(e) => err = e,
403 }
404
405 match err.downcast::<TransactionError>() {
407 Ok(e) => return *e,
408 Err(e) => err = e,
409 }
410
411 TransactionError::InternalDowncastError(format!(
412 "downcast to known transaction error type failed, original error: {err:?}",
413 ))
414 }
415}
416
417impl TransactionError {
418 pub fn mempool_misbehavior_score(&self) -> u32 {
421 use TransactionError::*;
422
423 match self {
425 ImmatureTransparentCoinbaseSpend { .. }
426 | UnshieldedTransparentCoinbaseSpend { .. }
427 | CoinbasePosition
428 | CoinbaseAfterFirst
429 | CoinbaseHasJoinSplit
430 | CoinbaseHasSpend
431 | CoinbaseHasOutputPreHeartwood
432 | CoinbaseHasEnableSpendsOrchard
433 | CoinbaseHasEnableSpendsIronwood
434 | CoinbaseHasOrchardActions
435 | OrchardHasEnableCrossAddress
436 | CoinbaseOutputsNotDecryptable
437 | CoinbaseInMempool
438 | NonCoinbaseHasCoinbaseInput
439 | CoinbaseExpiryBlockHeight { .. }
440 | IncorrectFee
441 | Subsidy(_)
442 | WrongVersion
443 | NoInputs
444 | NoOutputs
445 | BadBalance
446 | Script(_)
447 | SmallOrder
448 | Groth16(_)
449 | MalformedGroth16(_)
450 | Ed25519(_)
451 | RedJubjub(_)
452 | RedPallas(_)
453 | SaplingVerificationFailed
454 | Halo2VerificationFailed
455 | OrchardProofSize
456 | IronwoodProofSize
457 | BothVPubsNonZero
458 | DisabledAddToSproutPool
459 | NegativeOrchardValueBalance
460 | NotEnoughOrchardFlags
461 | NotEnoughIronwoodFlags
462 | WrongConsensusBranchId
463 | MissingConsensusBranchId
464 | LockedUntilAfterBlockHeight(_)
465 | LockedUntilAfterBlockTime(_) => 100,
466
467 _other => 0,
471 }
472 }
473}
474
475#[derive(Error, Clone, Debug, PartialEq, Eq)]
476#[allow(missing_docs)]
477pub enum BlockError {
478 #[error("block contains invalid transactions")]
479 Transaction(#[from] TransactionError),
480
481 #[error("block has no transactions")]
482 NoTransactions,
483
484 #[error("block has mismatched merkle root")]
485 BadMerkleRoot {
486 actual: zebra_chain::block::merkle::Root,
487 expected: zebra_chain::block::merkle::Root,
488 },
489
490 #[error("block contains duplicate transactions")]
491 DuplicateTransaction,
492
493 #[error("block {0:?} is already in present in the state {1:?}")]
494 AlreadyInChain(zebra_chain::block::Hash, zebra_state::KnownBlock),
495
496 #[error("invalid block {0:?}: missing block height")]
497 MissingHeight(zebra_chain::block::Hash),
498
499 #[error("invalid block height {0:?} in {1:?}: greater than the maximum height {2:?}")]
500 MaxHeight(
501 zebra_chain::block::Height,
502 zebra_chain::block::Hash,
503 zebra_chain::block::Height,
504 ),
505
506 #[error("invalid difficulty threshold in block header {0:?} {1:?}")]
507 InvalidDifficulty(zebra_chain::block::Height, zebra_chain::block::Hash),
508
509 #[error("block {0:?} has a difficulty threshold {2:?} that is easier than the {3:?} difficulty limit {4:?}, hash: {1:?}")]
510 TargetDifficultyLimit(
511 zebra_chain::block::Height,
512 zebra_chain::block::Hash,
513 zebra_chain::work::difficulty::ExpandedDifficulty,
514 zebra_chain::parameters::Network,
515 zebra_chain::work::difficulty::ExpandedDifficulty,
516 ),
517
518 #[error(
519 "block {0:?} on {3:?} has a hash {1:?} that is easier than its difficulty threshold {2:?}"
520 )]
521 DifficultyFilter(
522 zebra_chain::block::Height,
523 zebra_chain::block::Hash,
524 zebra_chain::work::difficulty::ExpandedDifficulty,
525 zebra_chain::parameters::Network,
526 ),
527
528 #[error("transaction has wrong consensus branch id for block network upgrade")]
529 WrongTransactionConsensusBranchId,
530
531 #[error("block {height:?} {hash:?} has {count} {pool}, but the limit is {limit}")]
532 TooManyShieldedActions {
533 height: zebra_chain::block::Height,
534 hash: zebra_chain::block::Hash,
535 pool: &'static str,
536 count: usize,
537 limit: usize,
538 },
539
540 #[error(
541 "block {height:?} {hash:?} has {sigops} legacy transparent signature operations, \
542 but the limit is {MAX_BLOCK_SIGOPS}"
543 )]
544 TooManyTransparentSignatureOperations {
545 height: zebra_chain::block::Height,
546 hash: zebra_chain::block::Hash,
547 sigops: u32,
548 },
549
550 #[error("summing miner fees for block {height:?} {hash:?} failed: {source:?}")]
551 SummingMinerFees {
552 height: zebra_chain::block::Height,
553 hash: zebra_chain::block::Hash,
554 source: amount::Error,
555 },
556
557 #[error("unexpected error occurred: {0}")]
558 Other(String),
559}
560
561impl From<SubsidyError> for BlockError {
562 fn from(err: SubsidyError) -> BlockError {
563 BlockError::Transaction(TransactionError::Subsidy(err))
564 }
565}
566
567impl From<amount::Error> for BlockError {
568 fn from(e: amount::Error) -> Self {
569 Self::from(SubsidyError::from(e))
570 }
571}
572
573impl BlockError {
574 pub fn is_duplicate_request(&self) -> bool {
577 matches!(self, BlockError::AlreadyInChain(..))
578 }
579
580 pub(crate) fn misbehavior_score(&self) -> u32 {
582 use BlockError::*;
583
584 match self {
585 MissingHeight(_)
586 | MaxHeight(_, _, _)
587 | InvalidDifficulty(_, _)
588 | TargetDifficultyLimit(_, _, _, _, _)
589 | DifficultyFilter(_, _, _, _)
590 | NoTransactions
591 | BadMerkleRoot { .. }
592 | WrongTransactionConsensusBranchId
593 | TooManyTransparentSignatureOperations { .. }
594 | TooManyShieldedActions { .. }
597 | DuplicateTransaction => 100,
601 Transaction(err) => err.mempool_misbehavior_score(),
602 _other => 0,
603 }
604 }
605}