zebra-chain 16.0.0

Core Zcash data structures
Documentation
//! 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},
    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)
    }

    /// 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.
        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,
        )?))
    }
}