floresta_chain/pruned_utreexo/
consensus.rs

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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
// SPDX-License-Identifier: MIT OR Apache-2.0

//! A collection of functions that implement the consensus rules for the Bitcoin Network.
//! This module contains functions that are used to verify blocks and transactions, and doesn't
//! assume anything about the chainstate, so it can be used in any context.
//! We use this to avoid code reuse among the different implementations of the chainstate.

extern crate alloc;

use core::ffi::c_uint;

use bitcoin::block::Header as BlockHeader;
use bitcoin::blockdata::Weight;
#[cfg(feature = "bitcoinkernel")]
use bitcoin::consensus::serialize;
use bitcoin::hashes::sha256;
use bitcoin::hashes::Hash;
use bitcoin::merkle_tree;
use bitcoin::script;
use bitcoin::Amount;
use bitcoin::Block;
use bitcoin::CompactTarget;
use bitcoin::Network;
use bitcoin::OutPoint;
use bitcoin::ScriptBuf;
use bitcoin::Target;
use bitcoin::Transaction;
use bitcoin::TxIn;
use bitcoin::Txid;
#[cfg(feature = "bitcoinkernel")]
use bitcoinkernel::PrecomputedTransactionData;
use floresta_common::prelude::*;
use rustreexo::node_hash::BitcoinNodeHash;
use rustreexo::proof::Proof;
use rustreexo::stump::Stump;

use super::chainparams::ChainParams;
use super::error::BlockValidationErrors;
use super::error::BlockchainError;
use super::udata;
use crate::pruned_utreexo::utxo_data::UtxoData;
use crate::TransactionError;

/// The version tag to be prepended to the leafhash. It's just the sha512 hash of the string
/// `UtreexoV1` represented as a vector of [u8] ([85 116 114 101 101 120 111 86 49]).
/// The same tag is "5574726565786f5631" as a hex string.
pub const UTREEXO_TAG_V1: [u8; 64] = [
    0x5b, 0x83, 0x2d, 0xb8, 0xca, 0x26, 0xc2, 0x5b, 0xe1, 0xc5, 0x42, 0xd6, 0xcc, 0xed, 0xdd, 0xa8,
    0xc1, 0x45, 0x61, 0x5c, 0xff, 0x5c, 0x35, 0x72, 0x7f, 0xb3, 0x46, 0x26, 0x10, 0x80, 0x7e, 0x20,
    0xae, 0x53, 0x4d, 0xc3, 0xf6, 0x42, 0x99, 0x19, 0x99, 0x31, 0x77, 0x2e, 0x03, 0x78, 0x7d, 0x18,
    0x15, 0x6e, 0xb3, 0x15, 0x1e, 0x0e, 0xd1, 0xb3, 0x09, 0x8b, 0xdc, 0x84, 0x45, 0x86, 0x18, 0x85,
];

/// The unspendable UTXO on block 91_722 that exists because of the historical
/// [BIP30 violation](https://bips.dev/30/). For Utreexo, this UTXO is not overwritten
/// as we commit the block hash in the leafhash. But since non-Utreexo nodes consider
/// this as unspendable as it's already been overwritten, we also need to make it not spendable.
///
/// Encoded in hex string is 84b3af0783b410b4564c5d1f361868559f7cf77cfc65ce2be951210357022fe3.
pub const UNSPENDABLE_BIP30_UTXO_91722: [u8; 32] = [
    0x84, 0xb3, 0xaf, 0x07, 0x83, 0xb4, 0x10, 0xb4, 0x56, 0x4c, 0x5d, 0x1f, 0x36, 0x18, 0x68, 0x55,
    0x9f, 0x7c, 0xf7, 0x7c, 0xfc, 0x65, 0xce, 0x2b, 0xe9, 0x51, 0x21, 0x03, 0x57, 0x02, 0x2f, 0xe3,
];

/// The unspendable UTXO on block 91_812 that exists because of the historical
/// [BIP30 violation](https://bips.dev/30/). For Utreexo, this UTXO is not overwritten
/// as we commit the block hash in the leafhash. But since non-Utreexo nodes consider
/// this as unspendable as it's already been overwritten, we also need to make it not spendable.
///
/// Encoded in hex string is bc6b4bf7cebbd33a18d6b0fe1f8ecc7aa5403083c39ee343b985d51fd0295ad8.
pub const UNSPENDABLE_BIP30_UTXO_91812: [u8; 32] = [
    0xbc, 0x6b, 0x4b, 0xf7, 0xce, 0xbb, 0xd3, 0x3a, 0x18, 0xd6, 0xb0, 0xfe, 0x1f, 0x8e, 0xcc, 0x7a,
    0xa5, 0x40, 0x30, 0x83, 0xc3, 0x9e, 0xe3, 0x43, 0xb9, 0x85, 0xd5, 0x1f, 0xd0, 0x29, 0x5a, 0xd8,
];

/// This struct contains all the information and methods needed to validate a block,
/// it is used by the [ChainState](crate::ChainState) to validate blocks and transactions.
#[derive(Debug, Clone)]
pub struct Consensus {
    /// The parameters of the chain we are validating, it is usually hardcoded
    /// constants. See [ChainParams] for more information.
    pub parameters: ChainParams,
}

impl From<Network> for Consensus {
    fn from(network: Network) -> Self {
        Consensus {
            parameters: network.into(),
        }
    }
}

impl Consensus {
    /// Returns the amount of block subsidy to be paid in a block, given it's height.
    ///
    /// The Bitcoin Core source can be found [here](https://github.com/bitcoin/bitcoin/blob/2b211b41e36f914b8d0487e698b619039cc3c8e2/src/validation.cpp#L1501-L1512).
    pub fn get_subsidy(&self, height: u32) -> u64 {
        let halvings = height / self.parameters.subsidy_halving_interval as u32;
        // Force block reward to zero when right shift is undefined.
        if halvings >= 64 {
            return 0;
        }
        let mut subsidy = 50 * Amount::ONE_BTC.to_sat();
        // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
        subsidy >>= halvings;
        subsidy
    }

    /// Verify if all transactions in a block are valid. Here we check the following:
    /// - The block must contain at least one transaction, and this transaction must be coinbase
    /// - The first transaction in the block must be coinbase
    /// - The coinbase transaction must have the correct value (subsidy + fees)
    /// - The block must not create more coins than allowed
    /// - All transactions must be valid, as verified by [`Consensus::verify_transaction`]
    #[allow(unused)]
    pub fn verify_block_transactions(
        height: u32,
        mut utxos: HashMap<OutPoint, UtxoData>,
        transactions: &[Transaction],
        subsidy: u64,
        verify_script: bool,
        flags: c_uint,
    ) -> Result<(), BlockchainError> {
        // Blocks must contain at least one transaction (i.e., the coinbase)
        if transactions.is_empty() {
            return Err(BlockValidationErrors::EmptyBlock)?;
        }

        // Total block fees that the miner can claim in the coinbase
        let mut fee = Amount::ZERO;

        for (n, transaction) in transactions.iter().enumerate() {
            if n == 0 {
                if !transaction.is_coinbase() {
                    return Err(BlockValidationErrors::FirstTxIsNotCoinbase)?;
                }
                Self::verify_coinbase(transaction)?;
                // Skip next checks: coinbase input is exempt, coinbase reward checked later
                continue;
            }

            // Actually verify the transaction
            let (in_value, out_value) =
                Self::verify_transaction(transaction, &mut utxos, height, verify_script, flags)?;

            // Fee is the difference between inputs and outputs. In the above function call we have
            // verified that `out_value <= in_value` (no underflow risk).
            fee = fee
                .checked_add(in_value - out_value)
                .ok_or(BlockValidationErrors::TooManyCoins)?;
        }

        // Check coinbase output values to ensure the miner isn't producing excess coins
        let allowed_reward = fee
            .checked_add(Amount::from_sat(subsidy))
            .ok_or(BlockValidationErrors::TooManyCoins)?;

        let coinbase_total = transactions[0]
            .output
            .iter()
            .try_fold(Amount::ZERO, |acc, out| acc.checked_add(out.value))
            .ok_or(BlockValidationErrors::TooManyCoins)?;

        if coinbase_total > allowed_reward {
            return Err(BlockValidationErrors::BadCoinbaseOutValue)?;
        }

        Ok(())
    }

    /// Verifies a single, non-coinbase transaction. To verify (the structure of) a coinbase
    /// transaction, use [`Consensus::verify_coinbase`].
    ///
    /// This function checks that the transaction:
    ///   - Has at least one input and one output
    ///   - Doesn't have null PrevOuts (reserved only for coinbase transactions)
    ///   - Doesn't spend more coins than it claims in the inputs
    ///   - Doesn't "move" more coins than allowed (at most 21 million)
    ///   - Spends mature coins, in case any input refers to a coinbase transaction
    ///   - Has valid scripts (if we don't assume them), and within the allowed size
    pub fn verify_transaction(
        transaction: &Transaction,
        utxos: &mut HashMap<OutPoint, UtxoData>,
        height: u32,
        _verify_script: bool,
        _flags: c_uint,
    ) -> Result<(Amount, Amount), BlockchainError> {
        let txid = || transaction.compute_txid();

        let out_value = Self::check_transaction_context_free(transaction)?;

        let mut in_value = Amount::ZERO;
        for input in &transaction.input {
            // Null PrevOuts already checked in the previous step

            let utxo = Self::get_utxo(input, utxos, txid)?;
            let txout = &utxo.txout;

            // A coinbase output created at height n can only be spent at height >= n + 100
            if utxo.is_coinbase && (height < utxo.creation_height + 100) {
                return Err(tx_err!(txid, CoinbaseNotMatured))?;
            }

            // Check script sizes (spent txo pubkey, inputs are covered already)
            Self::validate_script_size(&txout.script_pubkey, txid)?;

            in_value = in_value
                .checked_add(txout.value)
                .ok_or(BlockValidationErrors::TooManyCoins)?;
        }

        // Sanity check
        if in_value > Amount::MAX_MONEY {
            return Err(BlockValidationErrors::TooManyCoins)?;
        }

        // Value in should be greater or equal to value out. Otherwise, inflation.
        if out_value > in_value {
            return Err(tx_err!(txid, NotEnoughMoney))?;
        }

        // Verify the tx script
        #[cfg(feature = "bitcoinkernel")]
        if _verify_script {
            Self::verify_input_scripts(transaction, utxos, _flags)?;
        };

        Ok((in_value, out_value))
    }

    #[cfg(feature = "bitcoinkernel")]
    fn verify_input_scripts(
        transaction: &Transaction,
        utxos: &mut HashMap<OutPoint, UtxoData>,
        flags: c_uint,
    ) -> Result<(), BlockchainError> {
        let tx = serialize(&transaction);
        let txid = || transaction.compute_txid();

        let tx = bitcoinkernel::Transaction::try_from(tx.as_slice())
            .map_err(|e| tx_err!(txid, ScriptValidationError, e.to_string()))?;

        let mut spent_utxos = Vec::new();
        let mut spent_scripts = Vec::new();

        for input in &transaction.input {
            let spent_output = utxos
                .remove(&input.previous_output)
                .ok_or_else(|| tx_err!(txid, UtxoNotFound, input.previous_output))?
                .txout;

            let value = i64::try_from(spent_output.value.to_sat())
                .map_err(|_| tx_err!(txid, TooManyCoins))?;
            let spk = bitcoinkernel::ScriptPubkey::try_from(spent_output.script_pubkey.as_bytes())
                .map_err(|e| tx_err!(txid, ScriptValidationError, e.to_string()))?;

            spent_utxos.push(bitcoinkernel::TxOut::new(&spk, value));
            spent_scripts.push((spk, value));
        }

        let tx_data = PrecomputedTransactionData::new(&tx, &spent_utxos)
            .map_err(|e| tx_err!(txid, ScriptValidationError, e.to_string()))?;

        for (input_index, (script, amount)) in spent_scripts.iter().enumerate() {
            bitcoinkernel::verify(
                script,
                Some(*amount),
                &tx,
                input_index,
                Some(flags),
                &tx_data,
            )
            .map_err(|e| tx_err!(txid, ScriptValidationError, e.to_string()))?;
        }

        Ok(())
    }

    /// Performs consensus checks that are independent of the spent outputs (non-coinbase only).
    /// Returns the total output value as an [`Amount`].
    pub fn check_transaction_context_free(
        transaction: &Transaction,
    ) -> Result<Amount, BlockchainError> {
        let txid = || transaction.compute_txid();

        if transaction.input.is_empty() {
            return Err(tx_err!(txid, EmptyInputs))?;
        }
        if transaction.output.is_empty() {
            return Err(tx_err!(txid, EmptyOutputs))?;
        }

        for input in &transaction.input {
            // Null PrevOuts are only allowed in coinbase inputs
            if input.previous_output.is_null() {
                return Err(tx_err!(txid, NullPrevOut))?;
            }

            // Check script sizes (current tx scriptsig and TODO witness if present)
            Self::validate_script_size(&input.script_sig, txid)?;
            // TODO check also witness script size
        }

        let out_value = transaction
            .output
            .iter()
            .try_fold(Amount::ZERO, |acc, out| acc.checked_add(out.value))
            .ok_or(BlockValidationErrors::TooManyCoins)?;

        // Sanity check
        if out_value > Amount::MAX_MONEY {
            return Err(BlockValidationErrors::TooManyCoins)?;
        }

        Ok(out_value)
    }

    /// Runs inexpensive, consensus-critical block checks that don't require script execution. If
    /// successful, returns the list of [`Txid`]s computed for the merkle root check.
    ///
    /// This verifies:
    /// - the header merkle root matches the block's txids
    /// - BIP34 coinbase-encoded height once activated (at `bip34_height`)
    /// - if there are SegWit transactions, the witness commitment is present and correct
    /// - total block weight is within the 4,000,000 WU limit
    pub fn check_block(&self, block: &Block, height: u32) -> Result<Vec<Txid>, BlockchainError> {
        let Some(txids) = Self::check_merkle_root(block) else {
            return Err(BlockValidationErrors::BadMerkleRoot)?;
        };

        let bip34_height = self.parameters.params.bip34_height;
        // If bip34 is active, check that the encoded block height is correct
        if height >= bip34_height && Self::get_bip34_height(block) != Some(height) {
            return Err(BlockValidationErrors::BadBip34)?;
        }

        if !block.check_witness_commitment() {
            return Err(BlockValidationErrors::BadWitnessCommitment)?;
        }

        if block.weight() > Weight::MAX_BLOCK {
            return Err(BlockValidationErrors::BlockTooBig)?;
        }

        Ok(txids)
    }

    /// Checks if the merkle root of the header matches the merkle root of the transaction list.
    ///
    /// Unlike [`Block::check_merkle_root`], this function returns the list of computed [`Txid`]s
    /// if the merkle roots matched, or `None` otherwise.
    ///
    /// The merkle root is computed in the same way as [`Block::compute_merkle_root`].
    pub fn check_merkle_root(block: &Block) -> Option<Vec<Txid>> {
        let txids: Vec<_> = block.txdata.iter().map(|obj| obj.compute_txid()).collect();

        // Copy the hashes into an iterator, as `calculate_root` requires ownership
        let hashes_iter = txids.iter().copied().map(|txid| txid.to_raw_hash());

        let calculated = merkle_tree::calculate_root(hashes_iter).map(|h| h.into());
        match calculated {
            Some(merkle_root) if block.header.merkle_root == merkle_root => Some(txids),
            _ => None,
        }
    }

    /// Returns the TxOut being spent by the given input.
    ///
    /// Fails if the UTXO is not present in the given hashmap.
    fn get_utxo<'a, F: Fn() -> Txid>(
        input: &TxIn,
        utxos: &'a HashMap<OutPoint, UtxoData>,
        txid: F,
    ) -> Result<&'a UtxoData, TransactionError> {
        match utxos.get(&input.previous_output) {
            Some(utxo) => Ok(utxo),
            // This is the case when the spender:
            // - Spends an UTXO that doesn't exist
            // - Spends an UTXO that was already spent
            None => Err(tx_err!(txid, UtxoNotFound, input.previous_output)),
        }
    }

    #[allow(unused)]
    fn validate_locktime(
        input: &TxIn,
        transaction: &Transaction,
        height: u32,
    ) -> Result<(), BlockValidationErrors> {
        unimplemented!("validate_locktime")
    }

    /// Validates the script size and the number of sigops in a scriptpubkey or scriptsig.
    fn validate_script_size<F: Fn() -> Txid>(
        script: &ScriptBuf,
        txid: F,
    ) -> Result<(), TransactionError> {
        // The maximum script size for non-taproot spends is 10,000 bytes
        // https://github.com/bitcoin/bitcoin/blob/v28.0/src/script/script.h#L39
        if script.len() > 10_000 {
            return Err(tx_err!(txid, ScriptError));
        }
        if script.count_sigops() > 80_000 {
            return Err(tx_err!(txid, ScriptError));
        }
        Ok(())
    }

    /// Validates the coinbase transaction's input. The checks on the outputs require context about
    /// the block and are performed by [`Consensus::verify_block_transactions`].
    pub fn verify_coinbase(tx: &Transaction) -> Result<(), TransactionError> {
        let txid = || tx.compute_txid();
        let input = match tx.input.as_slice() {
            [i] => i,
            _ => return Err(tx_err!(txid, InvalidCoinbase, "Coinbase must have 1 input")),
        };

        // The PrevOut of the coinbase input must be null
        if !input.previous_output.is_null() {
            return Err(tx_err!(txid, InvalidCoinbase, "Invalid Coinbase PrevOut"));
        }

        // The scriptsig size must be between 2 and 100 bytes
        // https://github.com/bitcoin/bitcoin/blob/v28.0/src/consensus/tx_check.cpp#L49
        let size = input.script_sig.len();
        if !(2..=100).contains(&size) {
            return Err(tx_err!(txid, InvalidCoinbase, "Invalid ScriptSig size"));
        }

        Ok(())
    }

    // TODO remove this once https://github.com/rust-bitcoin/rust-bitcoin/pull/3585 makes it into a
    // rust-bitcoin stable release (i.e., 0.33).
    pub fn get_bip34_height(block: &Block) -> Option<u32> {
        let cb = block.coinbase()?;
        let input = cb.input.first()?;
        let push = input.script_sig.instructions_minimal().next()?;

        match push {
            Ok(script::Instruction::PushBytes(b)) => {
                let h = script::read_scriptint(b.as_bytes()).ok()?;
                Some(h as u32)
            }

            Ok(script::Instruction::Op(opcode)) => {
                let opcode = opcode.to_u8();
                if (0x51..=0x60).contains(&opcode) {
                    Some(opcode as u32 - 0x50)
                } else {
                    None
                }
            }

            _ => None,
        }
    }

    /// Checks if a testnet4 block is compliant with the anti-timewarp rules of BIP94.
    ///
    /// a. The block's nTime field MUST be greater than or equal to the nTime
    /// field of the immediately prior block minus 600 seconds
    pub fn check_bip94_time(
        block: &BlockHeader,
        prev_block: &BlockHeader,
    ) -> Result<(), BlockValidationErrors> {
        if block.time < (prev_block.time - 600) {
            return Err(BlockValidationErrors::BIP94TimeWarp);
        }

        Ok(())
    }

    /// Calculates the next target for the proof of work algorithm, given the
    /// first and last block headers inside a difficulty adjustment period.
    pub fn calc_next_work_required(
        last_block: &BlockHeader,
        first_block: &BlockHeader,
        params: ChainParams,
    ) -> Target {
        let actual_timespan = last_block.time - first_block.time;
        // from bip 94:
        //  a. The base difficulty value MUST be taken from the first block of the previous
        //     difficulty period
        //
        //  b. NOT from the last block as in previous implementations
        let bits = match params.enforce_bip94 {
            true => first_block.bits,
            false => last_block.bits,
        };

        CompactTarget::from_next_work_required(bits, actual_timespan as u64, params).into()
    }

    /// Updates our accumulator with the new block. This is done by calculating the new
    /// root hash of the accumulator, and then verifying the proof of inclusion of the
    /// deleted nodes. If the proof is valid, we return the new accumulator. Otherwise,
    /// we return an error.
    /// This function is pure, it doesn't modify the accumulator, but returns a new one.
    pub fn update_acc(
        acc: &Stump,
        block: &Block,
        height: u32,
        proof: Proof,
        del_hashes: Vec<sha256::Hash>,
    ) -> Result<Stump, BlockchainError> {
        let block_hash = block.block_hash();

        // Check if there is a spend of an unspendable UTXO (BIP30)
        if Self::contains_unspendable_utxo(&del_hashes) {
            return Err(BlockValidationErrors::UnspendableUTXO)?;
        }

        // Convert to BitcoinNodeHash, from rustreexo
        let del_hashes: Vec<_> = del_hashes
            .into_iter()
            .map(|hash| BitcoinNodeHash::Some(hash.to_byte_array()))
            .collect();

        let adds = udata::proof_util::get_block_adds(block, height, block_hash);

        // Update the accumulator
        let acc = acc.modify(&adds, &del_hashes, &proof)?.0;
        Ok(acc)
    }

    fn contains_unspendable_utxo(del_hashes: &[sha256::Hash]) -> bool {
        del_hashes.iter().any(|hash| {
            let bytes = hash.as_ref();
            bytes == UNSPENDABLE_BIP30_UTXO_91722 || bytes == UNSPENDABLE_BIP30_UTXO_91812
        })
    }
}

#[cfg(test)]
mod tests {
    use std::fs::File;

    use bitcoin::absolute::LockTime;
    use bitcoin::consensus::deserialize;
    use bitcoin::consensus::encode::deserialize_hex;
    use bitcoin::constants::genesis_block;
    use bitcoin::hashes::Hash;
    use bitcoin::opcodes::all::OP_NOP;
    use bitcoin::opcodes::OP_TRUE;
    use bitcoin::transaction::Version;
    use bitcoin::Amount;
    use bitcoin::Network;
    use bitcoin::OutPoint;
    use bitcoin::ScriptBuf;
    use bitcoin::Sequence;
    use bitcoin::Transaction;
    use bitcoin::TxIn;
    use bitcoin::TxOut;
    use bitcoin::Txid;
    use bitcoin::Witness;
    use floresta_common::assert_err;
    use floresta_common::assert_ok;
    use rand::rngs::StdRng;
    use rand::seq::SliceRandom;
    use rand::SeedableRng;

    use super::*;

    /// Macro for creating a TxOut
    macro_rules! txout {
        ($sats:expr, $script:expr) => {
            TxOut {
                value: Amount::from_sat($sats),
                script_pubkey: $script,
            }
        };
    }

    /// Macro for constructing a legacy [`TxIn`] with optional scriptSig and sequence number.
    /// Needs the outpoint and, if not provided, defaults to empty scriptSig and `Sequence::MAX`.
    macro_rules! txin {
        ($outpoint:expr) => {
            TxIn {
                previous_output: $outpoint,
                script_sig: ScriptBuf::new(),
                sequence: Sequence::MAX,
                witness: Witness::new(),
            }
        };
        ($outpoint:expr, $script:expr) => {
            TxIn {
                previous_output: $outpoint,
                script_sig: $script,
                sequence: Sequence::MAX,
                witness: Witness::new(),
            }
        };
        ($outpoint:expr, $script:expr, $sequence:expr) => {
            TxIn {
                previous_output: $outpoint,
                script_sig: $script,
                sequence: $sequence,
                witness: Witness::new(),
            }
        };
    }

    /// Helper for building a zero-locktime transaction given the input and output list.
    fn build_tx(input: Vec<TxIn>, output: Vec<TxOut>) -> Transaction {
        Transaction {
            version: Version::TWO,
            lock_time: LockTime::ZERO,
            input,
            output,
        }
    }

    /// Helper to avoid boilerplate in test cases. Note this is not a null outpoint, restricted to
    /// coinbase transactions only, as that requires the vout to be `u32::MAX`.
    fn dummy_outpoint() -> OutPoint {
        OutPoint {
            txid: Txid::all_zeros(),
            vout: 0,
        }
    }

    #[cfg(feature = "bitcoinkernel")]
    /// Some made up transactions that test our script limits checks.
    /// Here's what is wrong with each transaction:
    ///     - tx1: Too many ops (512, should be <= 201)
    ///     - tx2: It's ok, just huge
    ///     - tx3: Script push too big (520, should be <= 520)
    ///     - tx4: Script sig is too big
    ///     - tx5: Also Ok, but a big script on p2sh
    ///     - tx6: Too many sig ops (201, should be <= 201)
    ///     - tx7: Executed OPs limit exceeded
    const TX_VALIDATION_CASES_LEGACY: &[&str] = &[
        "0200000001fdaf053eeaeed2e96594b542792417c6c223fa8571e88d31e296b1a655c81eb500000000fd0306012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901294d000275757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575750000000001260200000000000017a9144e0c22952fa87a99064f93f77a74fb2e0184f04d8700000000:260200000000000017a9144e0c22952fa87a99064f93f77a74fb2e0184f04d87",
        "02000000013b4568b6d740e1625710ec49e6ce994e79ad55d7d1eef03cd945d5667229c05200000000fdcb04012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901294cc97575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575750000000001260200000000000017a91436f39a404b67ec67516b353b30c3766b33609dec8700000000:260200000000000017a91436f39a404b67ec67516b353b30c3766b33609dec87",
        "02000000010f5f070f769b7d6290882dfd8659150e781f4ea7f19c2f5d93a9917aebd7d54500000000fd970501290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901294d0004757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575750000000001260200000000000017a914dba622860b2edd8be5861f0cb204248f6a9f0b9d8700000000:260200000000000017a914dba622860b2edd8be5861f0cb204248f6a9f0b9d87",
        "0200000001540b20c497074bcb8c83869601566749f210ce7965f4e55ec1be9a8f648d743800000000fd9a0801290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901294cc875757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575757575750000000001260200000000000017a9141ea5312cab0ad9a531c35b9051dc136bebc0669e8700000000:260200000000000017a9141ea5312cab0ad9a531c35b9051dc136bebc0669e87",
        "02000000019ebe6327436c18f978611d3fae6c2f6834cd6fbc08471134bc4bee16f8b9062400000000fdec03012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901294cc86d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d0000000001260200000000000017a914a73ee4302bb9a6e5b7c42cae84b7c548638bc0148700000000:260200000000000017a914a73ee4302bb9a6e5b7c42cae84b7c548638bc01487",
        "0200000001cbbe326a4360ed38487a6fd1a091da0c22fd5084127401c3fba1ad52b8a37f3300000000fdec03012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901290129012901294cc8acacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacac0000000001260200000000000017a914436c244dc646042e3bafb50ff5729a0e80153e708700000000:260200000000000017a914436c244dc646042e3bafb50ff5729a0e80153e7087",
        "020000000139cf57739cb5d08335b7ed529792de34987d763d4856957dcc4b258c9cb1d0d300000000d601ff4cd276767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767600000000012602000000000000160014ef814b32b68a6138974b1144603b5c10569eeef600000000:2602000000000000160014ef814b32b68a6138974b1144603b5c10569eeef6",
    ];

    fn coinbase(is_valid: bool) -> Transaction {
        // This coinbase transaction was retrieved from https://learnmeabitcoin.com/explorer/block/0000000000000a0f82f8be9ec24ebfca3d5373fde8dc4d9b9a949d538e9ff679

        // Create input
        let script_sig = if is_valid {
            ScriptBuf::from_hex("03f0a2a4d9f0a2").unwrap()
        } else {
            // This must invalidate the coinbase transaction since it's a big script.
            ScriptBuf::from_hex(&format!("{:0>420}", "")).unwrap()
        };
        let input = txin!(OutPoint::null(), script_sig);

        // Create outputs
        let output_script = ScriptBuf::from_hex("41047eda6bd04fb27cab6e7c28c99b94977f073e912f25d1ff7165d9c95cd9bbe6da7e7ad7f2acb09e0ced91705f7616af53bee51a238b7dc527f2be0aa60469d140ac").unwrap();
        let output = txout!(5_000_350_000, output_script);

        Transaction {
            version: Version::ONE,
            lock_time: LockTime::from_height(150_007).unwrap(),
            input: vec![input],
            output: vec![output],
        }
    }

    /// Modifies a block to have a different output script (txdata is tampered with).
    fn mutate_block(block: &mut Block) {
        let mut rng = StdRng::seed_from_u64(0x_bebe_cafe);

        let tx = block.txdata.choose_mut(&mut rng).unwrap();
        let out = tx.output.choose_mut(&mut rng).unwrap();
        let spk = out.script_pubkey.as_mut_bytes();
        // Random byte from a random scriptPubKey
        let byte = spk.choose_mut(&mut rng).unwrap();

        *byte += 1;
    }

    /// Test helper to update the witness commitment in a block, assuming txdata was modified.
    /// This ensures `block` is not considered mutated, so we can exercise other error cases.
    fn update_witness_commitment(block: &mut Block) -> Option<()> {
        // BIP141 witness-commitment prefix, where the full commitment data is:
        //  1-byte - OP_RETURN (0x6a)
        //  1-byte - Push the following 36 bytes (0x24)
        //  4-byte - Commitment header (0xaa21a9ed)
        // 32-byte - Commitment hash: Double-SHA256(witness root hash|witness reserved value)
        const MAGIC: [u8; 6] = [0x6a, 0x24, 0xaa, 0x21, 0xa9, 0xed];

        let coinbase = &block.txdata[0];

        // Commitment is in the last coinbase output that starts with magic bytes.
        let pos = coinbase.output.iter().rposition(|out| {
            let spk = out.script_pubkey.as_bytes();
            spk.len() >= 38 && spk[0..6] == MAGIC
        })?;

        // Witness reserved value is in coinbase input witness.
        let witness_rv: &[u8; 32] = {
            let mut it = coinbase.input[0].witness.iter();
            match (it.next(), it.next()) {
                (Some(rv), None) => rv.try_into().ok()?,
                _ => return None,
            }
        };

        let root = block.witness_root()?;
        let c = *Block::compute_witness_commitment(&root, witness_rv).as_byte_array();

        block.txdata[0].output[pos].script_pubkey.as_mut_bytes()[6..38].copy_from_slice(&c);
        Some(())
    }

    /// Decode and deserialize a zstd-compressed block in the given file path.
    fn decode_block(file_path: &str) -> Block {
        let block_file = File::open(file_path).unwrap();
        let block_bytes = zstd::decode_all(block_file).unwrap();
        deserialize(&block_bytes).unwrap()
    }

    #[test]
    fn test_check_merkle_root() {
        let blocks = [
            genesis_block(Network::Bitcoin),
            genesis_block(Network::Testnet),
            genesis_block(Network::Testnet4),
            genesis_block(Network::Signet),
            genesis_block(Network::Regtest),
            decode_block("./testdata/block_866342/raw.zst"),
            decode_block("./testdata/block_367891/raw.zst"),
        ];

        for mut block in blocks {
            assert!(block.check_merkle_root());
            let txids = Consensus::check_merkle_root(&block).expect("merkle roots match");

            // Sanity check: the returned txids are the correct ones
            for (txid, tx) in txids.into_iter().zip(&block.txdata) {
                assert_eq!(txid, tx.compute_txid());
            }

            // Modifying the txdata should invalidate the block
            mutate_block(&mut block);

            assert!(!block.check_merkle_root());
            if Consensus::check_merkle_root(&block).is_some() {
                panic!("merkle roots shouldn't match");
            }
        }
    }

    /// Modifies historical block at height 866,342 by adding one extra transaction so that the
    /// updated block weight is 4,000,001 WUs. The block merkle roots are updated accordingly.
    fn build_oversized_866_342() -> Block {
        let mut block = decode_block("./testdata/block_866342/raw.zst");

        let consensus = Consensus::from(Network::Bitcoin);
        consensus.check_block(&block, 866_342).expect("valid block");

        // This block is close but below to the max weight
        assert_eq!(block.weight().to_wu(), 3_993_209);

        // Modify the block by adding one transaction that makes it exceed the weight limit
        let mut script_out = ScriptBuf::default();
        for _ in 0..1_636 {
            script_out.push_opcode(OP_NOP);
        }
        let out = txout!(1, script_out);
        let tx = build_tx(vec![txin!(dummy_outpoint())], vec![out]);

        block.txdata.insert(1, tx);

        // Update the witness commitment, and then the merkle root, which depends on the former
        update_witness_commitment(&mut block).expect("should be able to update");
        block.header.merkle_root = block.compute_merkle_root().unwrap();

        block
    }

    #[test]
    fn test_block_too_big() {
        let height = 866_342;
        let consensus = Consensus::from(Network::Bitcoin);
        let block = build_oversized_866_342();

        // This block is now just over the weight limit, by one unit!
        assert_eq!(block.weight().to_wu(), 4_000_001);
        assert!(block.weight() > Weight::MAX_BLOCK);
        assert_eq!(Weight::MAX_BLOCK.to_wu(), 4_000_000);

        // The txdata commitments match
        assert!(block.check_merkle_root());
        assert!(block.check_witness_commitment());
        Consensus::check_merkle_root(&block).expect("merkle root matches");

        match consensus.check_block(&block, height) {
            Err(BlockchainError::BlockValidation(BlockValidationErrors::BlockTooBig)) => (),
            other => panic!("We should have `BlockValidationErrors::BlockTooBig`, got {other:?}"),
        }
    }

    #[test]
    fn test_validate_script_size() {
        use bitcoin::hashes::Hash;
        let dummy_txid = Txid::all_zeros;

        // Generate a script larger than 10,000 bytes (e.g., 10,001 bytes)
        let large_script = ScriptBuf::from_hex(&format!("{:0>20002}", "")).unwrap();
        assert_eq!(large_script.len(), 10_001);

        let small_script =
            ScriptBuf::from_hex("76a9149206a30c09cc853bb03bd917a4f9f29b089c1bc788ac").unwrap();

        assert_ok!(Consensus::validate_script_size(&small_script, dummy_txid));
        assert_err!(Consensus::validate_script_size(&large_script, dummy_txid));
    }

    #[test]
    fn test_validate_coinbase() {
        let valid_one = coinbase(true);
        let invalid_one = coinbase(false);
        // The case that should be valid
        assert_ok!(Consensus::verify_coinbase(&valid_one));
        // Invalid coinbase script
        assert_eq!(
            Consensus::verify_coinbase(&invalid_one)
                .unwrap_err()
                .error
                .to_string(),
            "Invalid coinbase: \"Invalid ScriptSig size\""
        );
    }

    #[test]
    fn test_coinbase_maturity() {
        // Helper function to test coinbase spending
        // Requires the coinbase tx to have the relevant output at vout=0, and be spent at vin=0
        fn test_case(
            coinbase_tx: &Transaction,
            spending_tx: &Transaction,
            expected_coinbase: &str,
            expected_spending: &str,
            heights: (u32, u32),
            expected_ok: bool,
        ) {
            let (creation_height, spending_height) = heights;

            assert_eq!(coinbase_tx.compute_txid().to_string(), expected_coinbase);
            assert_eq!(spending_tx.compute_txid().to_string(), expected_spending);
            assert_ok!(Consensus::verify_coinbase(coinbase_tx));

            let mut utxos = HashMap::new();
            utxos.insert(
                spending_tx.input[0].previous_output,
                UtxoData {
                    txout: coinbase_tx.output[0].clone(),
                    is_coinbase: true,
                    creation_height,
                    creation_time: 0, // Use a dummy time
                },
            );

            let spend_result =
                Consensus::verify_transaction(spending_tx, &mut utxos, spending_height, true, 0);

            if expected_ok {
                assert_ok!(spend_result);
            } else {
                match spend_result.unwrap_err() {
                    BlockchainError::TransactionError(inner) => {
                        let txid = || spending_tx.compute_txid();
                        assert_eq!(inner, tx_err!(txid, CoinbaseNotMatured));
                    }
                    e => panic!("Expected a TransactionError, but got: {e:?}"),
                }
            }
        }

        // The first ever coinbase coins to be spent 101 blocks later are from this coinbase P2PK
        // output (bd4d7b0bf9341e575ab7f17b3e3187b70635fd2b99e0dc24d4c3f55e9e358115:0)
        let coinbase_74_547 = deserialize_hex("01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff080418ba001c02c205ffffffff0100f2052a010000004341040e6d9c4cea77c12fab14f4ef5a7713ed50a5c847e4060ae513ea672427babf878ee2b88a0f515157b39b706b1c799cdc42edac2554b205a6e61bf4bcc8ca595aac00000000").unwrap();
        let spending_tx = deserialize_hex("01000000011581359e5ef5c3d424dce0992bfd3506b787313e7bf1b75a571e34f90b7b4dbd0000000049483045022100a0bba3f5731b0d89af8a4fa9f20ccdd89a0758b9eee909db1f8a3eb55d8c907c02201e52ff6abc5c88c09f48dcd40a44beb25f6715aac01ab1e3b9b3e12b2509ab4c01ffffffff0100f2052a010000001976a914ee3a639d407116b0debb484f0335144d794f57e188ac00000000").unwrap();

        test_case(
            &coinbase_74_547,
            &spending_tx,
            // The expected txids
            "bd4d7b0bf9341e575ab7f17b3e3187b70635fd2b99e0dc24d4c3f55e9e358115",
            "315b8651901195deed71f830cb37f33b23eab9c524bd2f2cca32d5b7273a3528",
            // Creation and spending heights
            (74_547, 74_648),
            true,
        );

        // This is the 11th time a coinbase output was spent just 100 blocks later (the very first
        // case ever was 223ccdd55e625d4a82d616d3fbdcded0c47f237360098334430242c2262ac6ee:4)
        let coinbase_232_709 = deserialize_hex("01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff2703058d03062f503253482f04a9357651086007873a080000020d3430363638332f736c7573682f0000000001cbef8f96000000001976a914e285a29e0704004d4e95dbb7c57a98563d9fb2eb88ac00000000").unwrap();
        let spending_tx = deserialize_hex("01000000014c901737cca754ad3d0c96fb3e8523d8b00380babf3c20d35779316392b40767000000006a473044022026f8b003ce423ba36fd95f48d3bf297dfb37cd5533a635b76a1f47c76c30e99402205113058dfc25f821905d4ba26a05e870722fb0877e1406605a857f1d71ea13f5012102c37e0f2966c6f154fd43dc45fc3b5fcfdd2d85ed3c95961d6d07a60409e6e4c1ffffffff02cbf68c01000000001976a9145c0727387071c75451b500aacd7077744d6dfbea88ac80626a94000000001976a914e1c9b052561cf0a1da9ee3175df7d5a2d7ff7dd488ac00000000").unwrap();

        test_case(
            &coinbase_232_709,
            &spending_tx,
            "6707b49263317957d3203cbfba8003b0d823853efb960c3dad54a7cc3717904c",
            "0a5672eecf25f809d11053d7dc9098d8db3c98387d51052b499a4c79eef41b61",
            (232_709, 232_809), // Spent just at block n + 100
            true,
        );

        // These coins couldn't be spent at the previous block (not matured)
        test_case(
            &coinbase_232_709,
            &spending_tx,
            "6707b49263317957d3203cbfba8003b0d823853efb960c3dad54a7cc3717904c",
            "0a5672eecf25f809d11053d7dc9098d8db3c98387d51052b499a4c79eef41b61",
            (232_709, 232_808), // Spent at block n + 99
            false,
        );
    }

    #[test]
    #[cfg(feature = "bitcoinkernel")]
    fn test_consume_utxos() {
        // Transaction extracted from https://learnmeabitcoin.com/explorer/tx/0094492b6f010a5e39c2aacc97396ce9b6082dc733a7b4151ccdbd580f789278
        // Mock data for testing

        let mut utxos = HashMap::new();
        let tx: Transaction = deserialize_hex("0100000001bd597773d03dcf6e22ba832f2387152c9ab69d250a8d86792bdfeb690764af5b010000006c493046022100841d4f503f44dd6cef8781270e7260db73d0e3c26c4f1eea61d008760000b01e022100bc2675b8598773984bcf0bb1a7cad054c649e8a34cb522a118b072a453de1bf6012102de023224486b81d3761edcd32cedda7cbb30a4263e666c87607883197c914022ffffffff021ee16700000000001976a9144883bb595608dcfe882aea5f7c579ef107a4fb5b88ac52a0aa00000000001976a914782231de72adb5c9df7367ab0c21c7b44bbd743188ac00000000").unwrap();
        let txid = || tx.compute_txid();

        assert_eq!(tx.input.len(), 1, "We only spend one utxo in this tx");
        let outpoint = tx.input[0].previous_output;

        let output_script =
            ScriptBuf::from_hex("76a9149206a30c09cc853bb03bd917a4f9f29b089c1bc788ac").unwrap();

        utxos.insert(
            outpoint,
            UtxoData {
                txout: txout!(18000000, output_script),
                is_coinbase: false,
                creation_height: 0,
                creation_time: 0,
            },
        );
        let mut utxos_clone = utxos.clone();

        // Test consuming UTXOs with both high and low-level functions
        let flags = bitcoinkernel::VERIFY_P2SH;
        Consensus::verify_transaction(&tx, &mut utxos, 0, true, flags)
            .expect("Transaction should be valid");
        Consensus::verify_input_scripts(&tx, &mut utxos_clone, flags)
            .expect("Transaction should be valid");

        // Check that the UTXO was consumed
        assert!(utxos.is_empty(), "UTXO should be consumed");
        assert!(utxos_clone.is_empty(), "UTXO should be consumed");

        // Trying to verify again with an empty UTXO map must fail with this error
        let expected = tx_err!(txid, UtxoNotFound, outpoint);

        match Consensus::verify_transaction(&tx, &mut utxos, 0, true, flags) {
            Err(BlockchainError::TransactionError(e)) => assert_eq!(e, expected),
            other => panic!("Expected TransactionError, got: {other:?}"),
        }
        match Consensus::verify_input_scripts(&tx, &mut utxos_clone, flags) {
            Err(BlockchainError::TransactionError(e)) => assert_eq!(e, expected),
            other => panic!("Expected TransactionError, got: {other:?}"),
        }
    }

    #[test]
    fn test_output_value_overflow() {
        let ins = vec![txin!(dummy_outpoint())];
        let outs = vec![
            txout!(u64::MAX, ScriptBuf::new()),
            txout!(1, ScriptBuf::new()),
        ];
        let tx = build_tx(ins, outs);

        match Consensus::check_transaction_context_free(&tx) {
            Err(BlockchainError::BlockValidation(BlockValidationErrors::TooManyCoins)) => (),
            other => panic!("Expected TooManyCoins, got: {other:?}"),
        }
    }

    #[test]
    fn test_input_value_above_max_money() {
        let outpoint = dummy_outpoint();

        let excess_money = (Amount::MAX_MONEY + Amount::ONE_SAT).to_sat();
        assert_eq!(excess_money, 100_000_000 * 21_000_000 + 1); // sanity check

        let mut utxos = HashMap::new();
        utxos.insert(
            outpoint,
            UtxoData {
                txout: txout!(excess_money, ScriptBuf::new()),
                is_coinbase: false,
                creation_height: 0,
                creation_time: 0,
            },
        );

        let tx = build_tx(vec![txin!(outpoint)], vec![txout!(1, ScriptBuf::new())]);

        match Consensus::verify_transaction(&tx, &mut utxos, 0, false, 0) {
            Err(BlockchainError::BlockValidation(BlockValidationErrors::TooManyCoins)) => (),
            other => panic!("Expected TooManyCoins, got: {other:?}"),
        }
    }

    // Test cases for Bitcoin script limits in the format <spending_tx>:<prevout>.
    #[cfg(feature = "bitcoinkernel")]
    fn create_case(case: &str) -> (Transaction, HashMap<OutPoint, UtxoData>) {
        let Some((spending, prevout)) = case.split_once(':') else {
            panic!("Invalid case: {case}");
        };

        let spending_tx: Transaction = deserialize_hex(spending).unwrap();
        let txout: TxOut = deserialize_hex(prevout).unwrap();

        let mut utxos = HashMap::new();
        utxos.insert(
            spending_tx.input[0].previous_output,
            UtxoData {
                txout,
                is_coinbase: false,
                creation_height: 0,
                creation_time: 0,
            },
        );

        (spending_tx, utxos)
    }

    #[cfg(feature = "bitcoinkernel")]
    #[test]
    fn test_transaction_validation_legacy() {
        let expected = [false, true, false, false, true, false, false];
        let mut valid = expected.into_iter();

        for case in TX_VALIDATION_CASES_LEGACY.iter() {
            let (transaction, mut utxos) = create_case(case);
            let dummy_height = 0;

            let result = Consensus::verify_transaction(
                &transaction,
                &mut utxos,
                dummy_height,
                true,
                bitcoinkernel::VERIFY_ALL_PRE_TAPROOT,
            );

            let expected = valid.next().unwrap();
            assert_eq!(result.is_ok(), expected, "{case} {result:?}");
        }
    }

    pub fn true_script() -> ScriptBuf {
        let mut script = ScriptBuf::default();
        script.push_opcode(OP_TRUE);
        script
    }

    pub fn oversized_script() -> ScriptBuf {
        let mut script = ScriptBuf::default();
        for _ in 0..10_000 {
            script.push_opcode(OP_NOP);
        }
        script.push_opcode(OP_TRUE);
        script
    }

    #[test]
    // Bitcoin Consensus rules dictate that a scriptPubKey that's more than 10_000 bytes long
    // won't be spendable. However, such an output **can** be created. We only check those
    // sizes when it gets spent.
    //
    // This test creates an over-sized script, make sure that transaction containing it is valid.
    // Then we try to spend this output, and verify if this causes an error.
    fn test_spending_script_too_big() {
        let outpoint = dummy_outpoint();
        let flags = 0;
        let dummy_height = 0;

        let mut utxos = HashMap::new();
        utxos.insert(
            outpoint,
            UtxoData {
                txout: txout!(0, true_script()),
                is_coinbase: false,
                creation_height: 0,
                creation_time: 0,
            },
        );

        // 1. Build a valid transaction that produces an oversized, unspendable output.
        let dummy_in = txin!(outpoint);
        let oversized_out = txout!(0, oversized_script());
        let tx_with_oversized = build_tx(vec![dummy_in], vec![oversized_out.clone()]);

        Consensus::verify_transaction(&tx_with_oversized, &mut utxos, dummy_height, false, flags)
            .unwrap();

        // 2. Register the oversized output as an available UTXO.
        let prevout = OutPoint::new(tx_with_oversized.compute_txid(), 0);
        utxos.insert(
            prevout,
            UtxoData {
                txout: oversized_out,
                is_coinbase: false,
                creation_height: 0,
                creation_time: 0,
            },
        );

        // 3. Attempt to spend the oversized output.
        let spending_in = txin!(prevout);
        let spending_tx = build_tx(vec![spending_in], vec![txout!(0, true_script())]);
        let err =
            Consensus::verify_transaction(&spending_tx, &mut utxos, dummy_height, false, flags)
                .unwrap_err();

        // Check that the error is exactly what we expect.
        match err {
            BlockchainError::TransactionError(inner) => {
                assert_eq!(inner, tx_err!(|| spending_tx.compute_txid(), ScriptError));
            }
            e => panic!("Expected a TransactionError, but got: {e:?}"),
        }
    }
}