monero-oxide 0.1.0

A modern Monero transaction library
Documentation
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
use core::cmp::Ordering;
use std_shims::prelude::*;
use std_shims::io::{self, Read, Write};

use zeroize::Zeroize;

use crate::{
  io::*,
  ed25519::*,
  primitives::{UpperBound, LowerBound, keccak256},
  ring_signatures::RingSignature,
  ringct::{bulletproofs::Bulletproof, PrunedRctProofs},
};

// Ensure `usize` can be used to represent a block number, a prerequesite to so define `Input::Gen`
#[expect(clippy::absurd_extreme_comparisons)]
const _INPUT_GEN_MAY_USE_USIZE: () = {
  // https://github.com/monero-project/monero
  //   /blob/d85cfa04d86477dcb4001a21f30953a8ab6e1df2/src/cryptonote_config.h#L40
  assert!(usize::MAX >= 500_000_000);
};

/// An input in the Monero protocol.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Input {
  /// An input for a miner transaction, which is generating new coins.
  Gen(usize),
  /// An input spending an output on-chain.
  ToKey {
    /// The pool this input spends an output of.
    amount: Option<u64>,
    /// The decoys used by this input's ring, specified as their offset distance from each other.
    key_offsets: Vec<u64>,
    /// The key image (linking tag, nullifer) for the spent output.
    key_image: CompressedPoint,
  },
}

impl Input {
  /// The lower bound for the size of an input which isn't `Input::Gen(_)`.
  // `<usize as VarInt>::LOWER_BOUND` is used for the lower-bound of a `Vec`'s encoding's length
  const NON_GEN_SIZE_LOWER_BOUND: LowerBound<usize> =
    LowerBound(1 + <u64 as VarInt>::LOWER_BOUND + <usize as VarInt>::LOWER_BOUND + 32);

  /// Write the Input.
  pub fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
    match self {
      Input::Gen(height) => {
        w.write_all(&[255])?;
        VarInt::write(height, w)
      }

      Input::ToKey { amount, key_offsets, key_image } => {
        w.write_all(&[2])?;
        VarInt::write(&amount.unwrap_or(0), w)?;
        write_vec(VarInt::write, key_offsets, w)?;
        key_image.write(w)
      }
    }
  }

  /// Serialize the Input to a `Vec<u8>`.
  pub fn serialize(&self) -> Vec<u8> {
    let mut res = vec![];
    self.write(&mut res).expect("write failed but <Vec as io::Write> doesn't fail");
    res
  }

  /// Read an Input.
  pub fn read<R: Read>(r: &mut R) -> io::Result<Input> {
    Ok(match read_byte(r)? {
      255 => Input::Gen(VarInt::read(r)?),
      2 => {
        let amount = VarInt::read(r)?;
        // https://github.com/monero-project/monero/
        //   blob/00fd416a99686f0956361d1cd0337fe56e58d4a7/
        //   src/cryptonote_basic/cryptonote_format_utils.cpp#L860-L863
        // A non-RCT 0-amount input can't exist because only RCT TXs can have a 0-amount output
        // That's why collapsing to None if the amount is 0 is safe, even without knowing if RCT
        let amount = if amount == 0 { None } else { Some(amount) };
        Input::ToKey {
          amount,
          // Each offset takes at least one byte, and this won't be in a miner transaction
          key_offsets: read_vec(
            VarInt::read,
            Some(Transaction::<NotPruned>::NON_MINER_SIZE_UPPER_BOUND.0),
            r,
          )?,
          key_image: CompressedPoint::read(r)?,
        }
      }
      _ => Err(io::Error::other("Tried to deserialize unknown/unused input type"))?,
    })
  }
}

/// An output in the Monero protocol.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Output {
  /// The pool this output should be sorted into.
  pub amount: Option<u64>,
  /// The key which can spend this output.
  pub key: CompressedPoint,
  /// The view tag for this output, as used to accelerate scanning.
  pub view_tag: Option<u8>,
}

impl Output {
  /// The lower bound on the size of an output.
  pub const SIZE_LOWER_BOUND: LowerBound<usize> = LowerBound(<u64 as VarInt>::LOWER_BOUND + 1 + 32);
  /// The upper bound on the size of an output.
  pub const SIZE_UPPER_BOUND: UpperBound<usize> =
    UpperBound(<u64 as VarInt>::UPPER_BOUND + 1 + 32 + 1);

  /// Write the Output.
  pub fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
    VarInt::write(&self.amount.unwrap_or(0), w)?;
    w.write_all(&[2 + u8::from(self.view_tag.is_some())])?;
    w.write_all(&self.key.to_bytes())?;
    if let Some(view_tag) = self.view_tag {
      w.write_all(&[view_tag])?;
    }
    Ok(())
  }

  /// Write the Output to a `Vec<u8>`.
  pub fn serialize(&self) -> Vec<u8> {
    let mut res = Vec::with_capacity(Self::SIZE_UPPER_BOUND.0);
    self.write(&mut res).expect("write failed but <Vec as io::Write> doesn't fail");
    res
  }

  /// Read an Output.
  pub fn read<R: Read>(rct: bool, r: &mut R) -> io::Result<Output> {
    let amount = VarInt::read(r)?;
    let amount = if rct {
      if amount != 0 {
        Err(io::Error::other("RCT TX output wasn't 0"))?;
      }
      None
    } else {
      Some(amount)
    };

    let view_tag = match read_byte(r)? {
      2 => false,
      3 => true,
      _ => Err(io::Error::other("Tried to deserialize unknown/unused output type"))?,
    };

    Ok(Output {
      amount,
      key: CompressedPoint::read(r)?,
      view_tag: if view_tag { Some(read_byte(r)?) } else { None },
    })
  }
}

/// An additional timelock for a Monero transaction.
///
/// Monero outputs are locked by a default timelock. If a timelock is explicitly specified, the
/// longer of the two will be the timelock used.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Zeroize)]
pub enum Timelock {
  /// No additional timelock.
  None,
  /// Additionally locked until this block.
  Block(usize),
  /// Additionally locked until this many seconds since the epoch.
  Time(u64),
}

impl Timelock {
  /// Write the Timelock.
  pub fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
    match self {
      Timelock::None => VarInt::write(&0u8, w),
      Timelock::Block(block) => VarInt::write(block, w),
      Timelock::Time(time) => VarInt::write(time, w),
    }
  }

  /// Serialize the Timelock to a `Vec<u8>`.
  pub fn serialize(&self) -> Vec<u8> {
    let mut res = Vec::with_capacity(1);
    self.write(&mut res).expect("write failed but <Vec as io::Write> doesn't fail");
    res
  }

  /// Read a Timelock.
  pub fn read<R: Read>(r: &mut R) -> io::Result<Self> {
    const TIMELOCK_BLOCK_THRESHOLD: usize = 500_000_000;

    let raw = <u64 as VarInt>::read(r)?;
    Ok(if raw == 0 {
      Timelock::None
    } else if raw <
      u64::try_from(TIMELOCK_BLOCK_THRESHOLD)
        .expect("TIMELOCK_BLOCK_THRESHOLD didn't fit in a u64")
    {
      Timelock::Block(usize::try_from(raw).expect(
        "timelock overflowed usize despite being less than a const representable with a usize",
      ))
    } else {
      Timelock::Time(raw)
    })
  }
}

impl PartialOrd for Timelock {
  fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
    match (self, other) {
      (Timelock::None, Timelock::None) => Some(Ordering::Equal),
      (Timelock::None, _) => Some(Ordering::Less),
      (_, Timelock::None) => Some(Ordering::Greater),
      (Timelock::Block(a), Timelock::Block(b)) => a.partial_cmp(b),
      (Timelock::Time(a), Timelock::Time(b)) => a.partial_cmp(b),
      _ => None,
    }
  }
}

/// The transaction prefix.
///
/// This is common to all transaction versions and contains most parts of the transaction needed to
/// handle it. It excludes any proofs.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct TransactionPrefix {
  /// The timelock this transaction is additionally constrained by.
  ///
  /// All transactions on the blockchain are subject to a 10-block lock. This adds a further
  /// constraint.
  pub additional_timelock: Timelock,
  /// The inputs for this transaction.
  pub inputs: Vec<Input>,
  /// The outputs for this transaction.
  pub outputs: Vec<Output>,
  /// The additional data included within the transaction.
  ///
  /// This is an arbitrary data field, yet is used by wallets for containing the data necessary to
  /// scan the transaction.
  pub extra: Vec<u8>,
}

impl TransactionPrefix {
  /// The amount of inputs within a miner transaction.
  pub const MINER_INPUTS: usize = 1;
  /// The amount of inputs allowed within a non-miner transaction.
  // This is defined as the amount of whole (minimally-sized) inputs which would fit in the largest
  // possible transaction.
  pub const NON_MINER_INPUTS_UPPER_BOUND: UpperBound<usize> = UpperBound(
    Transaction::<NotPruned>::NON_MINER_SIZE_UPPER_BOUND.0 / Input::NON_GEN_SIZE_LOWER_BOUND.0,
  );
  /// The upper bound for the amount of inputs allowed within a transaction.
  pub const INPUTS_UPPER_BOUND: UpperBound<usize> = UpperBound(monero_primitives::const_max!(
    Self::MINER_INPUTS,
    Self::NON_MINER_INPUTS_UPPER_BOUND.0
  ));

  /// The upper bound for the amount of outputs allowed within a non-miner transaction.
  pub const NON_MINER_OUTPUTS_UPPER_BOUND: UpperBound<usize> =
    UpperBound(Transaction::<NotPruned>::NON_MINER_SIZE_UPPER_BOUND.0 / Output::SIZE_LOWER_BOUND.0);

  /// Write a TransactionPrefix.
  ///
  /// This is distinct from Monero in that it won't write any version.
  fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
    self.additional_timelock.write(w)?;
    write_vec(Input::write, &self.inputs, w)?;
    write_vec(Output::write, &self.outputs, w)?;
    VarInt::write(&self.extra.len(), w)?;
    w.write_all(&self.extra)
  }

  /// Read a TransactionPrefix.
  ///
  /// This is distinct from Monero in that it won't read the version. The version must be passed
  /// in.
  ///
  /// This MAY error if miscellaneous Monero conseusus rules are broken, as useful when
  /// deserializing. The result is not guaranteed to follow all Monero consensus rules or any
  /// specific set of consensus rules.
  pub fn read<R: Read>(r: &mut R, version: u64) -> io::Result<TransactionPrefix> {
    let additional_timelock = Timelock::read(r)?;

    let inputs = read_vec(|r| Input::read(r), Some(Self::INPUTS_UPPER_BOUND.0), r)?;
    if inputs.is_empty() {
      Err(io::Error::other("transaction had no inputs"))?;
    }
    let is_miner_tx = matches!(inputs[0], Input::Gen { .. });

    let max_outputs = if is_miner_tx { None } else { Some(Self::NON_MINER_OUTPUTS_UPPER_BOUND.0) };
    let mut prefix = TransactionPrefix {
      additional_timelock,
      inputs,
      outputs: read_vec(|r| Output::read((!is_miner_tx) && (version == 2), r), max_outputs, r)?,
      extra: vec![],
    };
    // Miner transactions have no limits on their size within the Monero protocol, unfortunately
    let max_extra =
      if is_miner_tx { None } else { Some(Transaction::<NotPruned>::NON_MINER_SIZE_UPPER_BOUND.0) };
    prefix.extra = read_vec(read_byte, max_extra, r)?;
    Ok(prefix)
  }

  fn hash(&self, version: u64) -> [u8; 32] {
    let mut buf = vec![];
    VarInt::write(&version, &mut buf).expect("write failed but <Vec as io::Write> doesn't fail");
    self.write(&mut buf).expect("write failed but <Vec as io::Write> doesn't fail");
    keccak256(buf)
  }
}

#[expect(private_bounds)]
mod sealed {
  use core::fmt::Debug;
  use crate::ringct::*;
  use super::*;

  pub(crate) trait PotentiallyPrunedRingSignatures:
    Clone + PartialEq + Eq + Default + Debug
  {
    fn signatures_to_write(&self) -> &[RingSignature];
    fn read_signatures(inputs: &[Input], r: &mut impl Read) -> io::Result<Self>;
  }

  impl PotentiallyPrunedRingSignatures for Vec<RingSignature> {
    fn signatures_to_write(&self) -> &[RingSignature] {
      self
    }
    fn read_signatures(inputs: &[Input], r: &mut impl Read) -> io::Result<Self> {
      let mut signatures = Vec::with_capacity(inputs.len());
      for input in inputs {
        match input {
          Input::ToKey { key_offsets, .. } => {
            signatures.push(RingSignature::read(key_offsets.len(), r)?);
          }
          Input::Gen { .. } => {
            Err(io::Error::other("reading signatures for a transaction with non-`ToKey` inputs"))?;
          }
        }
      }
      Ok(signatures)
    }
  }

  impl PotentiallyPrunedRingSignatures for () {
    fn signatures_to_write(&self) -> &[RingSignature] {
      &[]
    }
    fn read_signatures(_: &[Input], _: &mut impl Read) -> io::Result<Self> {
      Ok(())
    }
  }

  pub(crate) trait PotentiallyPrunedRctProofs: Clone + PartialEq + Eq + Debug {
    fn potentially_pruned_write(&self, w: &mut impl Write) -> io::Result<()>;
    fn potentially_pruned_read(
      ring_length: usize,
      inputs: usize,
      outputs: usize,
      r: &mut impl Read,
    ) -> io::Result<Option<Self>>;
    fn potentially_pruned_rct_type(&self) -> RctType;
    fn base(&self) -> &RctBase;
  }

  impl PotentiallyPrunedRctProofs for RctProofs {
    fn potentially_pruned_write(&self, w: &mut impl Write) -> io::Result<()> {
      self.write(w)
    }
    fn potentially_pruned_read(
      ring_length: usize,
      inputs: usize,
      outputs: usize,
      r: &mut impl Read,
    ) -> io::Result<Option<Self>> {
      RctProofs::read(ring_length, inputs, outputs, r)
    }
    fn potentially_pruned_rct_type(&self) -> RctType {
      self.rct_type()
    }
    fn base(&self) -> &RctBase {
      &self.base
    }
  }

  impl PotentiallyPrunedRctProofs for PrunedRctProofs {
    fn potentially_pruned_write(&self, w: &mut impl Write) -> io::Result<()> {
      self.base.write(w, self.rct_type)
    }
    fn potentially_pruned_read(
      _ring_length: usize,
      inputs: usize,
      outputs: usize,
      r: &mut impl Read,
    ) -> io::Result<Option<Self>> {
      Ok(RctBase::read(inputs, outputs, r)?.map(|(rct_type, base)| Self { rct_type, base }))
    }
    fn potentially_pruned_rct_type(&self) -> RctType {
      self.rct_type
    }
    fn base(&self) -> &RctBase {
      &self.base
    }
  }

  trait Sealed {}

  /// A trait representing either pruned or not pruned proofs.
  pub trait PotentiallyPruned: Sealed {
    /// Potentially-pruned ring signatures.
    type RingSignatures: PotentiallyPrunedRingSignatures;
    /// Potentially-pruned RingCT proofs.
    type RctProofs: PotentiallyPrunedRctProofs;
  }
  /// A marker for an object which isn't pruned.
  #[derive(Clone, PartialEq, Eq, Debug)]
  pub struct NotPruned;
  impl Sealed for NotPruned {}
  impl PotentiallyPruned for NotPruned {
    type RingSignatures = Vec<RingSignature>;
    type RctProofs = RctProofs;
  }
  /// A marker for an object which is pruned.
  #[derive(Clone, PartialEq, Eq, Debug)]
  pub struct Pruned;
  impl Sealed for Pruned {}
  impl PotentiallyPruned for Pruned {
    type RingSignatures = ();
    type RctProofs = PrunedRctProofs;
  }
}
pub use sealed::*;

/// A Monero transaction.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Transaction<P: PotentiallyPruned = NotPruned> {
  /// A version 1 transaction, used by the original Cryptonote codebase.
  V1 {
    /// The transaction's prefix.
    prefix: TransactionPrefix,
    /// The transaction's ring signatures.
    signatures: P::RingSignatures,
  },
  /// A version 2 transaction, used by the RingCT protocol.
  V2 {
    /// The transaction's prefix.
    prefix: TransactionPrefix,
    /// The transaction's proofs.
    proofs: Option<P::RctProofs>,
  },
}

enum PrunableHash<'a> {
  V1(&'a [RingSignature]),
  V2([u8; 32]),
}

impl<P: PotentiallyPruned> Transaction<P> {
  /// Get the version of this transaction.
  pub fn version(&self) -> u8 {
    match self {
      Transaction::V1 { .. } => 1,
      Transaction::V2 { .. } => 2,
    }
  }

  /// Get the TransactionPrefix of this transaction.
  pub fn prefix(&self) -> &TransactionPrefix {
    match self {
      Transaction::V1 { prefix, .. } | Transaction::V2 { prefix, .. } => prefix,
    }
  }

  /// Get a mutable reference to the TransactionPrefix of this transaction.
  pub fn prefix_mut(&mut self) -> &mut TransactionPrefix {
    match self {
      Transaction::V1 { prefix, .. } | Transaction::V2 { prefix, .. } => prefix,
    }
  }

  /// Write the Transaction.
  ///
  /// Some writable transactions may not be readable if they're malformed, per Monero's consensus
  /// rules.
  pub fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
    VarInt::write(&self.version(), w)?;
    match self {
      Transaction::V1 { prefix, signatures } => {
        prefix.write(w)?;
        for ring_sig in signatures.signatures_to_write() {
          ring_sig.write(w)?;
        }
      }
      Transaction::V2 { prefix, proofs } => {
        prefix.write(w)?;
        match proofs {
          None => w.write_all(&[0])?,
          Some(proofs) => proofs.potentially_pruned_write(w)?,
        }
      }
    }
    Ok(())
  }

  /// Write the Transaction to a `Vec<u8>`.
  pub fn serialize(&self) -> Vec<u8> {
    let mut res = Vec::with_capacity(2048);
    self.write(&mut res).expect("write failed but <Vec as io::Write> doesn't fail");
    res
  }

  /// Read a Transaction.
  ///
  /// This MAY error if miscellaneous Monero conseusus rules are broken, as useful when
  /// deserializing. The result is not guaranteed to follow all Monero consensus rules or any
  /// specific set of consensus rules.
  pub fn read<R: Read>(r: &mut R) -> io::Result<Self> {
    let version = VarInt::read(r)?;
    let prefix = TransactionPrefix::read(r, version)?;

    if version == 1 {
      let signatures = if (prefix.inputs.len() == 1) && matches!(prefix.inputs[0], Input::Gen(_)) {
        Default::default()
      } else {
        P::RingSignatures::read_signatures(&prefix.inputs, r)?
      };

      Ok(Transaction::V1 { prefix, signatures })
    } else if version == 2 {
      let proofs = P::RctProofs::potentially_pruned_read(
        prefix.inputs.first().map_or(0, |input| match input {
          Input::Gen(_) => 0,
          Input::ToKey { key_offsets, .. } => key_offsets.len(),
        }),
        prefix.inputs.len(),
        prefix.outputs.len(),
        r,
      )?;

      Ok(Transaction::V2 { prefix, proofs })
    } else {
      Err(io::Error::other("tried to deserialize unknown version"))
    }
  }

  // The hash of the transaction.
  #[expect(clippy::needless_pass_by_value)]
  fn hash_with_prunable_hash_internal(&self, prunable: PrunableHash<'_>) -> [u8; 32] {
    match self {
      Transaction::V1 { prefix, .. } => {
        let mut buf = Vec::with_capacity(512);

        // We don't use `self.write` as that may write the signatures (if this isn't pruned)
        VarInt::write(&self.version(), &mut buf)
          .expect("write failed but <Vec as io::Write> doesn't fail");
        prefix.write(&mut buf).expect("write failed but <Vec as io::Write> doesn't fail");

        // We explicitly write the signatures ourselves here
        let PrunableHash::V1(signatures) = prunable else {
          panic!("hashing v1 TX with non-v1 prunable data")
        };
        for signature in signatures {
          signature.write(&mut buf).expect("write failed but <Vec as io::Write> doesn't fail");
        }

        keccak256(buf)
      }
      Transaction::V2 { prefix, proofs } => {
        let mut hashes = Vec::with_capacity(96);

        hashes.extend(prefix.hash(2));

        if let Some(proofs) = proofs {
          let mut buf = Vec::with_capacity(512);
          proofs
            .base()
            .write(&mut buf, proofs.potentially_pruned_rct_type())
            .expect("write failed but <Vec as io::Write> doesn't fail");
          hashes.extend(keccak256(&buf));
        } else {
          // Serialization of RctBase::Null
          hashes.extend(keccak256([0]));
        }
        let PrunableHash::V2(prunable_hash) = prunable else {
          panic!("hashing v2 TX with non-v2 prunable data")
        };
        hashes.extend(prunable_hash);

        keccak256(hashes)
      }
    }
  }
}

impl Transaction<NotPruned> {
  /// The maximum size for a non-miner transaction.
  // https://github.com/monero-project/monero
  //   /blob/8d4c625713e3419573dfcc7119c8848f47cabbaa/src/cryptonote_config.h#L41
  pub const NON_MINER_SIZE_UPPER_BOUND: UpperBound<usize> = UpperBound(1_000_000);

  /// The prunable hash of the transaction.
  ///
  /// This will return `None` for V1 transactions which do not have a well-defined prunable hash.
  pub fn prunable_hash(&self) -> Option<[u8; 32]> {
    match self {
      Transaction::V1 { .. } => None,
      Transaction::V2 { proofs, .. } => Some(if let Some(proofs) = proofs {
        let mut buf = Vec::with_capacity(1024);
        proofs
          .prunable
          .write(&mut buf, proofs.rct_type())
          .expect("write failed but <Vec as io::Write> doesn't fail");
        keccak256(buf)
      } else {
        [0; 32]
      }),
    }
  }

  /// The hash of the transaction.
  pub fn hash(&self) -> [u8; 32] {
    match self {
      Transaction::V1 { signatures, .. } => {
        self.hash_with_prunable_hash_internal(PrunableHash::V1(signatures))
      }
      Transaction::V2 { .. } => self.hash_with_prunable_hash_internal(PrunableHash::V2(
        self.prunable_hash().expect("V2 transaction didn't have a prunable hash"),
      )),
    }
  }

  /// Calculate the hash of this transaction as needed for signing it.
  ///
  /// This returns None if the transaction is without signatures.
  pub fn signature_hash(&self) -> Option<[u8; 32]> {
    Some(match self {
      Transaction::V1 { prefix, .. } => {
        if (prefix.inputs.len() == 1) && matches!(prefix.inputs[0], Input::Gen(_)) {
          None?;
        }
        self.hash_with_prunable_hash_internal(PrunableHash::V1(&[]))
      }
      Transaction::V2 { proofs, .. } => self.hash_with_prunable_hash_internal({
        let Some(proofs) = proofs else { None? };
        let mut buf = Vec::with_capacity(1024);
        proofs
          .prunable
          .signature_write(&mut buf)
          .expect("write failed but <Vec as io::Write> doesn't fail");
        PrunableHash::V2(keccak256(buf))
      }),
    })
  }

  /// Splits this transaction into its pruned and serialized prunable part.
  pub fn pruned_with_prunable(self) -> (Transaction<Pruned>, Vec<u8>) {
    let mut buf = Vec::with_capacity(512);

    match self {
      Transaction::V1 { prefix, signatures } => {
        for signature in signatures {
          signature.write(&mut buf).expect("write failed but <Vec as io::Write> doesn't fail");
        }

        (Transaction::V1 { prefix, signatures: () }, buf)
      }
      Transaction::V2 { prefix, proofs } => {
        match &proofs {
          None => (),
          Some(proofs) => proofs.prunable.write(&mut buf, proofs.rct_type()).unwrap(),
        }

        (
          Transaction::V2 {
            prefix,
            proofs: proofs
              .map(|proofs| PrunedRctProofs { rct_type: proofs.rct_type(), base: proofs.base }),
          },
          buf,
        )
      }
    }
  }

  fn is_rct_bulletproof(&self) -> bool {
    match self {
      Transaction::V1 { .. } => false,
      Transaction::V2 { proofs, .. } => {
        let Some(proofs) = proofs else { return false };
        proofs.rct_type().bulletproof()
      }
    }
  }

  fn is_rct_bulletproof_plus(&self) -> bool {
    match self {
      Transaction::V1 { .. } => false,
      Transaction::V2 { proofs, .. } => {
        let Some(proofs) = proofs else { return false };
        proofs.rct_type().bulletproof_plus()
      }
    }
  }

  /// Calculate the transaction's weight.
  pub fn weight(&self) -> usize {
    let blob_size = self.serialize().len();

    let bp = self.is_rct_bulletproof();
    let bp_plus = self.is_rct_bulletproof_plus();
    if !(bp || bp_plus) {
      blob_size
    } else {
      blob_size +
        Bulletproof::calculate_clawback(
          bp_plus,
          match self {
            Transaction::V1 { .. } => panic!("v1 transaction was BP(+)"),
            Transaction::V2 { prefix, .. } => prefix.outputs.len(),
          },
        )
        .0
    }
  }
}

impl Transaction<Pruned> {
  /// Return the hash of the pruned transaction.
  ///
  /// This requires the transaction be version 2 and the hash of the pruned data be provided. If
  /// the proofs are `RctType::Null`, `prunable_hash` MUST equal `[0; 32]` for the result to be
  /// correct.
  pub fn hash_with_prunable_hash(&self, prunable_hash: [u8; 32]) -> Option<[u8; 32]> {
    match self {
      Transaction::V1 { .. } => None?,
      Transaction::V2 { .. } => {
        Some(self.hash_with_prunable_hash_internal(PrunableHash::V2(prunable_hash)))
      }
    }
  }
}

impl From<Transaction<NotPruned>> for Transaction<Pruned> {
  fn from(tx: Transaction<NotPruned>) -> Transaction<Pruned> {
    match tx {
      Transaction::V1 { prefix, .. } => Transaction::V1 { prefix, signatures: () },
      Transaction::V2 { prefix, proofs } => Transaction::V2 {
        prefix,
        proofs: proofs
          .map(|proofs| PrunedRctProofs { rct_type: proofs.rct_type(), base: proofs.base }),
      },
    }
  }
}