zebra-chain 14.0.0

Core Zcash data structures
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
//! Contains impls of `ZcashSerialize`, `ZcashDeserialize` for all of the
//! transaction types, so that all of the serialization logic is in one place.

use std::{borrow::Borrow, io, sync::Arc};

use halo2::pasta::{group::ff::PrimeField, pallas};
use hex::FromHex;

use crate::{
    block::MAX_BLOCK_BYTES,
    primitives::ZkSnarkProof,
    serialization::{
        ReadZcashExt, SerializationError, TrustedPreallocate, ZcashDeserialize,
        ZcashDeserializeInto, ZcashSerialize,
    },
};

use super::*;
use crate::sprout;

// Only the test-gated shielded-data codecs below need these.
#[cfg(any(test, feature = "proptest-impl"))]
use crate::{
    amount, ironwood, orchard,
    primitives::Halo2Proof,
    sapling,
    serialization::{
        zcash_deserialize_external_count, zcash_serialize_empty_list,
        zcash_serialize_external_count, AtLeastOne, CompactSizeMessage,
    },
};
#[cfg(any(test, feature = "proptest-impl"))]
use reddsa::{orchard::Binding, orchard::SpendAuth, Signature};

impl ZcashDeserialize for jubjub::Fq {
    fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
        let possible_scalar = jubjub::Fq::from_bytes(&reader.read_32_bytes()?);

        if possible_scalar.is_some().into() {
            Ok(possible_scalar.unwrap())
        } else {
            Err(SerializationError::Parse(
                "Invalid jubjub::Fq, input not canonical",
            ))
        }
    }
}

impl ZcashDeserialize for pallas::Scalar {
    fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
        let possible_scalar = pallas::Scalar::from_repr(reader.read_32_bytes()?);

        if possible_scalar.is_some().into() {
            Ok(possible_scalar.unwrap())
        } else {
            Err(SerializationError::Parse(
                "Invalid pallas::Scalar, input not canonical",
            ))
        }
    }
}

impl ZcashDeserialize for pallas::Base {
    fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
        let possible_field_element = pallas::Base::from_repr(reader.read_32_bytes()?);

        if possible_field_element.is_some().into() {
            Ok(possible_field_element.unwrap())
        } else {
            Err(SerializationError::Parse(
                "Invalid pallas::Base, input not canonical",
            ))
        }
    }
}

impl<P: ZkSnarkProof> ZcashSerialize for JoinSplitData<P> {
    fn zcash_serialize<W: io::Write>(&self, mut writer: W) -> Result<(), io::Error> {
        // Denoted as `nJoinSplit` and `vJoinSplit` in the spec.
        let joinsplits: Vec<_> = self.joinsplits().cloned().collect();
        joinsplits.zcash_serialize(&mut writer)?;

        // Denoted as `joinSplitPubKey` in the spec.
        writer.write_all(&<[u8; 32]>::from(self.pub_key)[..])?;

        // Denoted as `joinSplitSig` in the spec.
        writer.write_all(&<[u8; 64]>::from(self.sig)[..])?;
        Ok(())
    }
}

impl<P> ZcashDeserialize for Option<JoinSplitData<P>>
where
    P: ZkSnarkProof,
    sprout::JoinSplit<P>: TrustedPreallocate,
{
    fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
        // Denoted as `nJoinSplit` and `vJoinSplit` in the spec.
        let joinsplits: Vec<sprout::JoinSplit<P>> = (&mut reader).zcash_deserialize_into()?;
        match joinsplits.split_first() {
            None => Ok(None),
            Some((first, rest)) => {
                // Denoted as `joinSplitPubKey` in the spec.
                let pub_key = reader.read_32_bytes()?.into();
                // Denoted as `joinSplitSig` in the spec.
                let sig = reader.read_64_bytes()?.into();
                Ok(Some(JoinSplitData {
                    first: first.clone(),
                    rest: rest.to_vec(),
                    pub_key,
                    sig,
                }))
            }
        }
    }
}

// Serialization for Zebra's own shielded-data types.
//
// Production transaction serialization goes through `zcash_primitives`, which owns the wire
// format for every shielded pool (see the `ZcashSerialize`/`ZcashDeserialize` impls for
// `Transaction`). The codecs below operate on Zebra's `sapling`/`orchard`/`ironwood`
// shielded-data structs, which no production path serializes, so they are compiled only for
// tests. Gating them keeps a second copy of the wire format out of release builds and makes it
// unambiguous which encoder consensus depends on.

#[cfg(any(test, feature = "proptest-impl"))]
impl ZcashSerialize for Option<sapling::ShieldedData<sapling::PerSpendAnchor>> {
    fn zcash_serialize<W: io::Write>(&self, mut writer: W) -> Result<(), io::Error> {
        match self {
            None => {
                zcash_serialize_empty_list(&mut writer)?;
                zcash_serialize_empty_list(&mut writer)?;
            }
            Some(sd) => {
                sd.zcash_serialize(&mut writer)?;
            }
        }
        Ok(())
    }
}

#[cfg(any(test, feature = "proptest-impl"))]
impl ZcashSerialize for sapling::ShieldedData<sapling::PerSpendAnchor> {
    fn zcash_serialize<W: io::Write>(&self, mut writer: W) -> Result<(), io::Error> {
        let spends: Vec<_> = self.spends().cloned().collect();
        let outputs: Vec<_> = self
            .outputs()
            .cloned()
            .map(sapling::Output::into_v4)
            .collect();

        spends.zcash_serialize(&mut writer)?;
        outputs.zcash_serialize(&mut writer)?;
        self.value_balance.zcash_serialize(&mut writer)?;
        writer.write_all(&<[u8; 64]>::from(self.binding_sig)[..])?;
        Ok(())
    }
}

#[cfg(any(test, feature = "proptest-impl"))]
impl ZcashDeserialize for Option<sapling::ShieldedData<sapling::PerSpendAnchor>> {
    fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
        let spends: Vec<sapling::Spend<sapling::PerSpendAnchor>> =
            (&mut reader).zcash_deserialize_into()?;
        let outputs: Vec<sapling::OutputInTransactionV4> =
            (&mut reader).zcash_deserialize_into()?;

        if spends.is_empty() && outputs.is_empty() {
            return Ok(None);
        }

        let value_balance = (&mut reader).zcash_deserialize_into()?;
        let binding_sig = reader.read_64_bytes()?.into();

        let outputs: Vec<sapling::Output> = outputs
            .into_iter()
            .map(sapling::OutputInTransactionV4::into_output)
            .collect();

        let transfers = match spends.split_first() {
            None => sapling::TransferData::JustOutputs {
                outputs: outputs.try_into().map_err(|_| {
                    SerializationError::Parse(
                        "ShieldedData<PerSpendAnchor> with no spends or outputs",
                    )
                })?,
            },
            Some((first, rest)) => sapling::TransferData::SpendsAndMaybeOutputs {
                shared_anchor: sapling::FieldNotPresent,
                spends: std::iter::once(first.clone())
                    .chain(rest.iter().cloned())
                    .collect::<Vec<_>>()
                    .try_into()
                    .map_err(|_| {
                        SerializationError::Parse("ShieldedData<PerSpendAnchor> spend list empty")
                    })?,
                maybe_outputs: outputs,
            },
        };

        Ok(Some(sapling::ShieldedData {
            value_balance,
            transfers,
            binding_sig,
        }))
    }
}

// Transaction::V5 serializes sapling ShieldedData in a single continuous byte
// range, so we can implement its serialization and deserialization separately.
// (Unlike V4, where it must be serialized as part of the transaction.)

#[cfg(any(test, feature = "proptest-impl"))]
impl ZcashSerialize for Option<sapling::ShieldedData<sapling::SharedAnchor>> {
    fn zcash_serialize<W: io::Write>(&self, mut writer: W) -> Result<(), io::Error> {
        match self {
            None => {
                // Denoted as `nSpendsSapling` in the spec.
                zcash_serialize_empty_list(&mut writer)?;
                // Denoted as `nOutputsSapling` in the spec.
                zcash_serialize_empty_list(&mut writer)?;
            }
            Some(sapling_shielded_data) => {
                sapling_shielded_data.zcash_serialize(&mut writer)?;
            }
        }
        Ok(())
    }
}

#[cfg(any(test, feature = "proptest-impl"))]
impl ZcashSerialize for sapling::ShieldedData<sapling::SharedAnchor> {
    fn zcash_serialize<W: io::Write>(&self, mut writer: W) -> Result<(), io::Error> {
        // Collect arrays for Spends
        // There's no unzip3, so we have to unzip twice.
        let (spend_prefixes, spend_proofs_sigs): (Vec<_>, Vec<_>) = self
            .spends()
            .cloned()
            .map(sapling::Spend::<sapling::SharedAnchor>::into_v5_parts)
            .map(|(prefix, proof, sig)| (prefix, (proof, sig)))
            .unzip();
        let (spend_proofs, spend_sigs) = spend_proofs_sigs.into_iter().unzip();

        // Collect arrays for Outputs
        let (output_prefixes, output_proofs): (Vec<_>, _) = self
            .outputs()
            .cloned()
            .map(sapling::Output::into_v5_parts)
            .unzip();

        // Denoted as `nSpendsSapling` and `vSpendsSapling` in the spec.
        spend_prefixes.zcash_serialize(&mut writer)?;
        // Denoted as `nOutputsSapling` and `vOutputsSapling` in the spec.
        output_prefixes.zcash_serialize(&mut writer)?;

        // Denoted as `valueBalanceSapling` in the spec.
        self.value_balance.zcash_serialize(&mut writer)?;

        // Denoted as `anchorSapling` in the spec.
        // `TransferData` ensures this field is only present when there is at
        // least one spend.
        if let Some(shared_anchor) = self.shared_anchor() {
            writer.write_all(&<[u8; 32]>::from(shared_anchor)[..])?;
        }

        // Denoted as `vSpendProofsSapling` in the spec.
        zcash_serialize_external_count(&spend_proofs, &mut writer)?;
        // Denoted as `vSpendAuthSigsSapling` in the spec.
        zcash_serialize_external_count(&spend_sigs, &mut writer)?;

        // Denoted as `vOutputProofsSapling` in the spec.
        zcash_serialize_external_count(&output_proofs, &mut writer)?;

        // Denoted as `bindingSigSapling` in the spec.
        writer.write_all(&<[u8; 64]>::from(self.binding_sig)[..])?;

        Ok(())
    }
}

// we can't split ShieldedData out of Option<ShieldedData> deserialization,
// because the counts are read along with the arrays.
#[cfg(any(test, feature = "proptest-impl"))]
impl ZcashDeserialize for Option<sapling::ShieldedData<sapling::SharedAnchor>> {
    #[allow(clippy::unwrap_in_result)]
    fn zcash_deserialize<R: io::Read>(reader: R) -> Result<Self, SerializationError> {
        deserialize_v5_sapling_shielded_data(reader, false)
    }
}

/// Deserialize V5/V6 Sapling shielded data with an optional early coinbase
/// rejection.
///
/// When `is_coinbase` is true, a non-zero `nSpendsSapling` count is rejected
/// **before** allocating the spend vector, closing the late-validation gap
/// described in GHSA-rgwx-8r98-p34c.
#[allow(clippy::unwrap_in_result)]
#[cfg(any(test, feature = "proptest-impl"))]
fn deserialize_v5_sapling_shielded_data<R: io::Read>(
    mut reader: R,
    is_coinbase: bool,
) -> Result<Option<sapling::ShieldedData<sapling::SharedAnchor>>, SerializationError> {
    // Denoted as `nSpendsSapling` in the spec — read count before allocating.
    let spend_count: CompactSizeMessage = (&mut reader).zcash_deserialize_into()?;
    let spend_count: usize = spend_count.into();

    // # Consensus
    //
    // > A coinbase transaction MUST NOT have any Spend descriptions.
    //
    // <https://zips.z.cash/protocol/protocol.pdf#txnconsensus>
    //
    // Reject before allocating to prevent a peer from forcing thousands of
    // spend-prefix allocations for a transaction that will always be invalid.
    if is_coinbase && spend_count > 0 {
        return Err(SerializationError::Parse(
            "coinbase transaction must not have Sapling spends",
        ));
    }

    // Denoted as `vSpendsSapling` in the spec.
    let spend_prefixes: Vec<sapling::SpendPrefixInTransactionV5> =
        zcash_deserialize_external_count(spend_count, &mut reader)?;

    // Denoted as `nOutputsSapling` and `vOutputsSapling` in the spec.
    let output_prefixes: Vec<_> = (&mut reader).zcash_deserialize_into()?;

    // nSpendsSapling and nOutputsSapling as variables
    let spends_count = spend_prefixes.len();
    let outputs_count = output_prefixes.len();

    // All the other fields depend on having spends or outputs
    if spend_prefixes.is_empty() && output_prefixes.is_empty() {
        return Ok(None);
    }

    // Denoted as `valueBalanceSapling` in the spec.
    let value_balance = (&mut reader).zcash_deserialize_into()?;

    // Denoted as `anchorSapling` in the spec.
    //
    // # Consensus
    //
    // > Elements of a Spend description MUST be valid encodings of the types given above.
    //
    // https://zips.z.cash/protocol/protocol.pdf#spenddesc
    //
    // Type is `B^{[ℓ_{Sapling}_{Merkle}]}`, i.e. 32 bytes
    //
    // > LEOS2IP_{256}(anchorSapling), if present, MUST be less than 𝑞_𝕁.
    //
    // https://zips.z.cash/protocol/protocol.pdf#spendencodingandconsensus
    //
    // Validated in [`crate::sapling::tree::Root::zcash_deserialize`].
    let shared_anchor = if spends_count > 0 {
        Some((&mut reader).zcash_deserialize_into()?)
    } else {
        None
    };

    // Denoted as `vSpendProofsSapling` in the spec.
    //
    // # Consensus
    //
    // > Elements of a Spend description MUST be valid encodings of the types given above.
    //
    // https://zips.z.cash/protocol/protocol.pdf#spenddesc
    //
    // Type is `ZKSpend.Proof`, described in
    // https://zips.z.cash/protocol/protocol.pdf#grothencoding
    // It is not enforced here; this just reads 192 bytes.
    // The type is validated when validating the proof, see
    // [`groth16::Item::try_from`]. In #3179 we plan to validate here instead.
    let spend_proofs = zcash_deserialize_external_count(spends_count, &mut reader)?;

    // Denoted as `vSpendAuthSigsSapling` in the spec.
    //
    // # Consensus
    //
    // > Elements of a Spend description MUST be valid encodings of the types given above.
    //
    // https://zips.z.cash/protocol/protocol.pdf#spenddesc
    //
    // Type is SpendAuthSig^{Sapling}.Signature, i.e.
    // B^Y^{[ceiling(ℓ_G/8) + ceiling(bitlength(𝑟_G)/8)]} i.e. 64 bytes
    // https://zips.z.cash/protocol/protocol.pdf#concretereddsa
    // See [`redjubjub::Signature<SpendAuth>::zcash_deserialize`].
    let spend_sigs = zcash_deserialize_external_count(spends_count, &mut reader)?;

    // Denoted as `vOutputProofsSapling` in the spec.
    //
    // # Consensus
    //
    // > Elements of an Output description MUST be valid encodings of the types given above.
    //
    // https://zips.z.cash/protocol/protocol.pdf#outputdesc
    //
    // Type is `ZKOutput.Proof`, described in
    // https://zips.z.cash/protocol/protocol.pdf#grothencoding
    // It is not enforced here; this just reads 192 bytes.
    // The type is validated when validating the proof, see
    // [`groth16::Item::try_from`]. In #3179 we plan to validate here instead.
    let output_proofs = zcash_deserialize_external_count(outputs_count, &mut reader)?;

    // Denoted as `bindingSigSapling` in the spec.
    let binding_sig = reader.read_64_bytes()?.into();

    // Create shielded spends from deserialized parts
    let spends: Vec<_> = spend_prefixes
        .into_iter()
        .zip(spend_proofs)
        .zip(spend_sigs)
        .map(|((prefix, proof), sig)| {
            sapling::Spend::<sapling::SharedAnchor>::from_v5_parts(prefix, proof, sig)
        })
        .collect();

    // Create shielded outputs from deserialized parts
    let outputs = output_prefixes
        .into_iter()
        .zip(output_proofs)
        .map(|(prefix, proof)| sapling::Output::from_v5_parts(prefix, proof))
        .collect();

    // Create transfers
    //
    // # Consensus
    //
    // > The anchor of each Spend description MUST refer to some earlier
    // > block’s final Sapling treestate. The anchor is encoded separately
    // > in each Spend description for v4 transactions, or encoded once and
    // > shared between all Spend descriptions in a v5 transaction.
    //
    // <https://zips.z.cash/protocol/protocol.pdf#spendsandoutputs>
    //
    // This rule is also implemented in
    // [`zebra_state::service::check::anchor`] and
    // [`zebra_chain::sapling::spend`].
    //
    // The "anchor encoding for v5 transactions" is implemented here.
    let transfers = match shared_anchor {
        Some(shared_anchor) => sapling::TransferData::SpendsAndMaybeOutputs {
            shared_anchor,
            spends: spends
                .try_into()
                .expect("checked spends when parsing shared anchor"),
            maybe_outputs: outputs,
        },
        None => sapling::TransferData::JustOutputs {
            outputs: outputs
                .try_into()
                .expect("checked spends or outputs and returned early"),
        },
    };

    Ok(Some(sapling::ShieldedData {
        value_balance,
        transfers,
        binding_sig,
    }))
}

/// Serializes an optional Orchard-protocol bundle (v5 Orchard, v6 Orchard, or Ironwood).
///
/// All three share the same wire encoding: an empty action list (`nActions = 0`) when the bundle is
/// absent, otherwise the bundle's fields.
///
/// "The fields flagsOrchard, valueBalanceOrchard, anchorOrchard, sizeProofsOrchard, proofsOrchard,
/// and bindingSigOrchard are present if and only if nActionsOrchard > 0." — `§` note of the second
/// table of <https://zips.z.cash/protocol/protocol.pdf#txnencoding>
#[cfg(any(test, feature = "proptest-impl"))]
fn zcash_serialize_optional_orchard_bundle<W: io::Write>(
    shielded_data: Option<&orchard::ShieldedData>,
    mut writer: W,
) -> Result<(), io::Error> {
    match shielded_data {
        // Denoted as `nActionsOrchard` in the spec.
        None => zcash_serialize_empty_list(&mut writer),
        Some(shielded_data) => shielded_data.zcash_serialize(&mut writer),
    }
}

#[cfg(any(test, feature = "proptest-impl"))]
impl ZcashSerialize for Option<orchard::ShieldedData> {
    fn zcash_serialize<W: io::Write>(&self, writer: W) -> Result<(), io::Error> {
        zcash_serialize_optional_orchard_bundle(self.as_ref(), writer)
    }
}

#[cfg(any(test, feature = "proptest-impl"))]
impl ZcashSerialize for orchard::ShieldedData {
    fn zcash_serialize<W: io::Write>(&self, mut writer: W) -> Result<(), io::Error> {
        // Split the AuthorizedAction
        let (actions, sigs): (Vec<orchard::Action>, Vec<Signature<SpendAuth>>) = self
            .actions
            .iter()
            .cloned()
            .map(orchard::AuthorizedAction::into_parts)
            .unzip();

        // Denoted as `nActionsOrchard` and `vActionsOrchard` in the spec.
        actions.zcash_serialize(&mut writer)?;

        // Denoted as `flagsOrchard` in the spec.
        self.flags.zcash_serialize(&mut writer)?;

        // Denoted as `valueBalanceOrchard` in the spec.
        self.value_balance.zcash_serialize(&mut writer)?;

        // Denoted as `anchorOrchard` in the spec.
        self.shared_anchor.zcash_serialize(&mut writer)?;

        // Denoted as `sizeProofsOrchard` and `proofsOrchard` in the spec.
        self.proof.zcash_serialize(&mut writer)?;

        // Denoted as `vSpendAuthSigsOrchard` in the spec.
        zcash_serialize_external_count(&sigs, &mut writer)?;

        // Denoted as `bindingSigOrchard` in the spec.
        self.binding_sig.zcash_serialize(&mut writer)?;

        Ok(())
    }
}

/// The `flagsOrchard` codec a v6 Orchard-protocol bundle newtype uses on deserialization.
///
/// A v6 Orchard or Ironwood bundle encodes identically on the wire to a v5 Orchard bundle (the flag
/// byte is written as-is); the pools differ only in the reserved-bit rule applied to `flagsOrchard`.
/// The `enableCrossAddress` bit (bit 2) is permitted only for the Ironwood pool, and is reserved
/// (MUST be 0) for the Orchard pool regardless of tx version — matching
/// `orchard::bundle::Flags::from_byte`, which rejects bit 2 for `ValuePool::Orchard`. Tying the
/// codec to the bundle type lets the (de)serializers below imply it instead of naming it explicitly.
#[cfg(any(test, feature = "proptest-impl"))]
trait V6FlagCodec {
    /// The flag codec: `orchard::Flags` reserves bit 2, `orchard::FlagsV6` permits it.
    type Codec: ZcashDeserialize + Into<orchard::Flags>;
}

#[cfg(any(test, feature = "proptest-impl"))]
impl V6FlagCodec for orchard::ShieldedDataV6 {
    // The v6 Orchard bundle parses with the pre-NU6.3 codec, exactly like v5.
    type Codec = orchard::Flags;
}

#[cfg(any(test, feature = "proptest-impl"))]
impl V6FlagCodec for ironwood::ShieldedData {
    // Only the Ironwood bundle permits `enableCrossAddress`.
    type Codec = orchard::FlagsV6;
}

/// Deserializes the shared Orchard-protocol bundle body of a v6 bundle newtype `T`, using the flag
/// codec [implied by `T`](V6FlagCodec) rather than one named at the call site.
#[cfg(any(test, feature = "proptest-impl"))]
fn deserialize_v6_orchard_shielded_data<R, T>(
    reader: R,
) -> Result<Option<orchard::ShieldedData>, SerializationError>
where
    R: io::Read,
    T: V6FlagCodec,
{
    deserialize_orchard_shielded_data::<R, T::Codec>(reader)
}

#[cfg(any(test, feature = "proptest-impl"))]
impl ZcashDeserialize for Option<orchard::ShieldedDataV6> {
    fn zcash_deserialize<R: io::Read>(reader: R) -> Result<Self, SerializationError> {
        Ok(
            deserialize_v6_orchard_shielded_data::<R, orchard::ShieldedDataV6>(reader)?
                .map(orchard::ShieldedDataV6::new),
        )
    }
}

#[cfg(any(test, feature = "proptest-impl"))]
impl ZcashSerialize for Option<orchard::ShieldedDataV6> {
    fn zcash_serialize<W: io::Write>(&self, writer: W) -> Result<(), io::Error> {
        zcash_serialize_optional_orchard_bundle(self.as_ref().map(|data| data.data()), writer)
    }
}

#[cfg(any(test, feature = "proptest-impl"))]
impl ZcashDeserialize for Option<ironwood::ShieldedData> {
    fn zcash_deserialize<R: io::Read>(reader: R) -> Result<Self, SerializationError> {
        Ok(
            deserialize_v6_orchard_shielded_data::<R, ironwood::ShieldedData>(reader)?
                .map(orchard::ShieldedDataV6::new)
                .map(ironwood::ShieldedData::new),
        )
    }
}

#[cfg(any(test, feature = "proptest-impl"))]
impl ZcashSerialize for Option<ironwood::ShieldedData> {
    fn zcash_serialize<W: io::Write>(&self, writer: W) -> Result<(), io::Error> {
        zcash_serialize_optional_orchard_bundle(self.as_ref().map(|data| data.data()), writer)
    }
}

// we can't split ShieldedData out of Option<ShieldedData> deserialization,
// because the counts are read along with the arrays.
#[cfg(any(test, feature = "proptest-impl"))]
impl ZcashDeserialize for Option<orchard::ShieldedData> {
    fn zcash_deserialize<R: io::Read>(reader: R) -> Result<Self, SerializationError> {
        // The bare `Option<orchard::ShieldedData>` codec is the v5 Orchard bundle, which uses the
        // pre-NU6.3 flag-byte format (`orchard::Flags`). v6 Orchard and Ironwood bundles use the
        // `orchard::FlagsV6` newtype.
        deserialize_orchard_shielded_data::<R, orchard::Flags>(reader)
    }
}

/// Deserializes an `Option<orchard::ShieldedData>`, parsing the flags byte via the flag type `F`.
///
/// v5 Orchard bundles pass `F = orchard::Flags` (pre-NU6.3 format); v6 Orchard and Ironwood bundles
/// pass `F = orchard::FlagsV6` (the NU6.3 format, which permits the `enableCrossAddress` flag).
#[cfg(any(test, feature = "proptest-impl"))]
pub(crate) fn deserialize_orchard_shielded_data<R, F>(
    mut reader: R,
) -> Result<Option<orchard::ShieldedData>, SerializationError>
where
    R: io::Read,
    F: ZcashDeserialize + Into<orchard::Flags>,
{
    // Denoted as `nActionsOrchard` and `vActionsOrchard` in the spec.
    let actions: Vec<orchard::Action> = (&mut reader).zcash_deserialize_into()?;

    // "The fields flagsOrchard, valueBalanceOrchard, anchorOrchard, sizeProofsOrchard,
    // proofsOrchard , and bindingSigOrchard are present if and only if nActionsOrchard > 0."
    // `§` note of the second table of https://zips.z.cash/protocol/protocol.pdf#txnencoding
    if actions.is_empty() {
        return Ok(None);
    }

    // # Consensus
    //
    // > Elements of an Action description MUST be canonical encodings of the types given above.
    //
    // https://zips.z.cash/protocol/protocol.pdf#actiondesc
    //
    // Some Action elements are validated in this function; they are described below.

    // Denoted as `flagsOrchard` in the spec. The flag type `F` selects the reserved-bit rule
    // (pre-NU6.3 reserves bits 2..7; NU6.3 reserves bits 3..7).
    let flags: orchard::Flags = F::zcash_deserialize(&mut reader)?.into();

    // Denoted as `valueBalanceOrchard` in the spec.
    let value_balance: amount::Amount = (&mut reader).zcash_deserialize_into()?;

    // Denoted as `anchorOrchard` in the spec.
    // Consensus: type is `{0 .. 𝑞_ℙ − 1}`. See [`orchard::tree::Root::zcash_deserialize`].
    let shared_anchor: orchard::tree::Root = (&mut reader).zcash_deserialize_into()?;

    // Denoted as `sizeProofsOrchard` and `proofsOrchard` in the spec.
    // Consensus: type is `ZKAction.Proof`, i.e. a byte sequence.
    // https://zips.z.cash/protocol/protocol.pdf#halo2encoding
    let proof: Halo2Proof = (&mut reader).zcash_deserialize_into()?;

    // Denoted as `vSpendAuthSigsOrchard` in the spec.
    // Consensus: this validates the `spendAuthSig` elements, whose type is
    // SpendAuthSig^{Orchard}.Signature, i.e.
    // B^Y^{[ceiling(ℓ_G/8) + ceiling(bitlength(𝑟_G)/8)]} i.e. 64 bytes
    // See [`Signature::zcash_deserialize`].
    let sigs: Vec<Signature<SpendAuth>> =
        zcash_deserialize_external_count(actions.len(), &mut reader)?;

    // Denoted as `bindingSigOrchard` in the spec.
    let binding_sig: Signature<Binding> = (&mut reader).zcash_deserialize_into()?;

    // Create the AuthorizedAction from deserialized parts
    let authorized_actions: Vec<orchard::AuthorizedAction> = actions
        .into_iter()
        .zip(sigs)
        .map(|(action, spend_auth_sig)| {
            orchard::AuthorizedAction::from_parts(action, spend_auth_sig)
        })
        .collect();

    let actions: AtLeastOne<orchard::AuthorizedAction> = authorized_actions.try_into()?;

    Ok(Some(orchard::ShieldedData {
        flags,
        value_balance,
        shared_anchor,
        proof,
        actions,
        binding_sig,
    }))
}

impl<T: reddsa::SigType> ZcashSerialize for reddsa::Signature<T> {
    fn zcash_serialize<W: io::Write>(&self, mut writer: W) -> Result<(), io::Error> {
        writer.write_all(&<[u8; 64]>::from(*self)[..])?;
        Ok(())
    }
}

impl<T: reddsa::SigType> ZcashDeserialize for reddsa::Signature<T> {
    fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
        Ok(reader.read_64_bytes()?.into())
    }
}

impl<T> ZcashDeserialize for Arc<T>
where
    T: ZcashDeserialize,
{
    fn zcash_deserialize<R: io::Read>(reader: R) -> Result<Self, SerializationError> {
        Ok(Arc::new(T::zcash_deserialize(reader)?))
    }
}

impl<T> ZcashSerialize for Arc<T>
where
    T: ZcashSerialize,
{
    fn zcash_serialize<W: io::Write>(&self, writer: W) -> Result<(), io::Error> {
        T::zcash_serialize(self, writer)
    }
}

/// A Tx Input must have an Outpoint (32 byte hash + 4 byte index), a 4 byte sequence number,
/// and a signature script, which always takes a min of 1 byte (for a length 0 script).
pub(crate) const MIN_TRANSPARENT_INPUT_SIZE: u64 = 32 + 4 + 4 + 1;

/// A Transparent output has an 8 byte value and script which takes a min of 1 byte.
pub(crate) const MIN_TRANSPARENT_OUTPUT_SIZE: u64 = 8 + 1;

/// All txs must have at least one input, a 4 byte locktime, and at least one output.
///
/// Shielded transfers are much larger than transparent transfers,
/// so this is the minimum transaction size.
pub const MIN_TRANSPARENT_TX_SIZE: u64 =
    MIN_TRANSPARENT_INPUT_SIZE + 4 + MIN_TRANSPARENT_OUTPUT_SIZE;

/// The minimum transaction size for v4 transactions.
///
/// v4 transactions also have an expiry height.
pub const MIN_TRANSPARENT_TX_V4_SIZE: u64 = MIN_TRANSPARENT_TX_SIZE + 4;

/// The minimum transaction size for v5 transactions.
///
/// v5 transactions also have an expiry height and a consensus branch ID.
pub const MIN_TRANSPARENT_TX_V5_SIZE: u64 = MIN_TRANSPARENT_TX_SIZE + 4 + 4;

/// No valid Zcash message contains more transactions than can fit in a single block
///
/// `tx` messages contain a single transaction, and `block` messages are limited to the maximum
/// block size.
impl TrustedPreallocate for Transaction {
    fn max_allocation() -> u64 {
        // A transparent transaction is the smallest transaction variant
        MAX_BLOCK_BYTES / MIN_TRANSPARENT_TX_SIZE
    }
}

/// The maximum number of inputs in a valid Zcash on-chain transaction.
///
/// If a transaction contains more inputs than can fit in maximally large block, it might be
/// valid on the network and in the mempool, but it can never be mined into a block. So
/// rejecting these large edge-case transactions can never break consensus.
impl TrustedPreallocate for transparent::Input {
    fn max_allocation() -> u64 {
        MAX_BLOCK_BYTES / MIN_TRANSPARENT_INPUT_SIZE
    }
}

/// The maximum number of outputs in a valid Zcash on-chain transaction.
///
/// If a transaction contains more outputs than can fit in maximally large block, it might be
/// valid on the network and in the mempool, but it can never be mined into a block. So
/// rejecting these large edge-case transactions can never break consensus.
impl TrustedPreallocate for transparent::Output {
    fn max_allocation() -> u64 {
        MAX_BLOCK_BYTES / MIN_TRANSPARENT_OUTPUT_SIZE
    }
}

/// A serialized transaction.
///
/// Stores bytes that are guaranteed to be deserializable into a [`Transaction`].
///
/// Sorts in lexicographic order of the transaction's serialized data.
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct SerializedTransaction {
    bytes: Vec<u8>,
}

impl fmt::Display for SerializedTransaction {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(&hex::encode(&self.bytes))
    }
}

impl fmt::Debug for SerializedTransaction {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // A transaction with a lot of transfers can be extremely long in logs.
        let mut data_truncated = hex::encode(&self.bytes);
        if data_truncated.len() > 1003 {
            let end = data_truncated.len() - 500;
            // Replace the middle bytes with "...", but leave 500 bytes on either side.
            // The data is hex, so this replacement won't panic.
            data_truncated.replace_range(500..=end, "...");
        }

        f.debug_tuple("SerializedTransaction")
            .field(&data_truncated)
            .finish()
    }
}

/// Build a [`SerializedTransaction`] by serializing a block.
impl<B: Borrow<Transaction>> From<B> for SerializedTransaction {
    fn from(tx: B) -> Self {
        SerializedTransaction {
            bytes: tx
                .borrow()
                .zcash_serialize_to_vec()
                .expect("Writing to a `Vec` should never fail"),
        }
    }
}

/// Access the serialized bytes of a [`SerializedTransaction`].
impl AsRef<[u8]> for SerializedTransaction {
    fn as_ref(&self) -> &[u8] {
        self.bytes.as_ref()
    }
}

impl From<Vec<u8>> for SerializedTransaction {
    fn from(bytes: Vec<u8>) -> Self {
        Self { bytes }
    }
}

impl FromHex for SerializedTransaction {
    type Error = <Vec<u8> as FromHex>::Error;

    fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
        let bytes = <Vec<u8>>::from_hex(hex)?;

        Ok(bytes.into())
    }
}