zebra-chain 11.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
//! Orchard shielded data for `V5` `Transaction`s.

use std::{
    cmp::{Eq, PartialEq},
    fmt::{self, Debug},
    io,
};

use byteorder::{ReadBytesExt, WriteBytesExt};
use halo2::pasta::pallas;
use reddsa::{orchard::Binding, orchard::SpendAuth, Signature};

use crate::{
    amount::{Amount, NegativeAllowed},
    block::MAX_BLOCK_BYTES,
    orchard::{tree, Action, Nullifier, ValueCommitment},
    primitives::Halo2Proof,
    serialization::{
        AtLeastOne, SerializationError, TrustedPreallocate, ZcashDeserialize, ZcashSerialize,
    },
};

/// Returns the canonical size in bytes of an Orchard proof for `num_actions` actions.
///
/// An Orchard proof is a Halo2 proof whose length is exactly linear in the number of
/// actions (circuit instances): 4992 bytes for 1 action and 7264 bytes for 2 actions,
/// i.e. a fixed base plus 2272 bytes per action. The exact constants are owned by the
/// `orchard` crate, which derives them from the action circuit's `halo2_proofs`
/// `CircuitCost` and cross-checks them in its circuit tests, so we delegate to
/// [`orchard::Proof::expected_proof_size`] rather than re-deriving them here. The
/// `expected_proof_size_known_values` guard test cross-checks the returned values.
pub(crate) fn expected_proof_size(num_actions: usize) -> usize {
    orchard::Proof::expected_proof_size(num_actions)
}

/// A bundle of [`Action`] descriptions and signature data.
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct ShieldedData {
    /// The orchard flags for this transaction.
    /// Denoted as `flagsOrchard` in the spec.
    pub flags: Flags,
    /// The net value of Orchard spends minus outputs.
    /// Denoted as `valueBalanceOrchard` in the spec.
    pub value_balance: Amount,
    /// The shared anchor for all `Spend`s in this transaction.
    /// Denoted as `anchorOrchard` in the spec.
    pub shared_anchor: tree::Root,
    /// The aggregated zk-SNARK proof for all the actions in this transaction.
    /// Denoted as `proofsOrchard` in the spec.
    pub proof: Halo2Proof,
    /// The Orchard Actions, in the order they appear in the transaction.
    /// Denoted as `vActionsOrchard` and `vSpendAuthSigsOrchard` in the spec.
    pub actions: AtLeastOne<AuthorizedAction>,
    /// A signature on the transaction `sighash`.
    /// Denoted as `bindingSigOrchard` in the spec.
    pub binding_sig: Signature<Binding>,
}

/// A v6 (NU6.3) Orchard-protocol shielded bundle — used for both the Orchard and the Ironwood pool.
///
/// This newtype wraps [`ShieldedData`] to give it the NU6.3 flag-byte serialization
/// ([`FlagsV6`], which permits the `enableCrossAddress` flag), distinct from the
/// pre-NU6.3 serialization that the bare [`ShieldedData`] uses for v5 Orchard bundles. The two
/// formats differ only in which flag bits are reserved; encoding the format in the type keeps the
/// v5 and v6 (de)serialization paths from being confused.
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct ShieldedDataV6(ShieldedData);

impl ShieldedDataV6 {
    /// Wraps a v5-shaped Orchard [`ShieldedData`] as a v6 (NU6.3) Orchard bundle.
    pub fn new(shielded_data: ShieldedData) -> Self {
        Self(shielded_data)
    }

    /// Returns the inner Orchard [`ShieldedData`].
    pub fn data(&self) -> &ShieldedData {
        &self.0
    }

    /// Returns the inner Orchard [`ShieldedData`], mutably.
    pub fn data_mut(&mut self) -> &mut ShieldedData {
        &mut self.0
    }

    /// Consumes the wrapper, returning the inner Orchard [`ShieldedData`].
    pub fn into_inner(self) -> ShieldedData {
        self.0
    }
}

impl fmt::Display for ShieldedData {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut fmter = f.debug_struct("orchard::ShieldedData");

        fmter.field("actions", &self.actions.len());
        fmter.field("value_balance", &self.value_balance);
        fmter.field("flags", &self.flags);

        fmter.field("proof_len", &self.proof.zcash_serialized_size());

        fmter.field("shared_anchor", &self.shared_anchor);

        fmter.finish()
    }
}

impl ShieldedData {
    /// Iterate over the [`Action`]s for the [`AuthorizedAction`]s in this
    /// transaction, in the order they appear in it.
    pub fn actions(&self) -> impl Iterator<Item = &Action> {
        self.actions.actions()
    }

    /// Returns whether the proof has the canonical length for its number of actions.
    ///
    /// An Orchard proof is stored as an unbounded byte sequence, so a proof that is
    /// present but not canonically sized can be padded with arbitrary trailing data
    /// without affecting its validity. Bundles are parsed leniently (so that historical
    /// transactions remain deserializable), so this is enforced separately as a
    /// height-gated consensus rule. See `GHSA-jfw5-j458-pfv6`.
    pub fn proof_size_is_canonical(&self) -> bool {
        self.proof.0.len() == expected_proof_size(self.actions.len())
    }

    /// Collect the [`Nullifier`]s for this transaction.
    pub fn nullifiers(&self) -> impl Iterator<Item = &Nullifier> {
        self.actions().map(|action| &action.nullifier)
    }

    /// Calculate the Action binding verification key.
    ///
    /// Getting the binding signature validating key from the Action description
    /// value commitments and the balancing value implicitly checks that the
    /// balancing value is consistent with the value transferred in the
    /// Action descriptions, but also proves that the signer knew the
    /// randomness used for the Action value commitments, which
    /// prevents replays of Action descriptions that perform an output.
    /// In Orchard, all Action descriptions have a spend authorization signature,
    /// therefore the proof of knowledge of the value commitment randomness
    /// is less important, but stills provides defense in depth, and reduces the
    /// differences between Orchard and Sapling.
    ///
    /// The net value of Orchard spends minus outputs in a transaction
    /// is called the balancing value, measured in zatoshi as a signed integer
    /// cv_balance.
    ///
    /// Consistency of cv_balance with the value commitments in Action
    /// descriptions is enforced by the binding signature.
    ///
    /// Instead of generating a key pair at random, we generate it as a function
    /// of the value commitments in the Action descriptions of the transaction, and
    /// the balancing value.
    ///
    /// <https://zips.z.cash/protocol/protocol.pdf#orchardbalance>
    pub fn binding_verification_key(&self) -> reddsa::VerificationKeyBytes<Binding> {
        let cv: ValueCommitment = self.actions().map(|action| action.cv).sum();
        let cv_balance: ValueCommitment =
            ValueCommitment::new(pallas::Scalar::zero(), self.value_balance);

        let key_bytes: [u8; 32] = (cv - cv_balance).into();
        key_bytes.into()
    }

    /// Provide access to the `value_balance` field of the shielded data.
    ///
    /// Needed to calculate the sapling value balance.
    pub fn value_balance(&self) -> Amount<NegativeAllowed> {
        self.value_balance
    }

    /// Collect the cm_x's for this transaction, if it contains [`Action`]s with
    /// outputs, in the order they appear in the transaction.
    pub fn note_commitments(&self) -> impl Iterator<Item = &pallas::Base> {
        self.actions().map(|action| &action.cm_x)
    }
}

/// A trait for types that can provide Orchard actions.
pub trait OrchardActions {
    /// Returns an iterator over the actions in this type.
    fn actions(&self) -> impl Iterator<Item = &Action> + '_;
}

impl OrchardActions for AtLeastOne<AuthorizedAction> {
    /// Iterate over the [`Action`]s of each [`AuthorizedAction`].
    fn actions(&self) -> impl Iterator<Item = &Action> + '_ {
        self.iter()
            .map(|authorized_action| &authorized_action.action)
    }
}

/// An authorized action description.
///
/// Every authorized Orchard `Action` must have a corresponding `SpendAuth` signature.
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct AuthorizedAction {
    /// The action description of this Action.
    pub action: Action,
    /// The spend signature.
    pub spend_auth_sig: Signature<SpendAuth>,
}

impl AuthorizedAction {
    /// Split out the action and the signature for V5 transaction
    /// serialization.
    pub fn into_parts(self) -> (Action, Signature<SpendAuth>) {
        (self.action, self.spend_auth_sig)
    }

    // Combine the action and the spend auth sig from V5 transaction
    /// deserialization.
    pub fn from_parts(action: Action, spend_auth_sig: Signature<SpendAuth>) -> AuthorizedAction {
        AuthorizedAction {
            action,
            spend_auth_sig,
        }
    }
}

/// The size of a single Action
///
/// Actions are 5 * 32 + 580 + 80 bytes so the total size of each Action is 820 bytes.
/// [7.5 Action Description Encoding and Consensus][ps]
///
/// [ps]: <https://zips.z.cash/protocol/nu5.pdf#actionencodingandconsensus>
pub const ACTION_SIZE: u64 = 5 * 32 + 580 + 80;

/// The size of a single `Signature<SpendAuth>`.
///
/// Each Signature is 64 bytes.
/// [7.1 Transaction Encoding and Consensus][ps]
///
/// [ps]: <https://zips.z.cash/protocol/nu5.pdf#actionencodingandconsensus>
pub const SPEND_AUTH_SIG_SIZE: u64 = 64;

/// The size of a single AuthorizedAction
///
/// Each serialized `Action` has a corresponding `Signature<SpendAuth>`.
pub const AUTHORIZED_ACTION_SIZE: u64 = ACTION_SIZE + SPEND_AUTH_SIG_SIZE;

/// The maximum number of orchard actions in a valid Zcash on-chain transaction V5.
///
/// If a transaction contains more actions 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 Action {
    fn max_allocation() -> u64 {
        // Since a serialized Vec<AuthorizedAction> uses at least one byte for its length,
        // and the signature is required,
        // a valid max allocation can never exceed this size
        const MAX: u64 = (MAX_BLOCK_BYTES - 1) / AUTHORIZED_ACTION_SIZE;
        // # Consensus
        //
        // > [NU5 onward] nSpendsSapling, nOutputsSapling, and nActionsOrchard MUST all be less than 2^16.
        //
        // https://zips.z.cash/protocol/protocol.pdf#txnconsensus
        //
        // This acts as nActionsOrchard and is therefore subject to the rule.
        // The maximum value is actually smaller due to the block size limit,
        // but we ensure the 2^16 limit with a static assertion.
        static_assertions::const_assert!(MAX < (1 << 16));
        MAX
    }
}

impl TrustedPreallocate for Signature<SpendAuth> {
    fn max_allocation() -> u64 {
        // Each signature must have a corresponding action.
        Action::max_allocation()
    }
}

bitflags! {
    /// Per-Transaction flags for Orchard.
    ///
    /// The spend and output flags are passed to the `Halo2Proof` verifier, which verifies
    /// the relevant note spending and creation consensus rules.
    ///
    /// # Consensus
    ///
    /// > [NU5 onward] In a version 5 transaction, the reserved bits 2..7 of the flagsOrchard
    /// > field MUST be zero.
    ///
    /// <https://zips.z.cash/protocol/protocol.pdf#txnconsensus>
    ///
    /// ([`bitflags`](https://docs.rs/bitflags/1.2.1/bitflags/index.html) restricts its values to the
    /// set of valid flags)
    #[derive(Copy, Clone, Debug, PartialEq, Eq)]
    pub struct Flags: u8 {
        /// Enable spending non-zero valued Orchard notes.
        ///
        /// "the `enableSpendsOrchard` flag, if present, MUST be 0 for coinbase transactions"
        const ENABLE_SPENDS = 0b00000001;
        /// Enable creating new non-zero valued Orchard notes.
        const ENABLE_OUTPUTS = 0b00000010;
        /// `enableCrossAddress` (NU6.3, bit 2): allow output notes to use a different
        /// protocol-level address than the spending key.
        ///
        /// Reserved (MUST be 0) for the Orchard pool in every tx version. Valid only for the
        /// Ironwood pool (v6), parsed via the `FlagsV6` newtype.
        const ENABLE_CROSS_ADDRESS = 0b00000100;
    }
}

/// The Orchard flags of an Ironwood (v6) bundle.
///
/// Newtype over [`Flags`] whose [`ZcashDeserialize`] impl uses the NU6.3 Ironwood flag-byte format:
/// bit 2 (`enableCrossAddress`) is valid and only bits 3..7 are reserved. The bare [`Flags`] codec
/// is the format for every Orchard-pool bundle (v5 *and* v6), where bits 2..7 are all reserved —
/// `enableCrossAddress` is permitted only for the Ironwood pool. Encoding the format in the type
/// keeps the two flag-parsing paths from being confused (parallels [`ShieldedDataV6`]).
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct FlagsV6(Flags);

impl From<FlagsV6> for Flags {
    fn from(flags: FlagsV6) -> Self {
        flags.0
    }
}

impl Flags {
    /// The flag bits that are reserved (MUST be zero) in the pre-NU6.3 format.
    const PRE_NU6_3_RESERVED: u8 = !(Self::ENABLE_SPENDS.bits() | Self::ENABLE_OUTPUTS.bits());

    /// The flag bits that are reserved (MUST be zero) in the NU6.3 format.
    const NU6_3_RESERVED: u8 = !(Self::ENABLE_SPENDS.bits()
        | Self::ENABLE_OUTPUTS.bits()
        | Self::ENABLE_CROSS_ADDRESS.bits());

    /// Parses a flags byte, rejecting any bit set in the `reserved` mask.
    ///
    /// This is a generic helper that enforces whatever `reserved` mask the caller passes. The
    /// specific consensus rule for which bits must be zero depends on the bundle format and is
    /// documented at each call site (see the [`ZcashDeserialize`] impls for [`Flags`] and
    /// [`FlagsV6`]).
    fn from_byte(byte: u8, reserved: u8) -> Result<Self, SerializationError> {
        if byte & reserved != 0 {
            return Err(SerializationError::Parse("invalid reserved orchard flags"));
        }

        // `from_bits_truncate` keeps only known bits; the reserved-bit check above already
        // rejected any bit not permitted by this format.
        Ok(Self::from_bits_truncate(byte))
    }
}

// We use the `bitflags 2.x` library to implement [`Flags`]. The
// `2.x` version of the library uses a different serialization
// format compared to `1.x`.
// This manual implementation uses the `bitflags_serde_legacy` crate
// to serialize `Flags` as `bitflags 1.x` would.
impl serde::Serialize for Flags {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        bitflags_serde_legacy::serialize(self, "Flags", serializer)
    }
}

// We use the `bitflags 2.x` library to implement [`Flags`]. The
// `2.x` version of the library uses a different deserialization
// format compared to `1.x`.
// This manual implementation uses the `bitflags_serde_legacy` crate
// to deserialize `Flags` as `bitflags 1.x` would.
impl<'de> serde::Deserialize<'de> for Flags {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        bitflags_serde_legacy::deserialize("Flags", deserializer)
    }
}

impl ZcashSerialize for Flags {
    fn zcash_serialize<W: io::Write>(&self, mut writer: W) -> Result<(), io::Error> {
        writer.write_u8(self.bits())?;

        Ok(())
    }
}

impl ZcashDeserialize for Flags {
    /// # Consensus
    ///
    /// > [NU5 onward] In a version 5 transaction, the reserved bits 2..7 of the flagsOrchard
    /// > field MUST be zero.
    ///
    /// From NU6.3, the Ironwood flag byte uses bit 2 as `enableCrossAddress`, so only bits 3..7 are
    /// reserved (see [`FlagsV6`]); the Orchard pool keeps bit 2 reserved in every tx version.
    ///
    /// <https://zips.z.cash/protocol/protocol.pdf#txnconsensus>
    fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
        // The default codec is the pre-NU6.3 format, used by v5 *and* v6 Orchard bundles, where
        // bits 2..7 (including `enableCrossAddress`) are reserved and MUST be zero. Only the Ironwood
        // bundle deserializes via the `FlagsV6` newtype, which permits bit 2.
        Flags::from_byte(reader.read_u8()?, Flags::PRE_NU6_3_RESERVED)
    }
}

impl ZcashDeserialize for FlagsV6 {
    /// # Consensus
    ///
    /// From NU6.3, the Ironwood flag byte uses bit 2 as `enableCrossAddress`, so only bits 3..7 are
    /// reserved and MUST be zero (cf. the Orchard-pool rule on [`Flags`], which keeps bit 2
    /// reserved).
    ///
    /// <https://zips.z.cash/protocol/protocol.pdf#txnconsensus>
    fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
        // The NU6.3 Ironwood format: bit 2 (`enableCrossAddress`) is valid and only bits 3..7 are
        // reserved.
        Ok(FlagsV6(Flags::from_byte(
            reader.read_u8()?,
            Flags::NU6_3_RESERVED,
        )?))
    }
}