zakura-consensus 5.0.0

Implementation of Zcash consensus checks for the Zakura node. Internal crate, published to support cargo install zakura
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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
//! Errors that can occur when checking consensus rules.
//!
//! Each error variant corresponds to a consensus rule, so enumerating
//! all possible verification failures enumerates the consensus rules we
//! implement, and ensures that we don't reject blocks or transactions
//! for a non-enumerated reason.

use std::{array::TryFromSliceError, convert::Infallible};

use chrono::{DateTime, Utc};
use thiserror::Error;

use zakura_chain::{
    amount, block, ironwood, orchard,
    parameters::subsidy::SubsidyError,
    sapling, sprout,
    transparent::{self, MIN_TRANSPARENT_COINBASE_MATURITY},
};
use zakura_state::ValidateContextError;
use zcash_protocol::value::BalanceError;

use crate::{block::MAX_BLOCK_SIGOPS, transaction::check::MAX_STANDARD_SCRIPTSIG_SIZE, BoxError};

#[cfg(any(test, feature = "proptest-impl"))]
use proptest_derive::Arbitrary;

/// Workaround for format string identifier rules.
const MAX_EXPIRY_HEIGHT: block::Height = block::Height::MAX_EXPIRY_HEIGHT;

/// Errors for semantic transaction validation.
#[derive(Error, Clone, Debug, PartialEq, Eq)]
#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
#[allow(missing_docs)]
pub enum TransactionError {
    #[error("first transaction must be coinbase")]
    CoinbasePosition,

    #[error("coinbase input found in non-coinbase transaction")]
    CoinbaseAfterFirst,

    #[error("coinbase transaction MUST NOT have any JoinSplit descriptions")]
    CoinbaseHasJoinSplit,

    #[error("coinbase transaction MUST NOT have any Spend descriptions")]
    CoinbaseHasSpend,

    #[error("coinbase transaction MUST NOT have any Output descriptions pre-Heartwood")]
    CoinbaseHasOutputPreHeartwood,

    #[error("coinbase transaction MUST NOT have the EnableSpendsOrchard flag set")]
    CoinbaseHasEnableSpendsOrchard,

    #[error("coinbase transaction MUST NOT have the EnableSpendsIronwood flag set")]
    CoinbaseHasEnableSpendsIronwood,

    #[error("coinbase transaction MUST NOT have an Orchard shielded bundle")]
    CoinbaseHasOrchardShieldedData,

    #[error("coinbase transaction Sapling or Orchard outputs MUST be decryptable with an all-zero outgoing viewing key")]
    CoinbaseOutputsNotDecryptable,

    #[error("coinbase inputs MUST NOT exist in mempool")]
    CoinbaseInMempool,

    #[error("non-coinbase transactions MUST NOT have coinbase inputs")]
    NonCoinbaseHasCoinbaseInput,

    #[error("the tx is not coinbase, but it should be")]
    NotCoinbase,

    #[error("transaction is locked until after block height {}", _0.0)]
    LockedUntilAfterBlockHeight(block::Height),

    #[error("transaction is locked until after block time {0}")]
    #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
    LockedUntilAfterBlockTime(DateTime<Utc>),

    #[error(
        "coinbase expiry {expiry_height:?} must be the same as the block {block_height:?} \
         after NU5 activation, failing transaction: {transaction_hash:?}"
    )]
    CoinbaseExpiryBlockHeight {
        expiry_height: Option<zakura_chain::block::Height>,
        block_height: zakura_chain::block::Height,
        transaction_hash: zakura_chain::transaction::Hash,
    },

    #[error("could not construct coinbase tx: {0}")]
    CoinbaseConstruction(String),

    #[error(
        "expiry {expiry_height:?} must be less than the maximum {MAX_EXPIRY_HEIGHT:?} \
         coinbase: {is_coinbase}, block: {block_height:?}, failing transaction: {transaction_hash:?}"
    )]
    MaximumExpiryHeight {
        expiry_height: zakura_chain::block::Height,
        is_coinbase: bool,
        block_height: zakura_chain::block::Height,
        transaction_hash: zakura_chain::transaction::Hash,
    },

    #[error(
        "transaction must not be mined at a block {block_height:?} \
         greater than its expiry {expiry_height:?}, failing transaction {transaction_hash:?}"
    )]
    ExpiredTransaction {
        expiry_height: zakura_chain::block::Height,
        block_height: zakura_chain::block::Height,
        transaction_hash: zakura_chain::transaction::Hash,
    },

    #[error("coinbase transaction failed subsidy validation: {0}")]
    #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
    Subsidy(#[from] SubsidyError),

    #[error("transaction version number MUST be >= 4")]
    WrongVersion,

    #[error("transaction version {0} not supported by the network upgrade {1:?}")]
    UnsupportedByNetworkUpgrade(u32, zakura_chain::parameters::NetworkUpgrade),

    #[error("must have at least one input: transparent, shielded spend, or joinsplit")]
    NoInputs,

    #[error("must have at least one output: transparent, shielded output, or joinsplit")]
    NoOutputs,

    #[error("if there are no Spends or Outputs, the value balance MUST be 0.")]
    BadBalance,

    #[error("could not verify a transparent script: {0}")]
    #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
    Script(#[from] zakura_script::Error),

    #[error("Sapling proof or signature verification failed")]
    SaplingVerificationFailed,

    #[error("Orchard or Ironwood Halo2 proof verification failed")]
    Halo2VerificationFailed,

    #[error("spend description cv and rk MUST NOT be of small order")]
    SmallOrder,

    // TODO: the underlying error is bellman::VerificationError, but it does not implement
    // Arbitrary as required here.
    #[error("spend proof MUST be valid given a primary input formed from the other fields except spendAuthSig: {0}")]
    Groth16(String),

    // TODO: the underlying error is io::Error, but it does not implement Clone as required here.
    #[error("Groth16 proof is malformed: {0}")]
    MalformedGroth16(String),

    #[error(
        "Sprout joinSplitSig MUST represent a valid signature under joinSplitPubKey of dataToBeSigned: {0}"
    )]
    #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
    Ed25519(#[from] zakura_chain::primitives::ed25519::Error),

    #[error("Sapling bindingSig MUST represent a valid signature under the transaction binding validating key bvk of SigHash: {0}")]
    #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
    RedJubjub(zakura_chain::primitives::redjubjub::Error),

    #[error("Orchard bindingSig MUST represent a valid signature under the transaction binding validating key bvk of SigHash: {0}")]
    #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
    RedPallas(zakura_chain::primitives::reddsa::Error),

    #[error("could not convert an asynchronous verification error: {0}")]
    InternalDowncastError(String),

    #[error("either vpub_old or vpub_new must be zero")]
    BothVPubsNonZero,

    #[error("adding to the sprout pool is disabled after Canopy")]
    DisabledAddToSproutPool,

    #[error("adding to the orchard pool is disabled after NU6.3")]
    DisabledAddToOrchardPool,

    #[error("could not calculate the transaction fee")]
    IncorrectFee,

    #[error("transparent double-spend: {_0:?} is spent twice")]
    DuplicateTransparentSpend(transparent::OutPoint),

    #[error("sprout double-spend: duplicate nullifier: {_0:?}")]
    DuplicateSproutNullifier(sprout::Nullifier),

    #[error("sapling double-spend: duplicate nullifier: {_0:?}")]
    DuplicateSaplingNullifier(sapling::Nullifier),

    #[error("orchard double-spend: duplicate nullifier: {_0:?}")]
    DuplicateOrchardNullifier(orchard::Nullifier),

    #[error("ironwood double-spend: duplicate nullifier: {_0:?}")]
    DuplicateIronwoodNullifier(ironwood::Nullifier),

    #[error("must have at least one active orchard flag")]
    NotEnoughFlags,

    #[error("must have at least enable spend or enable output flag set")]
    NotEnoughIronwoodFlags,

    #[error("Orchard transactions MUST NOT have the EnableCrossAddress flag set")]
    OrchardHasEnableCrossAddress,

    #[error("could not find transparent input UTXO in the best chain or mempool")]
    TransparentInputNotFound,

    #[error("could not contextually validate transaction on best chain: {0}")]
    #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
    // This error variant is at least 128 bytes
    ValidateContextError(Box<ValidateContextError>),

    #[error("could not validate mempool transaction lock time on best chain: {0}")]
    #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
    // TODO: turn this into a typed error
    ValidateMempoolLockTimeError(String),

    #[error(
        "immature transparent coinbase spend: \
        attempt to spend {outpoint:?} at {spend_height:?}, \
        but spends are invalid before {min_spend_height:?}, \
        which is {MIN_TRANSPARENT_COINBASE_MATURITY:?} blocks \
        after it was created at {created_height:?}"
    )]
    #[non_exhaustive]
    ImmatureTransparentCoinbaseSpend {
        outpoint: transparent::OutPoint,
        spend_height: block::Height,
        min_spend_height: block::Height,
        created_height: block::Height,
    },

    #[error(
        "unshielded transparent coinbase spend: {outpoint:?} \
         must be spent in a transaction which only has shielded outputs"
    )]
    #[non_exhaustive]
    UnshieldedTransparentCoinbaseSpend {
        outpoint: transparent::OutPoint,
        min_spend_height: block::Height,
    },

    #[error(
        "failed to verify ZIP-317 transaction rules, transaction was not inserted to mempool: {0}"
    )]
    #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
    Zip317(#[from] zakura_chain::transaction::zip317::Error),

    // Mempool standardness (policy) rejections, applied before script verification.
    // These are not consensus rules: the same input scripts are valid in blocks.
    #[error(
        "mempool transaction input {input_index} has a {size} byte scriptSig, \
         above the {MAX_STANDARD_SCRIPTSIG_SIZE} byte standardness limit"
    )]
    NonStandardScriptSigSize { input_index: usize, size: usize },

    #[error("mempool transaction input {input_index} has a non-push-only scriptSig")]
    NonStandardScriptSigNotPushOnly { input_index: usize },

    #[error("mempool transaction has non-standard transparent inputs")]
    NonStandardInputs,

    #[error("transaction uses an incorrect consensus branch id")]
    WrongConsensusBranchId,

    #[error(
        "mempool transaction uses the NU6.2 consensus branch id during the NU6.3 grace period"
    )]
    WrongConsensusBranchIdNu6_3GracePeriod,

    #[error("wrong tx format: tx version is ≥ 5, but `nConsensusBranchId` is missing")]
    MissingConsensusBranchId,

    #[error("input/output error")]
    Io(String),

    #[error("failed to convert a slice")]
    TryFromSlice(String),

    #[error("invalid amount")]
    Amount(String),

    #[error("invalid balance")]
    Balance(String),

    #[error("Orchard proof has a non-canonical size")]
    OrchardProofSize,

    #[error("Ironwood proof has a non-canonical size")]
    IronwoodProofSize,

    #[error("unexpected error")]
    Other(String),
}

impl From<ValidateContextError> for TransactionError {
    fn from(err: ValidateContextError) -> Self {
        TransactionError::ValidateContextError(Box::new(err))
    }
}

impl From<zcash_transparent::builder::Error> for TransactionError {
    fn from(err: zcash_transparent::builder::Error) -> Self {
        TransactionError::CoinbaseConstruction(err.to_string())
    }
}

impl From<zcash_primitives::transaction::builder::Error<Infallible>> for TransactionError {
    fn from(err: zcash_primitives::transaction::builder::Error<Infallible>) -> Self {
        TransactionError::CoinbaseConstruction(err.to_string())
    }
}

impl From<BalanceError> for TransactionError {
    fn from(err: BalanceError) -> Self {
        TransactionError::Balance(err.to_string())
    }
}

impl From<libzcash_script::Error> for TransactionError {
    fn from(err: libzcash_script::Error) -> Self {
        TransactionError::Script(zakura_script::Error::from(err))
    }
}

impl From<std::io::Error> for TransactionError {
    fn from(err: std::io::Error) -> Self {
        TransactionError::Io(err.to_string())
    }
}

impl From<TryFromSliceError> for TransactionError {
    fn from(err: TryFromSliceError) -> Self {
        TransactionError::TryFromSlice(err.to_string())
    }
}

impl From<amount::Error> for TransactionError {
    fn from(err: amount::Error) -> Self {
        TransactionError::Amount(err.to_string())
    }
}

impl From<BoxError> for TransactionError {
    fn from(mut err: BoxError) -> Self {
        match err.downcast::<zakura_script::Error>() {
            Ok(e) => return TransactionError::Script(*e),
            Err(e) => err = e,
        }

        match err.downcast::<zakura_chain::primitives::ed25519::Error>() {
            Ok(e) => return TransactionError::Ed25519(*e),
            Err(e) => err = e,
        }
        match err.downcast::<zakura_chain::primitives::redjubjub::Error>() {
            Ok(e) => return TransactionError::RedJubjub(*e),
            Err(e) => err = e,
        }

        match err.downcast::<zakura_chain::primitives::reddsa::Error>() {
            Ok(e) => return TransactionError::RedPallas(*e),
            Err(e) => err = e,
        }

        match err.downcast::<ValidateContextError>() {
            Ok(e) => return (*e).into(),
            Err(e) => err = e,
        }

        // buffered transaction verifier service error
        match err.downcast::<TransactionError>() {
            Ok(e) => return *e,
            Err(e) => err = e,
        }

        TransactionError::InternalDowncastError(format!(
            "downcast to known transaction error type failed, original error: {err:?}",
        ))
    }
}

impl TransactionError {
    /// Returns a suggested misbehaviour score increment for a certain error when
    /// verifying a mempool transaction.
    pub fn mempool_misbehavior_score(&self) -> u32 {
        use TransactionError::*;

        // TODO: Adjust these values based on zcashd (#9258).
        match self {
            ImmatureTransparentCoinbaseSpend { .. }
            | UnshieldedTransparentCoinbaseSpend { .. }
            | CoinbasePosition
            | CoinbaseAfterFirst
            | CoinbaseHasJoinSplit
            | CoinbaseHasSpend
            | CoinbaseHasOutputPreHeartwood
            | CoinbaseHasEnableSpendsOrchard
            | CoinbaseHasEnableSpendsIronwood
            | CoinbaseHasOrchardShieldedData
            | CoinbaseOutputsNotDecryptable
            | CoinbaseInMempool
            | NonCoinbaseHasCoinbaseInput
            | CoinbaseExpiryBlockHeight { .. }
            | IncorrectFee
            | Subsidy(_)
            | WrongVersion
            | NoInputs
            | NoOutputs
            | BadBalance
            | Script(_)
            | SaplingVerificationFailed
            | Halo2VerificationFailed
            | SmallOrder
            | Groth16(_)
            | MalformedGroth16(_)
            | Ed25519(_)
            | RedJubjub(_)
            | RedPallas(_)
            | BothVPubsNonZero
            | DisabledAddToSproutPool
            | DisabledAddToOrchardPool
            | NotEnoughFlags
            | NotEnoughIronwoodFlags
            | OrchardHasEnableCrossAddress
            | OrchardProofSize
            | IronwoodProofSize
            | WrongConsensusBranchId
            | MissingConsensusBranchId
            | LockedUntilAfterBlockHeight(_)
            | LockedUntilAfterBlockTime(_) => 100,

            // NU6.2 mempool transactions are invalid under NU6.3 rules, but
            // honest peers can relay them briefly while their chain tips converge.
            WrongConsensusBranchIdNu6_3GracePeriod => 0,

            // TODO: Consider add peer penalty 1 if these are very old
            DuplicateTransparentSpend(_)
            | DuplicateSproutNullifier(_)
            | DuplicateSaplingNullifier(_)
            | DuplicateOrchardNullifier(_)
            | DuplicateIronwoodNullifier(_) => 0,

            // Standardness (policy) rejections must not be punished: non-standard
            // transactions are consensus-valid, and zcashd relays a reject message
            // without a DoS score for them.
            _other => 0,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn boxed_signature_errors_are_preserved() {
        let script_error: BoxError = Box::new(zakura_script::Error::ScriptInvalid);
        assert_eq!(
            TransactionError::from(script_error),
            TransactionError::Script(zakura_script::Error::ScriptInvalid)
        );

        let ed25519_error: BoxError =
            Box::new(zakura_chain::primitives::ed25519::Error::InvalidSignature);
        assert_eq!(
            TransactionError::from(ed25519_error),
            TransactionError::Ed25519(zakura_chain::primitives::ed25519::Error::InvalidSignature)
        );

        let redjubjub_error: BoxError =
            Box::new(zakura_chain::primitives::redjubjub::Error::InvalidSignature);
        assert_eq!(
            TransactionError::from(redjubjub_error),
            TransactionError::RedJubjub(
                zakura_chain::primitives::redjubjub::Error::InvalidSignature
            )
        );

        let redpallas_error: BoxError =
            Box::new(zakura_chain::primitives::reddsa::Error::InvalidSignature);
        assert_eq!(
            TransactionError::from(redpallas_error),
            TransactionError::RedPallas(zakura_chain::primitives::reddsa::Error::InvalidSignature)
        );
    }

    #[test]
    fn verification_errors_have_high_misbehavior_score() {
        for error in [
            TransactionError::Script(zakura_script::Error::ScriptInvalid),
            TransactionError::SaplingVerificationFailed,
            TransactionError::Halo2VerificationFailed,
            TransactionError::Ed25519(zakura_chain::primitives::ed25519::Error::InvalidSignature),
            TransactionError::RedJubjub(
                zakura_chain::primitives::redjubjub::Error::InvalidSignature,
            ),
            TransactionError::RedPallas(zakura_chain::primitives::reddsa::Error::InvalidSignature),
        ] {
            assert_eq!(error.mempool_misbehavior_score(), 100);
        }
    }

    #[test]
    fn duplicate_spend_errors_have_no_misbehavior_score() {
        let orchard_nullifier = orchard::Nullifier::try_from([0; 32])
            .expect("zero is a valid Pallas base-field encoding");

        for error in [
            TransactionError::DuplicateTransparentSpend(transparent::OutPoint {
                hash: [0; 32].into(),
                index: 0,
            }),
            TransactionError::DuplicateSproutNullifier([0; 32].into()),
            TransactionError::DuplicateSaplingNullifier([0; 32].into()),
            TransactionError::DuplicateOrchardNullifier(orchard_nullifier),
            TransactionError::DuplicateIronwoodNullifier(orchard_nullifier),
        ] {
            assert_eq!(error.mempool_misbehavior_score(), 0);
        }
    }
}

#[derive(Error, Clone, Debug, PartialEq, Eq)]
#[allow(missing_docs)]
pub enum BlockError {
    #[error("block contains invalid transactions")]
    Transaction(#[from] TransactionError),

    #[error("block has no transactions")]
    NoTransactions,

    #[error("block has mismatched merkle root")]
    BadMerkleRoot {
        actual: zakura_chain::block::merkle::Root,
        expected: zakura_chain::block::merkle::Root,
    },

    #[error("block contains duplicate transactions")]
    DuplicateTransaction,

    #[error("block {0:?} is already in present in the state {1:?}")]
    AlreadyInChain(zakura_chain::block::Hash, zakura_state::KnownBlock),

    #[error("invalid block {0:?}: missing block height")]
    MissingHeight(zakura_chain::block::Hash),

    #[error("invalid block height {0:?} in {1:?}: greater than the maximum height {2:?}")]
    MaxHeight(
        zakura_chain::block::Height,
        zakura_chain::block::Hash,
        zakura_chain::block::Height,
    ),

    #[error("invalid difficulty threshold in block header {0:?} {1:?}")]
    InvalidDifficulty(zakura_chain::block::Height, zakura_chain::block::Hash),

    #[error("block {0:?} has a difficulty threshold {2:?} that is easier than the {3:?} difficulty limit {4:?}, hash: {1:?}")]
    TargetDifficultyLimit(
        zakura_chain::block::Height,
        zakura_chain::block::Hash,
        zakura_chain::work::difficulty::ExpandedDifficulty,
        zakura_chain::parameters::Network,
        zakura_chain::work::difficulty::ExpandedDifficulty,
    ),

    #[error(
        "block {0:?} on {3:?} has a hash {1:?} that is easier than its difficulty threshold {2:?}"
    )]
    DifficultyFilter(
        zakura_chain::block::Height,
        zakura_chain::block::Hash,
        zakura_chain::work::difficulty::ExpandedDifficulty,
        zakura_chain::parameters::Network,
    ),

    #[error("transaction has wrong consensus branch id for block network upgrade")]
    WrongTransactionConsensusBranchId,

    #[error(
        "block {height:?} {hash:?} has {sigops} legacy transparent signature operations, \
         but the limit is {MAX_BLOCK_SIGOPS}"
    )]
    TooManyTransparentSignatureOperations {
        height: zakura_chain::block::Height,
        hash: zakura_chain::block::Hash,
        sigops: u32,
    },

    #[error("summing miner fees for block {height:?} {hash:?} failed: {source:?}")]
    SummingMinerFees {
        height: zakura_chain::block::Height,
        hash: zakura_chain::block::Hash,
        source: amount::Error,
    },

    #[error("unexpected error occurred: {0}")]
    Other(String),
}

impl From<SubsidyError> for BlockError {
    fn from(err: SubsidyError) -> BlockError {
        BlockError::Transaction(TransactionError::Subsidy(err))
    }
}

impl From<amount::Error> for BlockError {
    fn from(e: amount::Error) -> Self {
        Self::from(SubsidyError::from(e))
    }
}

impl BlockError {
    /// Returns `true` if this is definitely a duplicate request.
    /// Some duplicate requests might not be detected, and therefore return `false`.
    pub fn is_duplicate_request(&self) -> bool {
        matches!(self, BlockError::AlreadyInChain(..))
    }

    /// Returns a suggested misbehaviour score increment for a certain error.
    pub(crate) fn misbehavior_score(&self) -> u32 {
        use BlockError::*;

        match self {
            MissingHeight(_)
            | MaxHeight(_, _, _)
            | InvalidDifficulty(_, _)
            | TargetDifficultyLimit(_, _, _, _, _)
            | DifficultyFilter(_, _, _, _)
            | NoTransactions
            | BadMerkleRoot { .. }
            | WrongTransactionConsensusBranchId
            | TooManyTransparentSignatureOperations { .. } => 100,
            Transaction(err) => err.mempool_misbehavior_score(),
            _other => 0,
        }
    }
}