pczt 0.8.0

Tools for working with partially-created Zcash transactions
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
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
//! The Sapling fields of a PCZT.

use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::vec::Vec;
use core::cmp::Ordering;

use getset::Getters;
use serde::{Deserialize, Serialize};
use serde_with::serde_as;

use crate::{
    common::{Global, Zip32Derivation},
    roles::combiner::{merge_map, merge_optional},
};

const GROTH_PROOF_SIZE: usize = 48 + 96 + 48;

/// PCZT fields that are specific to producing the transaction's Sapling bundle (if any).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Getters)]
pub struct Bundle {
    #[getset(get = "pub")]
    pub(crate) spends: Vec<Spend>,
    #[getset(get = "pub")]
    pub(crate) outputs: Vec<Output>,

    /// The net value of Sapling spends minus outputs.
    ///
    /// This is initialized by the Creator, and updated by the Constructor as spends or
    /// outputs are added to the PCZT. It enables per-spend and per-output values to be
    /// redacted from the PCZT after they are no longer necessary.
    #[getset(get = "pub")]
    pub(crate) value_sum: i128,

    /// The Sapling anchor for this transaction.
    ///
    /// Set by the Creator.
    #[getset(get = "pub")]
    pub(crate) anchor: Option<[u8; 32]>,

    /// The Sapling binding signature signing key.
    ///
    /// - This is `None` until it is set by the IO Finalizer.
    /// - The Transaction Extractor uses this to produce the binding signature.
    pub(crate) bsk: Option<[u8; 32]>,
}

/// The canonical empty Sapling bundle: the form the Sapling bundle of a PCZT takes
/// when it carries no Sapling data.
pub(crate) const EMPTY_BUNDLE: Bundle = Bundle {
    spends: Vec::new(),
    outputs: Vec::new(),
    value_sum: 0,
    anchor: None,
    bsk: None,
};

/// The default anchor used as a parse-time placeholder for redacted empty
/// Sapling bundles.
pub(crate) const DEFAULT_ANCHOR: [u8; 32] = [0; 32];

/// Information about a Sapling spend within a transaction.
#[serde_as]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Getters)]
pub struct Spend {
    //
    // SpendDescription effecting data.
    //
    // These are required fields that are part of the final transaction, and are filled in
    // by the Constructor when adding an output.
    //
    #[getset(get = "pub")]
    pub(crate) cv: [u8; 32],
    #[getset(get = "pub")]
    pub(crate) nullifier: [u8; 32],
    #[getset(get = "pub")]
    pub(crate) rk: [u8; 32],

    /// The Spend proof.
    ///
    /// This is set by the Prover.
    #[serde_as(as = "Option<[_; GROTH_PROOF_SIZE]>")]
    pub(crate) zkproof: Option<[u8; GROTH_PROOF_SIZE]>,

    /// The spend authorization signature.
    ///
    /// This is set by the Signer.
    #[serde_as(as = "Option<[_; 64]>")]
    pub(crate) spend_auth_sig: Option<[u8; 64]>,

    /// The [raw encoding] of the Sapling payment address that received the note being spent.
    ///
    /// - This is set by the Constructor.
    /// - This is required by the Prover.
    ///
    /// [raw encoding]: https://zips.z.cash/protocol/protocol.pdf#saplingpaymentaddrencoding
    #[serde_as(as = "Option<[_; 43]>")]
    pub(crate) recipient: Option<[u8; 43]>,

    /// The value of the input being spent.
    ///
    /// This may be used by Signers to verify that the value matches `cv`, and to confirm
    /// the values and change involved in the transaction.
    ///
    /// This exposes the input value to all participants. For Signers who don't need this
    /// information, or after signatures have been applied, this can be redacted.
    pub(crate) value: Option<u64>,

    /// The note commitment randomness.
    ///
    /// - This is set by the Constructor. It MUST NOT be set if the note has an `rseed`
    ///   (i.e. was created after [ZIP 212] activation).
    /// - The Prover requires either this or `rseed`.
    ///
    /// [ZIP 212]: https://zips.z.cash/zip-0212
    pub(crate) rcm: Option<[u8; 32]>,

    /// The seed randomness for the note being spent.
    ///
    /// - This is set by the Constructor. It MUST NOT be set if the note has no `rseed`
    ///   (i.e. was created before [ZIP 212] activation).
    /// - The Prover requires either this or `rcm`.
    ///
    /// [ZIP 212]: https://zips.z.cash/zip-0212
    pub(crate) rseed: Option<[u8; 32]>,

    /// The value commitment randomness.
    ///
    /// - This is set by the Constructor.
    /// - The IO Finalizer compresses it into `bsk`.
    /// - This is required by the Prover.
    /// - This may be used by Signers to verify that the value correctly matches `cv`.
    ///
    /// This opens `cv` for all participants. For Signers who don't need this information,
    /// or after proofs / signatures have been applied, this can be redacted.
    pub(crate) rcv: Option<[u8; 32]>,

    /// The proof generation key `(ak, nsk)` corresponding to the recipient that received
    /// the note being spent.
    ///
    /// - This is set by the Updater.
    /// - This is required by the Prover.
    pub(crate) proof_generation_key: Option<([u8; 32], [u8; 32])>,

    /// A witness from the note to the bundle's anchor.
    ///
    /// - This is set by the Updater.
    /// - This is required by the Prover.
    pub(crate) witness: Option<(u32, [[u8; 32]; 32])>,

    /// The spend authorization randomizer.
    ///
    /// - This is chosen by the Constructor.
    /// - This is required by the Signer for creating `spend_auth_sig`, and may be used to
    ///   validate `rk`.
    /// - After `zkproof` / `spend_auth_sig` has been set, this can be redacted.
    pub(crate) alpha: Option<[u8; 32]>,

    /// The ZIP 32 derivation path at which the spending key can be found for the note
    /// being spent.
    pub(crate) zip32_derivation: Option<Zip32Derivation>,

    /// The spend authorizing key for this spent note, if it is a dummy note.
    ///
    /// - This is chosen by the Constructor.
    /// - This is required by the IO Finalizer, and is cleared by it once used.
    /// - Signers MUST reject PCZTs that contain `dummy_ask` values.
    pub(crate) dummy_ask: Option<[u8; 32]>,

    /// Proprietary fields related to the note being spent.
    #[getset(get = "pub")]
    pub(crate) proprietary: BTreeMap<String, Vec<u8>>,
}

/// Information about a Sapling output within a transaction.
#[serde_as]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Getters)]
pub struct Output {
    //
    // OutputDescription effecting data.
    //
    // These are required fields that are part of the final transaction, and are filled in
    // by the Constructor when adding an output.
    //
    #[getset(get = "pub")]
    pub(crate) cv: [u8; 32],
    #[getset(get = "pub")]
    pub(crate) cmu: [u8; 32],
    #[getset(get = "pub")]
    pub(crate) ephemeral_key: [u8; 32],
    /// The encrypted note plaintext for the output.
    ///
    /// Encoded as a `Vec<u8>` because its length depends on the transaction version.
    ///
    /// Once we have [memo bundles], we will be able to set memos independently of
    /// Outputs. For now, the Constructor sets both at the same time.
    ///
    /// [memo bundles]: https://zips.z.cash/zip-0231
    #[getset(get = "pub")]
    pub(crate) enc_ciphertext: Vec<u8>,
    /// The encrypted note plaintext for the output.
    ///
    /// Encoded as a `Vec<u8>` because its length depends on the transaction version.
    #[getset(get = "pub")]
    pub(crate) out_ciphertext: Vec<u8>,

    /// The Output proof.
    ///
    /// This is set by the Prover.
    #[serde_as(as = "Option<[_; GROTH_PROOF_SIZE]>")]
    pub(crate) zkproof: Option<[u8; GROTH_PROOF_SIZE]>,

    /// The [raw encoding] of the Sapling payment address that will receive the output.
    ///
    /// - This is set by the Constructor.
    /// - This is required by the Prover.
    ///
    /// [raw encoding]: https://zips.z.cash/protocol/protocol.pdf#saplingpaymentaddrencoding
    #[serde_as(as = "Option<[_; 43]>")]
    #[getset(get = "pub")]
    pub(crate) recipient: Option<[u8; 43]>,

    /// The value of the output.
    ///
    /// This may be used by Signers to verify that the value matches `cv`, and to confirm
    /// the values and change involved in the transaction.
    ///
    /// This exposes the output value to all participants. For Signers who don't need this
    /// information, or after signatures have been applied, this can be redacted.
    #[getset(get = "pub")]
    pub(crate) value: Option<u64>,

    /// The seed randomness for the output.
    ///
    /// - This is set by the Constructor.
    /// - This is required by the Prover, instead of disclosing `shared_secret` to them.
    #[getset(get = "pub")]
    pub(crate) rseed: Option<[u8; 32]>,

    /// The value commitment randomness.
    ///
    /// - This is set by the Constructor.
    /// - The IO Finalizer compresses it into `bsk`.
    /// - This is required by the Prover.
    /// - This may be used by Signers to verify that the value correctly matches `cv`.
    ///
    /// This opens `cv` for all participants. For Signers who don't need this information,
    /// or after proofs / signatures have been applied, this can be redacted.
    pub(crate) rcv: Option<[u8; 32]>,

    /// The `ock` value used to encrypt `out_ciphertext`.
    ///
    /// This enables Signers to verify that `out_ciphertext` is correctly encrypted.
    ///
    /// This may be `None` if the Constructor added the output using an OVK policy of
    /// "None", to make the output unrecoverable from the chain by the sender.
    pub(crate) ock: Option<[u8; 32]>,

    /// The ZIP 32 derivation path at which the spending key can be found for the output.
    pub(crate) zip32_derivation: Option<Zip32Derivation>,

    /// The user-facing address to which this output is being sent, if any.
    ///
    /// - This is set by an Updater.
    /// - Signers must parse this address (if present) and confirm that it contains
    ///   `recipient` (either directly, or e.g. as a receiver within a Unified Address).
    #[getset(get = "pub")]
    pub(crate) user_address: Option<String>,

    /// Proprietary fields related to the note being spent.
    #[getset(get = "pub")]
    pub(crate) proprietary: BTreeMap<String, Vec<u8>>,
}

impl Bundle {
    /// Merges this bundle with another.
    ///
    /// Returns `None` if the bundles have conflicting data.
    pub(crate) fn merge(
        mut self,
        other: Self,
        self_global: &Global,
        other_global: &Global,
    ) -> Option<Self> {
        // Destructure `other` to ensure we handle everything.
        let Self {
            mut spends,
            mut outputs,
            value_sum,
            anchor,
            bsk,
        } = other;

        // If `bsk` is set on either bundle, the IO Finalizer has run, which means we
        // cannot have differing numbers of spends or outputs, and the value balances must
        // match.
        match (self.bsk.as_mut(), bsk) {
            (Some(lhs), Some(rhs)) if lhs != &rhs => return None,
            (Some(_), _) | (_, Some(_))
                if self.spends.len() != spends.len()
                    || self.outputs.len() != outputs.len()
                    || self.value_sum != value_sum =>
            {
                return None;
            }
            // IO Finalizer has run, and neither bundle has excess spends or outputs.
            (Some(_), _) | (_, Some(_)) => (),
            // IO Finalizer has not run on either bundle.
            (None, None) => {
                let (spends_cmp_other, outputs_cmp_other) = match (
                    self.spends.len().cmp(&spends.len()),
                    self.outputs.len().cmp(&outputs.len()),
                ) {
                    // These cases require us to recalculate the value sum, which we can't
                    // do without a parsed bundle.
                    (Ordering::Less, Ordering::Greater) | (Ordering::Greater, Ordering::Less) => {
                        return None;
                    }
                    // These cases mean that at least one of the two value sums is correct
                    // and we can use it directly.
                    (spends, outputs) => (spends, outputs),
                };

                match (
                    self_global.shielded_modifiable(),
                    other_global.shielded_modifiable(),
                    spends_cmp_other,
                ) {
                    // Fail if the merge would add spends to a non-modifiable bundle.
                    (false, _, Ordering::Less) | (_, false, Ordering::Greater) => return None,
                    // If the other bundle has more spends than us, move them over; these cannot
                    // conflict by construction.
                    (true, _, Ordering::Less) => {
                        self.spends.extend(spends.drain(self.spends.len()..))
                    }
                    // Do nothing otherwise.
                    (_, _, Ordering::Equal) | (_, true, Ordering::Greater) => (),
                }

                match (
                    self_global.shielded_modifiable(),
                    other_global.shielded_modifiable(),
                    outputs_cmp_other,
                ) {
                    // Fail if the merge would add outputs to a non-modifiable bundle.
                    (false, _, Ordering::Less) | (_, false, Ordering::Greater) => return None,
                    // If the other bundle has more outputs than us, move them over; these cannot
                    // conflict by construction.
                    (true, _, Ordering::Less) => {
                        self.outputs.extend(outputs.drain(self.outputs.len()..))
                    }
                    // Do nothing otherwise.
                    (_, _, Ordering::Equal) | (_, true, Ordering::Greater) => (),
                }

                if matches!(spends_cmp_other, Ordering::Less)
                    || matches!(outputs_cmp_other, Ordering::Less)
                {
                    // We check below that the overlapping spends and outputs match.
                    // Assuming here that they will, we take the other bundle's value sum.
                    self.value_sum = value_sum;
                }
            }
        }

        if !merge_optional(&mut self.anchor, anchor) {
            return None;
        }

        // Leverage the early-exit behaviour of zip to confirm that the remaining data in
        // the other bundle matches this one.
        for (lhs, rhs) in self.spends.iter_mut().zip(spends) {
            // Destructure `rhs` to ensure we handle everything.
            let Spend {
                cv,
                nullifier,
                rk,
                zkproof,
                spend_auth_sig,
                recipient,
                value,
                rcm,
                rseed,
                rcv,
                proof_generation_key,
                witness,
                alpha,
                zip32_derivation,
                dummy_ask,
                proprietary,
            } = rhs;

            if lhs.cv != cv || lhs.nullifier != nullifier || lhs.rk != rk {
                return None;
            }

            if !(merge_optional(&mut lhs.zkproof, zkproof)
                && merge_optional(&mut lhs.spend_auth_sig, spend_auth_sig)
                && merge_optional(&mut lhs.recipient, recipient)
                && merge_optional(&mut lhs.value, value)
                && merge_optional(&mut lhs.rcm, rcm)
                && merge_optional(&mut lhs.rseed, rseed)
                && merge_optional(&mut lhs.rcv, rcv)
                && merge_optional(&mut lhs.proof_generation_key, proof_generation_key)
                && merge_optional(&mut lhs.witness, witness)
                && merge_optional(&mut lhs.alpha, alpha)
                && merge_optional(&mut lhs.zip32_derivation, zip32_derivation)
                && merge_optional(&mut lhs.dummy_ask, dummy_ask)
                && merge_map(&mut lhs.proprietary, proprietary))
            {
                return None;
            }
        }

        for (lhs, rhs) in self.outputs.iter_mut().zip(outputs) {
            // Destructure `rhs` to ensure we handle everything.
            let Output {
                cv,
                cmu,
                ephemeral_key,
                enc_ciphertext,
                out_ciphertext,
                zkproof,
                recipient,
                value,
                rseed,
                rcv,
                ock,
                zip32_derivation,
                user_address,
                proprietary,
            } = rhs;

            if lhs.cv != cv
                || lhs.cmu != cmu
                || lhs.ephemeral_key != ephemeral_key
                || lhs.enc_ciphertext != enc_ciphertext
                || lhs.out_ciphertext != out_ciphertext
            {
                return None;
            }

            if !(merge_optional(&mut lhs.zkproof, zkproof)
                && merge_optional(&mut lhs.recipient, recipient)
                && merge_optional(&mut lhs.value, value)
                && merge_optional(&mut lhs.rseed, rseed)
                && merge_optional(&mut lhs.rcv, rcv)
                && merge_optional(&mut lhs.ock, ock)
                && merge_optional(&mut lhs.zip32_derivation, zip32_derivation)
                && merge_optional(&mut lhs.user_address, user_address)
                && merge_map(&mut lhs.proprietary, proprietary))
            {
                return None;
            }
        }

        Some(self)
    }
}

/// Types for the v1 Sapling PCZT encoding.
pub(crate) mod v1 {
    use alloc::vec::Vec;

    use serde::{Deserialize, Serialize};

    /// PCZT fields that are specific to producing the transaction's Sapling
    /// bundle.
    #[derive(Clone, Debug, Serialize, Deserialize)]
    pub(crate) struct Bundle {
        spends: Vec<super::Spend>,
        outputs: Vec<super::Output>,
        value_sum: i128,
        anchor: [u8; 32],
        bsk: Option<[u8; 32]>,
    }

    impl TryFrom<super::Bundle> for Bundle {
        type Error = crate::EncodingError;

        fn try_from(bundle: super::Bundle) -> Result<Self, Self::Error> {
            let anchor = match bundle.anchor {
                Some(anchor) => anchor,
                None if bundle.spends.is_empty() => super::DEFAULT_ANCHOR,
                None => return Err(crate::EncodingError::RequiresV2),
            };

            Ok(Self {
                spends: bundle.spends,
                outputs: bundle.outputs,
                value_sum: bundle.value_sum,
                anchor,
                bsk: bundle.bsk,
            })
        }
    }

    impl From<Bundle> for super::Bundle {
        fn from(bundle: Bundle) -> Self {
            Self {
                spends: bundle.spends,
                outputs: bundle.outputs,
                value_sum: bundle.value_sum,
                anchor: Some(bundle.anchor),
                bsk: bundle.bsk,
            }
        }
    }
}

/// Types and operations for the v2 Sapling PCZT encoding.
pub(crate) mod v2 {
    /// Encodes a logical Sapling bundle for the v2 PCZT format, owning the
    /// decision of whether the bundle can be omitted. A bundle that is exactly
    /// equal to [`super::EMPTY_BUNDLE`] serializes to `None` and is dropped from
    /// the encoding. An otherwise-empty bundle carrying
    /// [`super::DEFAULT_ANCHOR`] is treated as empty for this purpose.
    pub(crate) fn encode(bundle: super::Bundle) -> Option<super::Bundle> {
        (!is_default_empty(&bundle)).then_some(bundle)
    }

    fn is_default_empty(bundle: &super::Bundle) -> bool {
        let mut bundle = bundle.clone();
        if bundle.anchor == Some(super::DEFAULT_ANCHOR) {
            bundle.anchor = None;
        }

        bundle == super::EMPTY_BUNDLE
    }
}

#[cfg(feature = "sapling")]
impl Bundle {
    /// Parses this bundle into the form used by the `sapling` crate.
    ///
    /// If the bundle's `anchor` is absent and `anchor_requirement` is
    /// [`AnchorRequirement::Required`], returns [`ParseError::MissingAnchor`] unless the
    /// bundle has no spends or outputs (in which case there is nothing to prove or
    /// extract).
    ///
    /// [`AnchorRequirement::Required`]: crate::common::AnchorRequirement::Required
    pub(crate) fn into_parsed(
        self,
        anchor_requirement: crate::common::AnchorRequirement,
    ) -> Result<Parsed, ParseError> {
        let wire_anchor = self.anchor;
        let anchor = anchor_requirement
            .resolve(
                wire_anchor,
                self.spends.is_empty() && self.outputs.is_empty(),
            )
            .ok_or(ParseError::MissingAnchor)?;

        let spends = self
            .spends
            .into_iter()
            .map(|spend| {
                sapling::pczt::Spend::parse(
                    spend.cv,
                    spend.nullifier,
                    spend.rk,
                    spend.zkproof,
                    spend.spend_auth_sig,
                    spend.recipient,
                    spend.value,
                    spend.rcm,
                    spend.rseed,
                    spend.rcv,
                    spend.proof_generation_key,
                    spend.witness,
                    spend.alpha,
                    spend
                        .zip32_derivation
                        .map(|z| {
                            sapling::pczt::Zip32Derivation::parse(
                                z.seed_fingerprint,
                                z.derivation_path,
                            )
                        })
                        .transpose()?,
                    spend.dummy_ask,
                    spend.proprietary,
                )
            })
            .collect::<Result<_, _>>()?;

        let outputs = self
            .outputs
            .into_iter()
            .map(|output| {
                sapling::pczt::Output::parse(
                    output.cv,
                    output.cmu,
                    output.ephemeral_key,
                    output.enc_ciphertext,
                    output.out_ciphertext,
                    output.zkproof,
                    output.recipient,
                    output.value,
                    output.rseed,
                    output.rcv,
                    output.ock,
                    output
                        .zip32_derivation
                        .map(|z| {
                            sapling::pczt::Zip32Derivation::parse(
                                z.seed_fingerprint,
                                z.derivation_path,
                            )
                        })
                        .transpose()?,
                    output.user_address,
                    output.proprietary,
                )
            })
            .collect::<Result<_, _>>()?;

        let bundle =
            sapling::pczt::Bundle::parse(spends, outputs, self.value_sum, anchor, self.bsk)?;

        Ok(Parsed {
            bundle,
            wire_anchor,
        })
    }

    pub(crate) fn serialize_from(bundle: sapling::pczt::Bundle) -> Self {
        let spends = bundle
            .spends()
            .iter()
            .map(|spend| {
                let (rcm, rseed) = match spend.rseed() {
                    Some(sapling::Rseed::BeforeZip212(rcm)) => (Some(rcm.to_bytes()), None),
                    Some(sapling::Rseed::AfterZip212(rseed)) => (None, Some(*rseed)),
                    None => (None, None),
                };

                Spend {
                    cv: spend.cv().to_bytes(),
                    nullifier: spend.nullifier().0,
                    rk: (*spend.rk()).into(),
                    zkproof: *spend.zkproof(),
                    spend_auth_sig: spend.spend_auth_sig().map(|s| s.into()),
                    recipient: spend.recipient().map(|recipient| recipient.to_bytes()),
                    value: spend.value().map(|value| value.inner()),
                    rcm,
                    rseed,
                    rcv: spend.rcv().as_ref().map(|rcv| rcv.inner().to_bytes()),
                    proof_generation_key: spend
                        .proof_generation_key()
                        .as_ref()
                        .map(|key| (key.ak.to_bytes(), key.nsk.to_bytes())),
                    witness: spend.witness().as_ref().map(|witness| {
                        (
                            u32::try_from(u64::from(witness.position()))
                                .expect("Sapling positions fit in u32"),
                            witness
                                .path_elems()
                                .iter()
                                .map(|node| node.to_bytes())
                                .collect::<Vec<_>>()[..]
                                .try_into()
                                .expect("path is length 32"),
                        )
                    }),
                    alpha: spend.alpha().map(|alpha| alpha.to_bytes()),
                    zip32_derivation: spend.zip32_derivation().as_ref().map(|z| Zip32Derivation {
                        seed_fingerprint: *z.seed_fingerprint(),
                        derivation_path: z.derivation_path().iter().map(|i| i.index()).collect(),
                    }),
                    dummy_ask: spend
                        .dummy_ask()
                        .as_ref()
                        .map(|dummy_ask| dummy_ask.to_bytes()),
                    proprietary: spend.proprietary().clone(),
                }
            })
            .collect();

        let outputs = bundle
            .outputs()
            .iter()
            .map(|output| Output {
                cv: output.cv().to_bytes(),
                cmu: output.cmu().to_bytes(),
                ephemeral_key: output.ephemeral_key().0,
                enc_ciphertext: output.enc_ciphertext().to_vec(),
                out_ciphertext: output.out_ciphertext().to_vec(),
                zkproof: *output.zkproof(),
                recipient: output.recipient().map(|recipient| recipient.to_bytes()),
                value: output.value().map(|value| value.inner()),
                rseed: *output.rseed(),
                rcv: output.rcv().as_ref().map(|rcv| rcv.inner().to_bytes()),
                ock: output.ock().as_ref().map(|ock| ock.0),
                zip32_derivation: output.zip32_derivation().as_ref().map(|z| Zip32Derivation {
                    seed_fingerprint: *z.seed_fingerprint(),
                    derivation_path: z.derivation_path().iter().map(|i| i.index()).collect(),
                }),
                user_address: output.user_address().clone(),
                proprietary: output.proprietary().clone(),
            })
            .collect();

        Self {
            spends,
            outputs,
            value_sum: bundle.value_sum().to_raw(),
            anchor: Some(bundle.anchor().to_bytes()),
            bsk: bundle.bsk().map(|bsk| bsk.into()),
        }
    }
}

/// Errors that can occur while parsing a Sapling bundle into the form used by
/// the `sapling` crate.
#[cfg(feature = "sapling")]
#[derive(Debug)]
#[non_exhaustive]
pub enum ParseError {
    /// The operation requires the bundle's `anchor` to be set, but it was absent.
    ///
    /// For a v6 transaction, an Updater can resolve this by setting the anchor; see
    /// [ZIP 374: Anchors and pre-authorization](https://zips.z.cash/zip-0374#anchors-and-pre-authorization).
    MissingAnchor,
    /// The bundle's remaining fields were structurally invalid.
    Bundle(sapling::pczt::ParseError),
}

#[cfg(feature = "sapling")]
impl From<sapling::pczt::ParseError> for ParseError {
    fn from(e: sapling::pczt::ParseError) -> Self {
        ParseError::Bundle(e)
    }
}

/// Errors that can occur while checking that a Sapling bundle's spend witnesses are
/// consistent with its anchor.
#[cfg(all(feature = "sapling", feature = "prover"))]
#[derive(Debug)]
#[non_exhaustive]
pub enum AnchorConsistencyError {
    /// A non-zero-valued spend has a `witness` but is missing other note data required
    /// to compute its Merkle path root.
    IncompleteSpendData,
    /// A non-zero-valued spend's `witness` does not root to the given anchor.
    WitnessDoesNotRootToAnchor,
}

/// Checks that every non-zero-valued spend in `bundle` whose `witness` is present has a
/// Merkle path that roots to `anchor` (\[ZIP 374\] "Anchors and pre-authorization").
///
/// Zero-valued spends are skipped, as their Merkle paths are not checked by the Sapling
/// circuit.
///
/// [ZIP 374]: https://zips.z.cash/zip-0374#anchors-and-pre-authorization
#[cfg(all(feature = "sapling", feature = "prover"))]
pub(crate) fn verify_witnesses_root_to_anchor(
    bundle: &sapling::pczt::Bundle,
    anchor: sapling::Anchor,
) -> Result<(), AnchorConsistencyError> {
    for spend in bundle.spends() {
        let Some(witness) = spend.witness() else {
            continue;
        };
        let Some(value) = spend.value() else {
            continue;
        };
        if value.inner() == 0 {
            continue;
        }

        let recipient = spend
            .recipient()
            .ok_or(AnchorConsistencyError::IncompleteSpendData)?;
        let rseed = (*spend.rseed()).ok_or(AnchorConsistencyError::IncompleteSpendData)?;

        let note = sapling::Note::from_parts(recipient, *value, rseed);
        let leaf = sapling::Node::from_cmu(&note.cmu());
        let computed_anchor: sapling::Anchor = witness.root(leaf).into();

        if computed_anchor != anchor {
            return Err(AnchorConsistencyError::WitnessDoesNotRootToAnchor);
        }
    }

    Ok(())
}

/// The result of parsing a Sapling bundle via [`Bundle::into_parsed`].
///
/// Carries the bundle's original wire `anchor` alongside the parsed form, so that
/// [`Parsed::reserialize`] can restore it after an operation that does not itself
/// change the anchor, even though parsing may have substituted a placeholder for it
/// (see [ZIP 374: Anchors and pre-authorization](https://zips.z.cash/zip-0374#anchors-and-pre-authorization)).
#[cfg(feature = "sapling")]
pub(crate) struct Parsed {
    pub(crate) bundle: sapling::pczt::Bundle,
    pub(crate) wire_anchor: Option<[u8; 32]>,
}

#[cfg(feature = "sapling")]
impl Parsed {
    /// Serializes the parsed bundle back into its wire representation, using
    /// [`Self::wire_anchor`] as the result's `anchor` in place of any placeholder
    /// substituted while parsing.
    ///
    /// Must not be used after an operation that legitimately changes the anchor;
    /// such operations should set `wire_anchor` to the new value first.
    pub(crate) fn reserialize(self) -> Bundle {
        Bundle {
            anchor: self.wire_anchor,
            ..Bundle::serialize_from(self.bundle)
        }
    }
}

#[cfg(all(test, feature = "sapling"))]
mod tests {
    use rand_chacha::{ChaCha20Rng, rand_core::SeedableRng};

    use super::{Bundle, ParseError};
    use crate::common::AnchorRequirement;

    fn output_only_bundle() -> Bundle {
        let recipient = sapling::zip32::ExtendedSpendingKey::master(&[0; 32])
            .to_diversifiable_full_viewing_key()
            .default_address()
            .1;
        let mut builder = sapling::builder::Builder::new(
            sapling::note_encryption::Zip212Enforcement::On,
            sapling::builder::BundleType::DEFAULT,
            sapling::Anchor::empty_tree(),
        );
        builder
            .add_output(
                None,
                recipient,
                sapling::value::NoteValue::from_raw(1),
                [0; 512],
            )
            .unwrap();
        let (bundle, _) = builder
            .build_for_pczt(ChaCha20Rng::from_seed([0; 32]))
            .unwrap();
        let mut bundle = Bundle::serialize_from(bundle);
        bundle.anchor = None;
        bundle
    }

    #[test]
    fn output_only_bundle_requires_anchor_when_required() {
        assert!(matches!(
            output_only_bundle().into_parsed(AnchorRequirement::Required),
            Err(ParseError::MissingAnchor)
        ));
    }

    #[test]
    fn output_only_bundle_preserves_absent_anchor_when_not_required() {
        let bundle = output_only_bundle();
        let output_count = bundle.outputs.len();

        let parsed = bundle.into_parsed(AnchorRequirement::NotRequired).unwrap();
        assert!(parsed.bundle.spends().is_empty());
        assert_eq!(parsed.bundle.outputs().len(), output_count);

        let reserialized = parsed.reserialize();
        assert!(reserialized.anchor.is_none());
        assert_eq!(reserialized.outputs.len(), output_count);
    }
}