zebra_chain/orchard/shielded_data.rs
1//! Orchard shielded data for `V5` `Transaction`s.
2
3use std::{
4 cmp::{Eq, PartialEq},
5 fmt::{self, Debug},
6 io,
7};
8
9use byteorder::{ReadBytesExt, WriteBytesExt};
10use halo2::pasta::pallas;
11use reddsa::{orchard::Binding, orchard::SpendAuth, Signature};
12
13use crate::{
14 amount::{Amount, NegativeAllowed},
15 block::MAX_BLOCK_BYTES,
16 orchard::{tree, Action, Nullifier},
17 primitives::Halo2Proof,
18 serialization::{
19 AtLeastOne, SerializationError, TrustedPreallocate, ZcashDeserialize, ZcashSerialize,
20 },
21};
22
23/// Returns the canonical size in bytes of an Orchard proof for `num_actions` actions.
24///
25/// An Orchard proof is a Halo2 proof whose length is exactly linear in the number of
26/// actions (circuit instances): 4992 bytes for 1 action and 7264 bytes for 2 actions,
27/// i.e. a fixed base plus 2272 bytes per action. The exact constants are owned by the
28/// `orchard` crate, which derives them from the action circuit's `halo2_proofs`
29/// `CircuitCost` and cross-checks them in its circuit tests, so we delegate to
30/// [`orchard::Proof::expected_proof_size`] rather than re-deriving them here. The
31/// `expected_proof_size_known_values` guard test cross-checks the returned values.
32pub(crate) fn expected_proof_size(num_actions: usize) -> usize {
33 orchard::Proof::expected_proof_size(num_actions)
34}
35
36/// A bundle of [`Action`] descriptions and signature data.
37#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
38pub struct ShieldedData {
39 /// The orchard flags for this transaction.
40 /// Denoted as `flagsOrchard` in the spec.
41 pub flags: Flags,
42 /// The net value of Orchard spends minus outputs.
43 /// Denoted as `valueBalanceOrchard` in the spec.
44 pub value_balance: Amount,
45 /// The shared anchor for all `Spend`s in this transaction.
46 /// Denoted as `anchorOrchard` in the spec.
47 pub shared_anchor: tree::Root,
48 /// The aggregated zk-SNARK proof for all the actions in this transaction.
49 /// Denoted as `proofsOrchard` in the spec.
50 pub proof: Halo2Proof,
51 /// The Orchard Actions, in the order they appear in the transaction.
52 /// Denoted as `vActionsOrchard` and `vSpendAuthSigsOrchard` in the spec.
53 pub actions: AtLeastOne<AuthorizedAction>,
54 /// A signature on the transaction `sighash`.
55 /// Denoted as `bindingSigOrchard` in the spec.
56 pub binding_sig: Signature<Binding>,
57}
58
59/// A v6 (NU6.3) Orchard-protocol shielded bundle — used for both the Orchard and the Ironwood pool.
60///
61/// This newtype wraps [`ShieldedData`] to give it the NU6.3 flag-byte serialization
62/// ([`FlagsV6`], which permits the `enableCrossAddress` flag), distinct from the
63/// pre-NU6.3 serialization that the bare [`ShieldedData`] uses for v5 Orchard bundles. The two
64/// formats differ only in which flag bits are reserved; encoding the format in the type keeps the
65/// v5 and v6 (de)serialization paths from being confused.
66#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
67pub struct ShieldedDataV6(ShieldedData);
68
69impl ShieldedDataV6 {
70 /// Wraps a v5-shaped Orchard [`ShieldedData`] as a v6 (NU6.3) Orchard bundle.
71 pub fn new(shielded_data: ShieldedData) -> Self {
72 Self(shielded_data)
73 }
74
75 /// Returns the inner Orchard [`ShieldedData`].
76 pub fn data(&self) -> &ShieldedData {
77 &self.0
78 }
79
80 /// Returns the inner Orchard [`ShieldedData`], mutably.
81 pub fn data_mut(&mut self) -> &mut ShieldedData {
82 &mut self.0
83 }
84
85 /// Consumes the wrapper, returning the inner Orchard [`ShieldedData`].
86 pub fn into_inner(self) -> ShieldedData {
87 self.0
88 }
89}
90
91impl fmt::Display for ShieldedData {
92 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93 let mut fmter = f.debug_struct("orchard::ShieldedData");
94
95 fmter.field("actions", &self.actions.len());
96 fmter.field("value_balance", &self.value_balance);
97 fmter.field("flags", &self.flags);
98
99 fmter.field("proof_len", &self.proof.zcash_serialized_size());
100
101 fmter.field("shared_anchor", &self.shared_anchor);
102
103 fmter.finish()
104 }
105}
106
107impl ShieldedData {
108 /// Iterate over the [`Action`]s for the [`AuthorizedAction`]s in this
109 /// transaction, in the order they appear in it.
110 pub fn actions(&self) -> impl Iterator<Item = &Action> {
111 self.actions.actions()
112 }
113
114 /// Returns whether the proof has the canonical length for its number of actions.
115 ///
116 /// An Orchard proof is stored as an unbounded byte sequence, so a proof that is
117 /// present but not canonically sized can be padded with arbitrary trailing data
118 /// without affecting its validity. Bundles are parsed leniently (so that historical
119 /// transactions remain deserializable), so this is enforced separately as a
120 /// height-gated consensus rule. See `GHSA-jfw5-j458-pfv6`.
121 pub fn proof_size_is_canonical(&self) -> bool {
122 self.proof.0.len() == expected_proof_size(self.actions.len())
123 }
124
125 /// Collect the [`Nullifier`]s for this transaction.
126 pub fn nullifiers(&self) -> impl Iterator<Item = &Nullifier> {
127 self.actions().map(|action| &action.nullifier)
128 }
129
130 /// Provide access to the `value_balance` field of the shielded data.
131 ///
132 /// Needed to calculate the sapling value balance.
133 pub fn value_balance(&self) -> Amount<NegativeAllowed> {
134 self.value_balance
135 }
136
137 /// Collect the cm_x's for this transaction, if it contains [`Action`]s with
138 /// outputs, in the order they appear in the transaction.
139 pub fn note_commitments(&self) -> impl Iterator<Item = &pallas::Base> {
140 self.actions().map(|action| &action.cm_x)
141 }
142}
143
144/// A trait for types that can provide Orchard actions.
145pub trait OrchardActions {
146 /// Returns an iterator over the actions in this type.
147 fn actions(&self) -> impl Iterator<Item = &Action> + '_;
148}
149
150impl OrchardActions for AtLeastOne<AuthorizedAction> {
151 /// Iterate over the [`Action`]s of each [`AuthorizedAction`].
152 fn actions(&self) -> impl Iterator<Item = &Action> + '_ {
153 self.iter()
154 .map(|authorized_action| &authorized_action.action)
155 }
156}
157
158/// An authorized action description.
159///
160/// Every authorized Orchard `Action` must have a corresponding `SpendAuth` signature.
161#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
162pub struct AuthorizedAction {
163 /// The action description of this Action.
164 pub action: Action,
165 /// The spend signature.
166 pub spend_auth_sig: Signature<SpendAuth>,
167}
168
169impl AuthorizedAction {
170 /// Split out the action and the signature for V5 transaction
171 /// serialization.
172 pub fn into_parts(self) -> (Action, Signature<SpendAuth>) {
173 (self.action, self.spend_auth_sig)
174 }
175
176 // Combine the action and the spend auth sig from V5 transaction
177 /// deserialization.
178 pub fn from_parts(action: Action, spend_auth_sig: Signature<SpendAuth>) -> AuthorizedAction {
179 AuthorizedAction {
180 action,
181 spend_auth_sig,
182 }
183 }
184}
185
186/// The size of a single Action
187///
188/// Actions are 5 * 32 + 580 + 80 bytes so the total size of each Action is 820 bytes.
189/// [7.5 Action Description Encoding and Consensus][ps]
190///
191/// [ps]: <https://zips.z.cash/protocol/nu5.pdf#actionencodingandconsensus>
192pub const ACTION_SIZE: u64 = 5 * 32 + 580 + 80;
193
194/// The size of a single `Signature<SpendAuth>`.
195///
196/// Each Signature is 64 bytes.
197/// [7.1 Transaction Encoding and Consensus][ps]
198///
199/// [ps]: <https://zips.z.cash/protocol/nu5.pdf#actionencodingandconsensus>
200pub const SPEND_AUTH_SIG_SIZE: u64 = 64;
201
202/// The size of a single AuthorizedAction
203///
204/// Each serialized `Action` has a corresponding `Signature<SpendAuth>`.
205pub const AUTHORIZED_ACTION_SIZE: u64 = ACTION_SIZE + SPEND_AUTH_SIG_SIZE;
206
207/// The maximum number of orchard actions in a valid Zcash on-chain transaction V5.
208///
209/// If a transaction contains more actions than can fit in maximally large block, it might be
210/// valid on the network and in the mempool, but it can never be mined into a block. So
211/// rejecting these large edge-case transactions can never break consensus.
212impl TrustedPreallocate for Action {
213 fn max_allocation() -> u64 {
214 // Since a serialized Vec<AuthorizedAction> uses at least one byte for its length,
215 // and the signature is required,
216 // a valid max allocation can never exceed this size
217 const MAX: u64 = (MAX_BLOCK_BYTES - 1) / AUTHORIZED_ACTION_SIZE;
218 // # Consensus
219 //
220 // > [NU5 onward] nSpendsSapling, nOutputsSapling, and nActionsOrchard MUST all be less than 2^16.
221 //
222 // https://zips.z.cash/protocol/protocol.pdf#txnconsensus
223 //
224 // This acts as nActionsOrchard and is therefore subject to the rule.
225 // The maximum value is actually smaller due to the block size limit,
226 // but we ensure the 2^16 limit with a static assertion.
227 const {
228 assert!(MAX < (1 << 16));
229 };
230 MAX
231 }
232}
233
234impl TrustedPreallocate for Signature<SpendAuth> {
235 fn max_allocation() -> u64 {
236 // Each signature must have a corresponding action.
237 Action::max_allocation()
238 }
239}
240
241bitflags! {
242 /// Per-Transaction flags for Orchard.
243 ///
244 /// The spend and output flags are passed to the `Halo2Proof` verifier, which verifies
245 /// the relevant note spending and creation consensus rules.
246 ///
247 /// # Consensus
248 ///
249 /// > [NU5 onward] In a version 5 transaction, the reserved bits 2..7 of the flagsOrchard
250 /// > field MUST be zero.
251 ///
252 /// <https://zips.z.cash/protocol/protocol.pdf#txnconsensus>
253 ///
254 /// ([`bitflags`](https://docs.rs/bitflags/1.2.1/bitflags/index.html) restricts its values to the
255 /// set of valid flags)
256 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
257 pub struct Flags: u8 {
258 /// Enable spending non-zero valued Orchard notes.
259 ///
260 /// "the `enableSpendsOrchard` flag, if present, MUST be 0 for coinbase transactions"
261 const ENABLE_SPENDS = 0b00000001;
262 /// Enable creating new non-zero valued Orchard notes.
263 const ENABLE_OUTPUTS = 0b00000010;
264 /// `enableCrossAddress` (NU6.3, bit 2): allow output notes to use a different
265 /// protocol-level address than the spending key.
266 ///
267 /// Reserved (MUST be 0) for the Orchard pool in every tx version. Valid only for the
268 /// Ironwood pool (v6), parsed via the `FlagsV6` newtype.
269 const ENABLE_CROSS_ADDRESS = 0b00000100;
270 }
271}
272
273/// The Orchard flags of an Ironwood (v6) bundle.
274///
275/// Newtype over [`Flags`] whose [`ZcashDeserialize`] impl uses the NU6.3 Ironwood flag-byte format:
276/// bit 2 (`enableCrossAddress`) is valid and only bits 3..7 are reserved. The bare [`Flags`] codec
277/// is the format for every Orchard-pool bundle (v5 *and* v6), where bits 2..7 are all reserved —
278/// `enableCrossAddress` is permitted only for the Ironwood pool. Encoding the format in the type
279/// keeps the two flag-parsing paths from being confused (parallels [`ShieldedDataV6`]).
280#[derive(Copy, Clone, Debug, PartialEq, Eq)]
281pub struct FlagsV6(Flags);
282
283impl From<FlagsV6> for Flags {
284 fn from(flags: FlagsV6) -> Self {
285 flags.0
286 }
287}
288
289impl Flags {
290 /// The flag bits that are reserved (MUST be zero) in the pre-NU6.3 format.
291 const PRE_NU6_3_RESERVED: u8 = !(Self::ENABLE_SPENDS.bits() | Self::ENABLE_OUTPUTS.bits());
292
293 /// The flag bits that are reserved (MUST be zero) in the NU6.3 format.
294 const NU6_3_RESERVED: u8 = !(Self::ENABLE_SPENDS.bits()
295 | Self::ENABLE_OUTPUTS.bits()
296 | Self::ENABLE_CROSS_ADDRESS.bits());
297
298 /// Parses a flags byte, rejecting any bit set in the `reserved` mask.
299 ///
300 /// This is a generic helper that enforces whatever `reserved` mask the caller passes. The
301 /// specific consensus rule for which bits must be zero depends on the bundle format and is
302 /// documented at each call site (see the [`ZcashDeserialize`] impls for [`Flags`] and
303 /// [`FlagsV6`]).
304 fn from_byte(byte: u8, reserved: u8) -> Result<Self, SerializationError> {
305 if byte & reserved != 0 {
306 return Err(SerializationError::Parse("invalid reserved orchard flags"));
307 }
308
309 // `from_bits_truncate` keeps only known bits; the reserved-bit check above already
310 // rejected any bit not permitted by this format.
311 Ok(Self::from_bits_truncate(byte))
312 }
313}
314
315// We use the `bitflags 2.x` library to implement [`Flags`]. The
316// `2.x` version of the library uses a different serialization
317// format compared to `1.x`.
318// This manual implementation uses the `bitflags_serde_legacy` crate
319// to serialize `Flags` as `bitflags 1.x` would.
320impl serde::Serialize for Flags {
321 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
322 bitflags_serde_legacy::serialize(self, "Flags", serializer)
323 }
324}
325
326// We use the `bitflags 2.x` library to implement [`Flags`]. The
327// `2.x` version of the library uses a different deserialization
328// format compared to `1.x`.
329// This manual implementation uses the `bitflags_serde_legacy` crate
330// to deserialize `Flags` as `bitflags 1.x` would.
331impl<'de> serde::Deserialize<'de> for Flags {
332 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
333 bitflags_serde_legacy::deserialize("Flags", deserializer)
334 }
335}
336
337impl ZcashSerialize for Flags {
338 fn zcash_serialize<W: io::Write>(&self, mut writer: W) -> Result<(), io::Error> {
339 writer.write_u8(self.bits())?;
340
341 Ok(())
342 }
343}
344
345impl ZcashDeserialize for Flags {
346 /// # Consensus
347 ///
348 /// > [NU5 onward] In a version 5 transaction, the reserved bits 2..7 of the flagsOrchard
349 /// > field MUST be zero.
350 ///
351 /// From NU6.3, the Ironwood flag byte uses bit 2 as `enableCrossAddress`, so only bits 3..7 are
352 /// reserved (see [`FlagsV6`]); the Orchard pool keeps bit 2 reserved in every tx version.
353 ///
354 /// <https://zips.z.cash/protocol/protocol.pdf#txnconsensus>
355 fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
356 // The default codec is the pre-NU6.3 format, used by v5 *and* v6 Orchard bundles, where
357 // bits 2..7 (including `enableCrossAddress`) are reserved and MUST be zero. Only the Ironwood
358 // bundle deserializes via the `FlagsV6` newtype, which permits bit 2.
359 Flags::from_byte(reader.read_u8()?, Flags::PRE_NU6_3_RESERVED)
360 }
361}
362
363impl ZcashDeserialize for FlagsV6 {
364 /// # Consensus
365 ///
366 /// From NU6.3, the Ironwood flag byte uses bit 2 as `enableCrossAddress`, so only bits 3..7 are
367 /// reserved and MUST be zero (cf. the Orchard-pool rule on [`Flags`], which keeps bit 2
368 /// reserved).
369 ///
370 /// <https://zips.z.cash/protocol/protocol.pdf#txnconsensus>
371 fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
372 // The NU6.3 Ironwood format: bit 2 (`enableCrossAddress`) is valid and only bits 3..7 are
373 // reserved.
374 Ok(FlagsV6(Flags::from_byte(
375 reader.read_u8()?,
376 Flags::NU6_3_RESERVED,
377 )?))
378 }
379}