neptune-consensus 0.14.0

Consensus logic and proof abstractions for Neptune Cash.
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
use std::collections::HashSet;
use std::sync::OnceLock;

use get_size2::GetSize;
use itertools::Itertools;
use neptune_mutator_set::addition_record::AdditionRecord;
use neptune_mutator_set::mutator_set_accumulator::MutatorSetAccumulator;
use neptune_mutator_set::removal_record::removal_record_list::RemovalRecordListUnpackError;
use neptune_mutator_set::removal_record::RemovalRecord;
use neptune_primitives::mast_hash::HasDiscriminant;
use neptune_primitives::mast_hash::MastHash;
use neptune_primitives::timestamp::Timestamp;
use num_traits::Zero;
use serde::Deserialize;
use serde::Serialize;
use strum::EnumCount;
use strum::VariantArray;
use tasm_lib::structure::tasm_object::TasmObject;
use tasm_lib::twenty_first::math::b_field_element::BFieldElement;
use tasm_lib::twenty_first::math::bfield_codec::BFieldCodec;
use tasm_lib::twenty_first::tip5::digest::Digest;

use super::announcement::Announcement;
use crate::transaction::transparent_input::TransparentInput;
use crate::type_scripts::native_currency_amount::NativeCurrencyAmount;

pub(crate) const LUSTRATION_FLAG: BFieldElement = BFieldElement::new(51022176260u64);

/// TransactionKernel is immutable and its hash never changes.
///
/// See [`TransactionKernelModifier`] for generating modified copies.
#[readonly::make]
#[derive(Debug, Clone, Serialize, Deserialize, GetSize, BFieldCodec, TasmObject)]
pub struct TransactionKernel {
    // note: see field descriptions in [`TransactionKernelProxy`]
    pub inputs: Vec<RemovalRecord>,
    pub outputs: Vec<AdditionRecord>,
    pub announcements: Vec<Announcement>,
    pub fee: NativeCurrencyAmount,
    pub coinbase: Option<NativeCurrencyAmount>,
    pub timestamp: Timestamp,
    pub mutator_set_hash: Digest,

    /// Indicates whether the transaction is the result of some merger.
    pub merge_bit: bool,

    // this is only here as a cache for MastHash
    // so that we lazily compute the input sequences at most once.
    #[serde(skip)]
    #[bfield_codec(ignore)]
    #[tasm_object(ignore)]
    #[get_size(ignore)]
    mast_sequences: OnceLock<Vec<Vec<BFieldElement>>>,
}

impl std::fmt::Display for TransactionKernel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "
kernel hash: {mast_hash}
inputs: {inputs}
outputs: {outputs}
announcements: {announcements}
coinbase: {coinbase}
timestamp: {timestamp}
mutator_set_hash: {ms_hash}
merge_bit: {merge_bit}
",
            mast_hash = self.mast_hash().to_hex(),
            inputs = self.inputs.len(),
            outputs = self.outputs.len(),
            announcements = self.announcements.len(),
            coinbase = self
                .coinbase
                .unwrap_or_else(|| NativeCurrencyAmount::coins(0)),
            timestamp = self.timestamp,
            ms_hash = self.mutator_set_hash.to_hex(),
            merge_bit = self.merge_bit,
        )
    }
}

// we impl PartialEq manually in order to skip mast_sequences field.
// This could also be achieved with the `derivative` crate that has a
// PartialEq that can skip fields, but this way we avoid an extra dep.
impl PartialEq for TransactionKernel {
    fn eq(&self, o: &Self) -> bool {
        self.inputs == o.inputs
            && self.outputs == o.outputs
            && self.announcements == o.announcements
            && self.fee == o.fee
            && self.coinbase == o.coinbase
            && self.timestamp == o.timestamp
            && self.mutator_set_hash == o.mutator_set_hash
            && self.merge_bit == o.merge_bit

        // mast_sequences intentionally skipped.
    }
}

impl Eq for TransactionKernel {}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum TransactionConfirmabilityError {
    InvalidRemovalRecord(usize),
    DuplicateInputs,
    AlreadySpentInput(usize),
    RemovalRecordUnpackFailure,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum TransactionLustrationError {
    InvalidAoclRangeForIndexSet,
    MissingLustrationAnnouncement,
}

impl From<RemovalRecordListUnpackError> for TransactionConfirmabilityError {
    fn from(_: RemovalRecordListUnpackError) -> Self {
        Self::RemovalRecordUnpackFailure
    }
}

impl TransactionKernel {
    /// Check if transaction is confirmable. Inputs must be unpacked before this
    /// check is performed.
    pub fn is_confirmable_relative_to(
        &self,
        mutator_set_accumulator: &MutatorSetAccumulator,
    ) -> Result<(), TransactionConfirmabilityError> {
        // check validity of removal records
        //       ^^^^^^^^

        // meaning: a) all required membership proofs exist; and b) are valid.
        let inputs = &self.inputs;
        let maybe_invalid_removal_record = inputs
            .iter()
            .enumerate()
            .find(|(_, rr)| !rr.validate(mutator_set_accumulator));
        if let Some((index, _invalid_removal_record)) = maybe_invalid_removal_record {
            return Err(TransactionConfirmabilityError::InvalidRemovalRecord(index));
        }

        // check for duplicates
        let has_unique_inputs =
            inputs.iter().unique_by(|rr| rr.absolute_indices).count() == inputs.len();
        if !has_unique_inputs {
            return Err(TransactionConfirmabilityError::DuplicateInputs);
        }

        // check for already-spent inputs
        let already_spent_removal_record = inputs
            .iter()
            .enumerate()
            .find(|(_, rr)| !mutator_set_accumulator.can_remove(rr));
        if let Some((index, _already_spent_removal_record)) = already_spent_removal_record {
            return Err(TransactionConfirmabilityError::AlreadySpentInput(index));
        }

        Ok(())
    }

    /// Returns `true` iff the "output" transaction kernel is a merged
    /// transaction that has the "input" transaction as one of its inputs. In
    /// other  words, if there exists an X that is not a nop transaction such
    /// that (input, X) -> output is a valid merge of two transactions this
    /// function returns true.
    ///
    /// The caller must verify that the associated transaction proofs are of
    /// type single proof, as only single proof-backed transactions can be
    /// merged.
    pub fn have_merge_relationship(output: &Self, input: &Self) -> bool {
        // Merge outputs are guaranteed to have merge bit set
        if !output.merge_bit {
            return false;
        }

        // merge output cannot have fewer inputs/outputs/announcements than
        // the two transaction it was merged from.
        if output.inputs.len() < input.inputs.len() {
            return false;
        }

        if output.outputs.len() < input.outputs.len() {
            return false;
        }

        if output.announcements.len() < input.announcements.len() {
            return false;
        }

        // Merge result cannot have timestamp prior to its input transactions.
        if output.timestamp < input.timestamp {
            return false;
        }

        // At least one of the fields, inputs/outputs/announcements must have
        // grown in a proper (i.e. non-nop) merge.
        if output.inputs.len() == input.inputs.len()
            && output.outputs.len() == input.outputs.len()
            && output.announcements.len() == input.announcements.len()
        {
            return false;
        }

        // Inputs/outputs/announcements for existing transaction must all be
        // subsets of new transaction in case of merge.
        let new_txs_outputs: HashSet<_> = output.outputs.clone().into_iter().collect();
        for old_tx_output in &input.outputs {
            if !new_txs_outputs.contains(old_tx_output) {
                return false;
            }
        }

        let new_txs_inputs: HashSet<_> = output.inputs.iter().map(|x| x.absolute_indices).collect();
        for old_tx_input in &input.inputs {
            if !new_txs_inputs.contains(&old_tx_input.absolute_indices) {
                return false;
            }
        }

        let new_txs_announcements: HashSet<_> = output.announcements.clone().into_iter().collect();
        for old_tx_announcement in &input.announcements {
            if !new_txs_announcements.contains(old_tx_announcement) {
                return false;
            }
        }

        true
    }

    /// Check if a transaction lustrates (reveals) all the required amounts, and
    /// if it does, return the amount that the lustration counter should be
    /// decreased with, if this transaction is mined.
    ///
    /// Returns an error if the lustration rule defined by the AOCL leaf index
    /// threshold is not followed. The threshold defines the *last* AOCL leaf
    /// that must lustrate.
    ///
    /// Returns an error if the transaction or block violates the rules
    /// specified by the function parameter.
    ///
    /// Note that an `Ok` result only confirms these specific rules are met;
    /// it does not guarantee the overall validity of the block or transaction.
    pub fn verified_lustration_amount(
        &self,
        max_lustrating_aocl_leaf_index: u64,
        fix_lustration_double_counting: bool,
    ) -> Result<NativeCurrencyAmount, TransactionLustrationError> {
        let mut required_lustrations = vec![];
        for input in &self.inputs {
            let Ok((input_index_lower_end, _)) = input.absolute_indices.aocl_range() else {
                return Err(TransactionLustrationError::InvalidAoclRangeForIndexSet);
            };

            let must_lustrate = input_index_lower_end <= max_lustrating_aocl_leaf_index;
            if must_lustrate {
                required_lustrations.push(input.absolute_indices);
            }
        }

        let mut required_lustrations: HashSet<_> = required_lustrations.into_iter().collect();

        let all_lustrations = self
            .announcements
            .iter()
            .filter(|ann| {
                ann.message
                    .first()
                    .is_some_and(|elem0| *elem0 == LUSTRATION_FLAG)
            })
            .collect_vec();

        let mut acc_amount = NativeCurrencyAmount::zero();
        for lustration in all_lustrations {
            let Ok(lustration) = TransparentInput::decode(&lustration.message[1..]) else {
                continue;
            };
            let implied_index_set = lustration.absolute_index_set();
            let was_present = required_lustrations.remove(&implied_index_set);
            if was_present {
                // Hardfork-beta double counts lustrations that happen close
                // to the barrier. This bug was fixed in hardfork-gamma. Cf.:
                // https://talk.neptune.cash/t/small-bug-in-lustration-counter-update-logic/
                // https://web.archive.org/web/20260609105401/https://talk.neptune.cash/t/small-bug-in-lustration-counter-update-logic/286
                let is_before_barrier =
                    lustration.aocl_leaf_index <= max_lustrating_aocl_leaf_index;
                if is_before_barrier || !fix_lustration_double_counting {
                    acc_amount += lustration.utxo.get_native_currency_amount();
                }
            }
        }

        if !required_lustrations.is_empty() {
            return Err(TransactionLustrationError::MissingLustrationAnnouncement);
        }

        Ok(acc_amount)
    }
}

#[derive(VariantArray, Debug, Clone, EnumCount, Copy, strum::Display)]
#[strum(serialize_all = "snake_case")]
pub enum TransactionKernelField {
    Inputs,
    Outputs,
    Announcements,
    Fee,
    Coinbase,
    Timestamp,
    MutatorSetHash,
    MergeBit,
}

impl HasDiscriminant for TransactionKernelField {
    fn discriminant(&self) -> usize {
        *self as usize
    }
}

impl MastHash for TransactionKernel {
    type FieldEnum = TransactionKernelField;

    /// Return the sequences (= leaf preimages) of the kernel Merkle tree.
    fn mast_sequences(&self) -> Vec<Vec<BFieldElement>> {
        self.mast_sequences
            .get_or_init(|| {
                let input_utxos_sequence = self.inputs.encode();

                let output_utxos_sequence = self.outputs.encode();

                let announcements_sequence = self.announcements.encode();

                let fee_sequence = self.fee.encode();

                let coinbase_sequence = self.coinbase.encode();

                let timestamp_sequence = self.timestamp.encode();

                let mutator_set_hash_sequence = self.mutator_set_hash.encode();

                let merge_bit_sequence = self.merge_bit.encode();

                vec![
                    input_utxos_sequence,
                    output_utxos_sequence,
                    announcements_sequence,
                    fee_sequence,
                    coinbase_sequence,
                    timestamp_sequence,
                    mutator_set_hash_sequence,
                    merge_bit_sequence,
                ]
            })
            .clone() // can we refactor to avoid this clone?
    }
}

#[cfg(any(test, feature = "arbitrary-impls"))]
pub mod neptune_arbitrary {
    use arbitrary::Arbitrary;
    use itertools::Itertools;
    use proptest::prelude::Strategy;

    use super::*;

    impl TransactionKernel {
        pub(crate) fn arbitrary_with_fee<'a>(
            u: &mut ::arbitrary::Unstructured<'a>,
            fee: NativeCurrencyAmount,
        ) -> ::arbitrary::Result<Self> {
            let num_inputs = u.int_in_range(0..=4)?;
            let num_outputs = u.int_in_range(0..=4)?;
            let num_announcements = u.int_in_range(0..=2)?;
            let num_aocl_leafs = u.int_in_range(0u64..=(1u64 << 63))?;

            // Get some seed bytes from the unstructured input
            let seed = u.bytes(32)?; // choose an appropriate length

            // Create a proptest RNG from the seed
            let rng = proptest::test_runner::TestRng::from_seed(
                proptest::test_runner::RngAlgorithm::ChaCha,
                &seed.try_into().unwrap_or([0u8; 32]), // handle length mismatch
            );

            let config = proptest::test_runner::Config::default();
            let mut runner = proptest::test_runner::TestRunner::new_with_rng(config, rng);

            let inputs = RemovalRecord::arbitrary_synchronized_set(num_aocl_leafs, num_inputs)
                .new_tree(&mut runner)
                .unwrap()
                .current();
            let outputs: Vec<AdditionRecord> = (0..num_outputs)
                .map(|_| u.arbitrary().unwrap())
                .collect_vec();
            let announcements: Vec<Announcement> = (0..num_announcements)
                .map(|_| u.arbitrary().unwrap())
                .collect_vec();
            let coinbase: Option<NativeCurrencyAmount> = u.arbitrary()?;
            let timestamp: Timestamp = u.arbitrary()?;
            let mutator_set_hash: Digest = u.arbitrary()?;
            let merge_bit: bool = u.arbitrary()?;

            let transaction_kernel = TransactionKernelProxy {
                inputs,
                outputs,
                announcements,
                fee,
                coinbase,
                timestamp,
                mutator_set_hash,
                merge_bit,
            }
            .into_kernel();

            Ok(transaction_kernel)
        }
    }

    impl<'a> Arbitrary<'a> for TransactionKernel {
        /// Produces unpacked inputs.
        fn arbitrary(u: &mut ::arbitrary::Unstructured<'a>) -> ::arbitrary::Result<Self> {
            let fee: NativeCurrencyAmount = u.arbitrary()?;
            Self::arbitrary_with_fee(u, fee)
        }
    }
}

/// performs instantiation and destructuring of [TransactionKernel]
///
/// [TransactionKernel] is immutable, so it cannot be instantiated
/// by direct field access.  This proxy is mutable, and it has an
/// into_kernel() method that converts it to a [TransactionKernel].
///
/// It is also useful for destructuring kernel fields without cloning.
#[derive(Debug, Clone)]
#[cfg_attr(any(test, feature = "arbitrary-impls"), derive(arbitrary::Arbitrary))]
pub struct TransactionKernelProxy {
    /// contains the transaction inputs.
    pub inputs: Vec<RemovalRecord>,

    /// contains the commitments (addition records) that go into the AOCL
    pub outputs: Vec<AdditionRecord>,

    /// list of public-announcements to include in blockchain
    pub announcements: Vec<Announcement>,

    /// tx fee amount
    pub fee: NativeCurrencyAmount,

    /// optional coinbase.  applies only to miner payments.
    pub coinbase: Option<NativeCurrencyAmount>,

    /// number of milliseconds since unix epoch
    pub timestamp: Timestamp,

    /// mutator set hash *prior* to updating mutator set with this transaction.
    pub mutator_set_hash: Digest,

    /// Indicates whether the transaction is the result of some merger.
    pub merge_bit: bool,
}

impl From<TransactionKernel> for TransactionKernelProxy {
    fn from(k: TransactionKernel) -> Self {
        Self {
            inputs: k.inputs,
            outputs: k.outputs,
            announcements: k.announcements,
            fee: k.fee,
            coinbase: k.coinbase,
            timestamp: k.timestamp,
            mutator_set_hash: k.mutator_set_hash,
            merge_bit: k.merge_bit,
        }
    }
}

impl TransactionKernelProxy {
    pub fn into_kernel(self) -> TransactionKernel {
        TransactionKernel {
            inputs: self.inputs,
            outputs: self.outputs,
            announcements: self.announcements,
            fee: self.fee,
            coinbase: self.coinbase,
            timestamp: self.timestamp,
            mutator_set_hash: self.mutator_set_hash,
            merge_bit: self.merge_bit,
            mast_sequences: Default::default(),
        }
    }
}

/// performs modifications of [TransactionKernel]
///
/// [TransactionKernel] is immutable, so any modifications must
/// generate a new instance.  [TransactionKernelModifier] uses
/// a builder pattern to facilitate that task.
///
/// supports a move/modify operation and a clone/modify operation.
#[derive(Debug, Default, Clone)]
pub struct TransactionKernelModifier {
    pub inputs: Option<Vec<RemovalRecord>>,
    pub outputs: Option<Vec<AdditionRecord>>,
    pub announcements: Option<Vec<Announcement>>,
    pub fee: Option<NativeCurrencyAmount>,
    pub coinbase: Option<Option<NativeCurrencyAmount>>,
    pub timestamp: Option<Timestamp>,
    pub mutator_set_hash: Option<Digest>,
    pub merge_bit: Option<bool>,
}

impl TransactionKernelModifier {
    /// set modified inputs
    pub fn inputs(mut self, inputs: Vec<RemovalRecord>) -> Self {
        self.inputs = Some(inputs);
        self
    }
    /// set modified outputs
    pub fn outputs(mut self, outputs: Vec<AdditionRecord>) -> Self {
        self.outputs = Some(outputs);
        self
    }
    /// set modified public-announcements
    pub fn announcements(mut self, announcements: Vec<Announcement>) -> Self {
        self.announcements = Some(announcements);
        self
    }
    /// set modified fee
    pub fn fee(mut self, fee: NativeCurrencyAmount) -> Self {
        self.fee = Some(fee);
        self
    }
    /// set modified coinbase
    pub fn coinbase(mut self, coinbase: Option<NativeCurrencyAmount>) -> Self {
        self.coinbase = Some(coinbase);
        self
    }
    /// set modified timestamp
    pub fn timestamp(mut self, timestamp: Timestamp) -> Self {
        self.timestamp = Some(timestamp);
        self
    }
    /// set modified mutator-set-hash digest
    pub fn mutator_set_hash(mut self, mutator_set_hash: Digest) -> Self {
        self.mutator_set_hash = Some(mutator_set_hash);
        self
    }
    /// set merge-bit
    pub fn merge_bit(mut self, merge_bit: bool) -> Self {
        self.merge_bit = Some(merge_bit);
        self
    }

    /// perform move+modify operation.
    ///
    /// The input [TransactionKernel] is replaced with a copy
    /// that contains any modifications previously set in the builder.
    ///
    /// Unmodified fields from the input kernel are moved into the
    /// output kernel (no clone).
    pub fn modify(self, k: TransactionKernel) -> TransactionKernel {
        TransactionKernel {
            inputs: self.inputs.unwrap_or(k.inputs),
            outputs: self.outputs.unwrap_or(k.outputs),
            announcements: self.announcements.unwrap_or(k.announcements),
            fee: self.fee.unwrap_or(k.fee),
            coinbase: self.coinbase.unwrap_or(k.coinbase),
            timestamp: self.timestamp.unwrap_or(k.timestamp),
            mutator_set_hash: self.mutator_set_hash.unwrap_or(k.mutator_set_hash),
            merge_bit: self.merge_bit.unwrap_or(k.merge_bit),

            // we must not copy from original, as the modified
            // one must have a different sequence/hash.
            mast_sequences: Default::default(),
        }
    }

    /// perform clone+modify operation.
    ///
    /// The input [TransactionKernel] is replaced with a cloned copy
    /// that contains any modifications previously set in the builder.
    pub fn clone_modify(self, k: &TransactionKernel) -> TransactionKernel {
        self.modify(k.clone())
    }
}

#[cfg(any(test, feature = "test-helpers"))]
mod test_support {
    use arbitrary::Unstructured;
    use proptest::prelude::BoxedStrategy;
    use proptest::prelude::Strategy;
    use proptest_arbitrary_interop::arb;

    use super::*;

    impl rand::distr::Distribution<TransactionKernel> for rand::distr::StandardUniform {
        fn sample<R: rand::Rng + ?Sized>(&self, rng: &mut R) -> TransactionKernel {
            TransactionKernel {
                inputs: (0..10).map(|_| rng.random()).collect_vec(),
                outputs: (0..10).map(|_| rng.random()).collect_vec(),
                announcements: (0..10).map(|_| rng.random()).collect_vec(),
                fee: rng.random::<NativeCurrencyAmount>().abs(),
                coinbase: if rng.random_bool(0.5) {
                    Some(rng.random())
                } else {
                    None
                },
                timestamp: rng.random(),
                mutator_set_hash: rng.random(),
                merge_bit: rng.random(),
                mast_sequences: OnceLock::new(),
            }
        }
    }

    impl TransactionKernel {
        /// Lifts `Self::arbitrary_with_fee` into a `Strategy`.
        pub fn strategy_with_fee(fee: NativeCurrencyAmount) -> BoxedStrategy<Self> {
            // Choose an upper bound for how many bytes you want to feed into
            // `Unstructured`.
            const MAX_BYTES: usize = 262144;

            proptest::collection::vec(arb::<u8>(), 0..=MAX_BYTES)
                .prop_filter_map("could not construct from bytes", move |bytes| {
                    let mut u = Unstructured::new(&bytes);
                    Self::arbitrary_with_fee(&mut u, fee).ok()
                })
                .boxed()
        }

        pub fn lowest_aocl_leaf_index(&self) -> Option<u64> {
            self.inputs
                .iter()
                .map(|input| {
                    let (min_leaf, _) = input.absolute_indices.aocl_range().unwrap();
                    min_leaf
                })
                .min()
        }
    }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
pub mod tests {

    use itertools::Itertools;
    use proptest::prelude::Strategy;
    use proptest::strategy::ValueTree;
    use proptest::test_runner::TestRunner;
    use proptest_arbitrary_interop::arb;
    use test_strategy::proptest;

    use super::*;
    use crate::block::mutator_set_update::MutatorSetUpdate;
    use crate::transaction::PrimitiveWitness;
    use crate::transaction::Transaction;
    use crate::transaction::TransactionProof;

    #[test]
    pub fn arbitrary_tx_kernel_is_deterministic() {
        use proptest::prelude::Strategy;
        use proptest::strategy::ValueTree;
        use proptest::test_runner::TestRunner;
        use proptest_arbitrary_interop::arb;

        let mut test_runner = TestRunner::deterministic();
        let a = arb::<TransactionKernel>()
            .new_tree(&mut test_runner)
            .unwrap()
            .current();

        test_runner = TestRunner::deterministic();
        let b = arb::<TransactionKernel>()
            .new_tree(&mut test_runner)
            .unwrap()
            .current();

        assert_eq!(a.outputs, b.outputs);
        assert_eq!(a.fee, b.fee);
        assert_eq!(a.coinbase, b.coinbase);
        assert_eq!(a.mutator_set_hash, b.mutator_set_hash);
        assert_eq!(a.merge_bit, b.merge_bit);
        assert_eq!(a.announcements, b.announcements);
        assert_eq!(a.timestamp, b.timestamp);
        assert_eq!(a.inputs, b.inputs);
        assert_eq!(a, b);
    }

    #[test]
    fn can_identify_double_spends() {
        let mut test_runner = TestRunner::deterministic();

        let pw = PrimitiveWitness::arbitrary_with_size_numbers(Some(2), 2, 2)
            .new_tree(&mut test_runner)
            .unwrap()
            .current();
        let mut msa = pw.mutator_set_accumulator.clone();
        let tx = Transaction {
            kernel: pw.kernel.clone(),
            proof: TransactionProof::Witness(pw),
        };
        assert_eq!(Ok(()), tx.kernel.is_confirmable_relative_to(&msa));

        let repeated_input = [tx.kernel.inputs.clone(), vec![tx.kernel.inputs[0].clone()]].concat();
        let repeated_input = TransactionKernelModifier::default()
            .inputs(repeated_input)
            .modify(tx.kernel.clone());
        assert!(matches!(
            repeated_input.is_confirmable_relative_to(&msa),
            Err(TransactionConfirmabilityError::DuplicateInputs),
        ));

        // Update the mutator set to *after* applying this tx. Then verify tx is
        // unspendable because inputs are already spent.
        let mut removal_records = tx.kernel.inputs.clone();
        let ms_update = MutatorSetUpdate::new(removal_records.clone(), tx.kernel.outputs.clone());
        ms_update
            .apply_to_accumulator_and_records(
                &mut msa,
                &mut removal_records.iter_mut().collect_vec(),
                &mut [],
            )
            .unwrap();
        let new_tx = TransactionKernelModifier::default()
            .inputs(removal_records)
            .mutator_set_hash(msa.hash())
            .modify(tx.kernel.clone());
        assert!(
            matches!(
                new_tx.is_confirmable_relative_to(&msa),
                Err(TransactionConfirmabilityError::AlreadySpentInput(_))
            ),
            "{:?}",
            repeated_input.is_confirmable_relative_to(&msa)
        );
    }

    #[proptest]
    fn decode_announcement(#[strategy(arb::<Announcement>())] announcement: Announcement) {
        let encoded = announcement.encode();
        let decoded = *Announcement::decode(&encoded).unwrap();
        assert_eq!(announcement, decoded);
    }

    #[proptest]
    fn decode_announcements(#[strategy([arb(), arb()])] announcements: [Announcement; 2]) {
        let announcements = announcements.to_vec();
        let encoded = announcements.encode();
        let decoded = *Vec::<Announcement>::decode(&encoded).unwrap();
        assert_eq!(announcements, decoded);
    }

    #[proptest]
    fn test_decode_transaction_kernel(
        #[strategy(crate::transaction::test_helpers::txkernel::default(false))]
        kernel: TransactionKernel,
    ) {
        let encoded = kernel.encode();
        let decoded = *TransactionKernel::decode(&encoded).unwrap();
        assert_eq!(kernel, decoded);
    }

    proptest::proptest! {
        #[test]
        fn test_decode_transaction_kernel_small(
            absolute_indices in neptune_mutator_set::strategies::absindset(),
            canonical_commitment in arb::<Digest>(),
            mutator_set_hash in arb::<Digest>(),
        ) {
            let removal_record = RemovalRecord {
                absolute_indices,
                target_chunks: Default::default(),
            };
            let kernel = TransactionKernelProxy {
                inputs: vec![removal_record],
                outputs: vec![AdditionRecord {
                    canonical_commitment
                }],
                announcements: Default::default(),
                fee: NativeCurrencyAmount::one_nau(),
                coinbase: None,
                timestamp: Default::default(),
                mutator_set_hash,
                merge_bit: true,
            }
            .into_kernel();
            let encoded = kernel.encode();
            println!(
                "encoded: {}",
                encoded.iter().map(|x| x.to_string()).join(", ")
            );
            let decoded = *TransactionKernel::decode(&encoded).unwrap();
            assert_eq!(kernel, decoded);
        }
    }

    mod lustrations {
        use tasm_lib::twenty_first::bfe;

        use super::*;
        use crate::transaction::utxo::Utxo;

        #[proptest(cases = 5)]
        fn no_lustration_required_on_new_aocl_leafs(
            #[strategy(PrimitiveWitness::arbitrary_with_size_numbers(Some(2), 2, 2))]
            primitive_witness: PrimitiveWitness,
        ) {
            let kernel = &primitive_witness.kernel;
            assert_eq!(
                Ok(NativeCurrencyAmount::zero()),
                kernel.verified_lustration_amount(
                    kernel.lowest_aocl_leaf_index().unwrap() - 1,
                    false
                )
            );
        }

        #[proptest(cases = 5)]
        fn returns_error_on_missing_lustration(
            #[strategy(PrimitiveWitness::arbitrary_with_size_numbers(Some(2), 2, 2))]
            primitive_witness: PrimitiveWitness,
        ) {
            let kernel = &primitive_witness.kernel;

            let min_aocl_leaf_index = kernel.lowest_aocl_leaf_index().unwrap();
            assert_eq!(
                Err(TransactionLustrationError::MissingLustrationAnnouncement),
                kernel.verified_lustration_amount(min_aocl_leaf_index, false)
            );
            assert_eq!(
                Err(TransactionLustrationError::MissingLustrationAnnouncement),
                kernel.verified_lustration_amount(min_aocl_leaf_index + 1, false)
            );
        }

        #[proptest(cases = 5)]
        fn tx_without_inputs_requires_no_lustration(
            #[strategy(PrimitiveWitness::arbitrary_with_size_numbers(Some(0), 2, 2))]
            primitive_witness: PrimitiveWitness,
        ) {
            let kernel = &primitive_witness.kernel;
            assert_eq!(
                Ok(NativeCurrencyAmount::zero()),
                kernel.verified_lustration_amount(u64::MAX, false)
            );
        }

        fn one_input_kernel(
            test_runner: &mut TestRunner,
            include_lustration: bool,
        ) -> TransactionKernel {
            use crate::transaction::lock_script::LockScriptAndWitness;

            let lock_script_and_witness =
                LockScriptAndWitness::genaddr_like_hash_lock_from_seed(Digest::default());

            let input_utxo = Utxo::new_native_currency(
                lock_script_and_witness.program.hash(),
                NativeCurrencyAmount::coins(12),
            );

            let fee = NativeCurrencyAmount::zero();
            let coinbase = None;
            let primitive_witness = PrimitiveWitness::arbitrary_primitive_witness_with(
                std::slice::from_ref(&input_utxo),
                std::slice::from_ref(&lock_script_and_witness),
                &[],
                &[],
                fee,
                coinbase,
            )
            .new_tree(test_runner)
            .unwrap()
            .current();

            let mut kernel = primitive_witness.kernel.clone();

            if include_lustration {
                let msmp = &primitive_witness.input_membership_proofs[0];
                let input = TransparentInput {
                    utxo: input_utxo.clone(),
                    aocl_leaf_index: msmp.aocl_leaf_index,
                    sender_randomness: msmp.sender_randomness,
                    receiver_preimage: msmp.receiver_preimage,
                };
                kernel
                    .announcements
                    .push(Announcement::lustration_announcement(&input));
            }

            kernel
        }

        #[test]
        fn lustration_check_one_input() {
            let mut test_runner = TestRunner::deterministic();

            let no_lustration = one_input_kernel(&mut test_runner, false);
            assert_eq!(
                Err(TransactionLustrationError::MissingLustrationAnnouncement),
                no_lustration.verified_lustration_amount(u64::MAX, false)
            );

            // Then add lustration, and verify that Ok(amount) is returned.
            let mut with_lustration = one_input_kernel(&mut test_runner, true);
            assert_eq!(
                1,
                with_lustration.announcements.len(),
                "Lustrating kernel must contain exactly one announcement"
            );
            assert_eq!(
                Ok(NativeCurrencyAmount::coins(12)),
                with_lustration.verified_lustration_amount(u64::MAX, false)
            );

            // Modify the announcement such that it no longer correctly
            // lustrates.
            with_lustration.announcements[0].message[15] = bfe!(u64::MAX);
            assert_eq!(
                Err(TransactionLustrationError::MissingLustrationAnnouncement),
                with_lustration.verified_lustration_amount(u64::MAX, false)
            );
        }
    }
}