Skip to main content

zebra_chain/primitives/
zcash_primitives.rs

1//! Contains code that interfaces with the zcash_primitives crate from
2//! librustzcash.
3
4use std::{io, ops::Deref, sync::Arc};
5
6use zcash_primitives::transaction::{self as zp_tx, sighash::PrecomputedSighashData};
7use zcash_protocol::value::{BalanceError, ZatBalance, Zatoshis};
8use zcash_script::script;
9
10use crate::{
11    amount::{Amount, NonNegative},
12    serialization::ZcashSerialize,
13    transaction::{HashType, SigHash},
14    transparent::{self, Script},
15    Error,
16};
17
18use crate::{parameters::NetworkUpgrade, transaction::Transaction};
19
20// TODO: move copied and modified code to a separate module.
21//
22// Used by boilerplate code below.
23
24#[derive(Clone, Debug)]
25struct TransparentAuth {
26    all_prev_outputs: Arc<Vec<transparent::Output>>,
27}
28
29impl zcash_transparent::bundle::Authorization for TransparentAuth {
30    type ScriptSig = zcash_transparent::address::Script;
31}
32
33// In this block we convert our Output to a librustzcash to TxOut.
34// (We could do the serialize/deserialize route but it's simple enough to convert manually)
35impl zcash_transparent::sighash::TransparentAuthorizingContext for TransparentAuth {
36    fn input_amounts(&self) -> Vec<Zatoshis> {
37        self.all_prev_outputs
38            .iter()
39            .map(|prevout| {
40                prevout
41                    .value
42                    .try_into()
43                    .expect("will not fail since it was previously validated")
44            })
45            .collect()
46    }
47
48    fn input_scriptpubkeys(&self) -> Vec<zcash_transparent::address::Script> {
49        self.all_prev_outputs
50            .iter()
51            .map(|prevout| {
52                zcash_transparent::address::Script(script::Code(
53                    prevout.lock_script.as_raw_bytes().into(),
54                ))
55            })
56            .collect()
57    }
58}
59
60// Boilerplate mostly copied from `zcash/src/rust/src/transaction_ffi.rs` which is required
61// to compute sighash.
62// TODO: remove/change if they improve the API to not require this.
63
64struct MapTransparent {
65    auth: TransparentAuth,
66}
67
68impl zcash_transparent::bundle::MapAuth<zcash_transparent::bundle::Authorized, TransparentAuth>
69    for MapTransparent
70{
71    fn map_script_sig(
72        &self,
73        s: <zcash_transparent::bundle::Authorized as zcash_transparent::bundle::Authorization>::ScriptSig,
74    ) -> <TransparentAuth as zcash_transparent::bundle::Authorization>::ScriptSig {
75        s
76    }
77
78    fn map_authorization(&self, _: zcash_transparent::bundle::Authorized) -> TransparentAuth {
79        // TODO: This map should consume self, so we can move self.auth
80        self.auth.clone()
81    }
82}
83
84struct IdentityMap;
85
86impl
87    zp_tx::components::sapling::MapAuth<
88        sapling_crypto::bundle::Authorized,
89        sapling_crypto::bundle::Authorized,
90    > for IdentityMap
91{
92    fn map_spend_proof(
93        &mut self,
94        p: <sapling_crypto::bundle::Authorized as sapling_crypto::bundle::Authorization>::SpendProof,
95    ) -> <sapling_crypto::bundle::Authorized as sapling_crypto::bundle::Authorization>::SpendProof
96    {
97        p
98    }
99
100    fn map_output_proof(
101        &mut self,
102        p: <sapling_crypto::bundle::Authorized as sapling_crypto::bundle::Authorization>::OutputProof,
103    ) -> <sapling_crypto::bundle::Authorized as sapling_crypto::bundle::Authorization>::OutputProof
104    {
105        p
106    }
107
108    fn map_auth_sig(
109        &mut self,
110        s: <sapling_crypto::bundle::Authorized as sapling_crypto::bundle::Authorization>::AuthSig,
111    ) -> <sapling_crypto::bundle::Authorized as sapling_crypto::bundle::Authorization>::AuthSig
112    {
113        s
114    }
115
116    fn map_authorization(
117        &mut self,
118        a: sapling_crypto::bundle::Authorized,
119    ) -> sapling_crypto::bundle::Authorized {
120        a
121    }
122}
123
124impl zp_tx::components::orchard::MapAuth<orchard::bundle::Authorized, orchard::bundle::Authorized>
125    for IdentityMap
126{
127    fn map_spend_auth(
128        &self,
129        s: <orchard::bundle::Authorized as orchard::bundle::Authorization>::SpendAuth,
130    ) -> <orchard::bundle::Authorized as orchard::bundle::Authorization>::SpendAuth {
131        s
132    }
133
134    fn map_authorization(&self, a: orchard::bundle::Authorized) -> orchard::bundle::Authorized {
135        a
136    }
137}
138
139#[derive(Debug)]
140struct PrecomputedAuth {}
141
142impl zp_tx::Authorization for PrecomputedAuth {
143    type TransparentAuth = TransparentAuth;
144    type SaplingAuth = sapling_crypto::bundle::Authorized;
145    type OrchardAuth = orchard::bundle::Authorized;
146
147    #[cfg(zcash_unstable = "zfuture")]
148    type TzeAuth = zp_tx::components::tze::Authorized;
149}
150
151// End of (mostly) copied code
152
153/// Convert a Zebra transparent::Output into a librustzcash one.
154impl TryFrom<&transparent::Output> for zcash_transparent::bundle::TxOut {
155    type Error = io::Error;
156
157    #[allow(clippy::unwrap_in_result)]
158    fn try_from(output: &transparent::Output) -> Result<Self, Self::Error> {
159        let serialized_output_bytes = output
160            .zcash_serialize_to_vec()
161            .expect("zcash_primitives and Zebra transparent output formats must be compatible");
162
163        zcash_transparent::bundle::TxOut::read(&mut serialized_output_bytes.as_slice())
164    }
165}
166
167/// Convert a Zebra transparent::Output into a librustzcash one.
168impl TryFrom<transparent::Output> for zcash_transparent::bundle::TxOut {
169    type Error = io::Error;
170
171    // The borrow is actually needed to use TryFrom<&transparent::Output>
172    #[allow(clippy::needless_borrow)]
173    fn try_from(output: transparent::Output) -> Result<Self, Self::Error> {
174        (&output).try_into()
175    }
176}
177
178/// Convert a Zebra non-negative Amount into a librustzcash one.
179impl TryFrom<Amount<NonNegative>> for zcash_protocol::value::Zatoshis {
180    type Error = BalanceError;
181
182    fn try_from(amount: Amount<NonNegative>) -> Result<Self, Self::Error> {
183        zcash_protocol::value::Zatoshis::from_nonnegative_i64(amount.into())
184    }
185}
186
187impl TryFrom<Amount> for ZatBalance {
188    type Error = BalanceError;
189
190    fn try_from(amount: Amount) -> Result<Self, Self::Error> {
191        ZatBalance::from_i64(amount.into())
192    }
193}
194
195/// Convert a Zebra Script into a librustzcash one.
196impl From<&Script> for zcash_transparent::address::Script {
197    fn from(script: &Script) -> Self {
198        zcash_transparent::address::Script(script::Code(script.as_raw_bytes().to_vec()))
199    }
200}
201
202/// Convert a Zebra Script into a librustzcash one.
203impl From<Script> for zcash_transparent::address::Script {
204    // The borrow is actually needed to use From<&Script>
205    #[allow(clippy::needless_borrow)]
206    fn from(script: Script) -> Self {
207        (&script).into()
208    }
209}
210
211/// Precomputed data used for sighash or txid computation.
212#[derive(Debug)]
213pub(crate) struct PrecomputedTxData {
214    /// The transaction, and the digests that every signature hash of it commits to.
215    ///
216    /// Computing these once per transaction keeps the cost of computing the signature
217    /// hashes of all of its inputs linear in the number of inputs.
218    sighash_data: PrecomputedSighashData<PrecomputedAuth>,
219    all_previous_outputs: Arc<Vec<transparent::Output>>,
220}
221
222impl PrecomputedTxData {
223    /// Computes the data used for sighash or txid computation.
224    ///
225    /// For V4 transactions, uses the network upgrade's consensus branch ID for the sighash,
226    /// which must match the branch ID used when the transaction was signed.
227    /// Returns an error if `nu` doesn't have a valid consensus branch ID.
228    pub(crate) fn new(
229        tx: &Transaction,
230        nu: NetworkUpgrade,
231        all_previous_outputs: Arc<Vec<transparent::Output>>,
232    ) -> Result<PrecomputedTxData, Error> {
233        let branch_id = nu
234            .branch_id()
235            .and_then(|cbid| zcash_protocol::consensus::BranchId::try_from(cbid).ok())
236            .ok_or(Error::InvalidConsensusBranchId)?;
237
238        // For V5+ transactions, the branch_id is embedded and must match.
239        // For V4 transactions, use the network upgrade's branch_id for the sighash.
240        let tx_branch_id = tx.inner().deref().consensus_branch_id();
241        if tx.version() >= 5 && tx_branch_id != branch_id {
242            return Err(Error::InvalidConsensusBranchId);
243        }
244
245        Self::from_transaction_with_branch_id(tx, branch_id, all_previous_outputs)
246    }
247
248    /// Computes precomputed sighash data with an explicit consensus branch ID.
249    ///
250    /// Clones the transaction to get an owned `TransactionData` for `map_authorization`,
251    /// reconstructing with the correct `branch_id` for V1-V4 sighash computation.
252    fn from_transaction_with_branch_id(
253        tx: &crate::transaction::Transaction,
254        branch_id: zcash_protocol::consensus::BranchId,
255        all_previous_outputs: Arc<Vec<transparent::Output>>,
256    ) -> Result<PrecomputedTxData, Error> {
257        let inner = tx.inner();
258
259        // Clone the transaction to get an owned TransactionData we can transform.
260        // Reconstruct with the correct branch_id (the stored value may differ for
261        // V1-V4 transactions that were parsed without network context).
262        //
263        // The rebuild must preserve every bundle: losing the Ironwood one would leave
264        // `PrecomputedTxData::ironwood_bundle` empty, and the verifier queues an Ironwood proof
265        // check only when that returns `Some`.
266        let data = inner.clone().into_data();
267        let data_with_branch_id = crate::transaction::compat::transaction_data_from_parts(
268            data.version(),
269            branch_id,
270            data.lock_time(),
271            data.expiry_height(),
272            data.transparent_bundle().cloned(),
273            data.sprout_bundle().cloned(),
274            data.sapling_bundle().cloned(),
275            data.orchard_bundle().cloned(),
276            data.ironwood_bundle().cloned(),
277        );
278
279        let tx_data: zp_tx::TransactionData<PrecomputedAuth> = data_with_branch_id
280            .map_authorization(
281                MapTransparent {
282                    auth: TransparentAuth {
283                        all_prev_outputs: all_previous_outputs.clone(),
284                    },
285                },
286                IdentityMap,
287                IdentityMap,
288                #[cfg(zcash_unstable = "zfuture")]
289                (),
290            );
291
292        Ok(PrecomputedTxData {
293            sighash_data: PrecomputedSighashData::new(tx_data),
294            all_previous_outputs,
295        })
296    }
297
298    /// Returns the Orchard bundle of the transaction.
299    pub fn orchard_bundle(
300        &self,
301    ) -> Option<orchard::bundle::Bundle<orchard::bundle::Authorized, ZatBalance>> {
302        self.sighash_data.tx().orchard_bundle().cloned()
303    }
304
305    /// Returns the Ironwood bundle of the transaction (NU6.3 onward).
306    ///
307    /// The Ironwood bundle reuses the Orchard bundle type; it differs only by pool (separate tree,
308    /// nullifier set, and value balance) and is verified under the NU6.3 Action circuit key.
309    pub fn ironwood_bundle(
310        &self,
311    ) -> Option<orchard::bundle::Bundle<orchard::bundle::Authorized, ZatBalance>> {
312        self.sighash_data.tx().ironwood_bundle().cloned()
313    }
314
315    /// Returns the Sapling bundle of the transaction.
316    pub fn sapling_bundle(
317        &self,
318    ) -> Option<sapling_crypto::Bundle<sapling_crypto::bundle::Authorized, ZatBalance>> {
319        self.sighash_data.tx().sapling_bundle().cloned()
320    }
321}
322
323/// Internal error type returned by [`sighash_inner`] when a sighash request
324/// violates one of the documented preconditions of [`sighash`] or
325/// [`sighash_v4_raw`].
326///
327/// Public callers (`SigHasher::sighash`, `SigHasher::sighash_v4_raw`) document
328/// these conditions as panics, so they unwrap the result at the public
329/// boundary. Keeping the internal code `Result`-shaped avoids spreading
330/// `.expect()` calls across multiple locations whose justifications all
331/// depend on the same caller invariants.
332#[derive(Debug)]
333enum SighashError {
334    /// Caller passed an `input_index` greater than or equal to the number of
335    /// transparent inputs the caller declared in `all_previous_outputs`.
336    InputIndexOutOfBounds {
337        input_index: usize,
338        input_count: usize,
339    },
340    /// Caller asked for a transparent sighash on a transaction that
341    /// `zcash_primitives` parsed without a transparent bundle. This contradicts
342    /// the precondition that `Some((input_index, _))` is only passed for
343    /// transactions with at least one transparent input.
344    NoTransparentBundle,
345    /// `input_index` is within bounds for `all_previous_outputs` but out of
346    /// bounds for the transparent bundle's `vin` returned by
347    /// `zcash_primitives`. Reaching this branch indicates a serialize /
348    /// deserialize round-trip inconsistency between Zebra's `Transaction` and
349    /// the parsed `zcash_primitives::Transaction`, which would be a bug in
350    /// either crate.
351    BundleInputCountMismatch {
352        input_index: usize,
353        bundle_vin_len: usize,
354        all_prev_outputs_len: usize,
355    },
356    /// The previous output's value could not be converted to `Zatoshis`.
357    /// Reaching this branch means the caller passed an output whose amount
358    /// was not validated by the consensus rules before sighash computation.
359    InvalidPreviousOutputAmount,
360}
361
362impl std::fmt::Display for SighashError {
363    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
364        match self {
365            Self::InputIndexOutOfBounds {
366                input_index,
367                input_count,
368            } => write!(
369                f,
370                "input_index {input_index} is out of bounds (transaction has \
371                 {input_count} transparent inputs)"
372            ),
373            Self::NoTransparentBundle => f.write_str(
374                "transparent sighash requested for a transaction with no \
375                 transparent bundle (vin and vout both empty)",
376            ),
377            Self::BundleInputCountMismatch {
378                input_index,
379                bundle_vin_len,
380                all_prev_outputs_len,
381            } => write!(
382                f,
383                "input_index {input_index} valid for all_previous_outputs (len \
384                 {all_prev_outputs_len}) but out of bounds for the parsed \
385                 transparent bundle (vin len {bundle_vin_len}); this indicates \
386                 a serialize/deserialize round-trip inconsistency"
387            ),
388            Self::InvalidPreviousOutputAmount => f.write_str(
389                "previous output amount could not be converted to Zatoshis; \
390                 the amount should have been validated before sighash \
391                 computation",
392            ),
393        }
394    }
395}
396
397impl std::error::Error for SighashError {}
398
399/// Compute a signature hash using librustzcash.
400///
401/// # Inputs
402///
403/// - `precomputed_tx_data`: precomputed data for the transaction whose
404///   signature hash is being computed.
405/// - `hash_type`: the type of hash (SIGHASH) being used.
406/// - `input_index_script_code`: a tuple with the index of the transparent Input
407///   for which we are producing a sighash and the respective script code being
408///   validated, or None if it's a shielded input.
409///
410/// # Panics
411///
412/// - if `input_index_script_code` is `Some((input_index, _))` and `input_index`
413///   is out of bounds for `precomputed_tx_data.all_previous_outputs`. The
414///   public callers in `zebra-chain` document this as a precondition.
415/// - if the previous output at `input_index` has a value that cannot be
416///   converted to `Zatoshis`. Output values are validated before sighash
417///   computation, so this branch is unreachable in practice.
418pub(crate) fn sighash(
419    precomputed_tx_data: &PrecomputedTxData,
420    hash_type: HashType,
421    input_index_script_code: Option<(usize, Vec<u8>)>,
422) -> SigHash {
423    sighash_inner(
424        precomputed_tx_data,
425        hash_type.try_into().expect("hash type should be canonical"),
426        input_index_script_code,
427    )
428    .expect(
429        "sighash precondition violated: callers must pass an in-bounds \
430         input_index when computing a transparent sighash, and the transaction \
431         must contain the transparent input being signed",
432    )
433}
434
435/// Compute a pre-V5 (V4) signature hash using the raw `hash_type` byte.
436///
437/// `zcashd` serializes the full raw byte into the V4 sighash preimage and only
438/// masks with `SIGHASH_MASK` (0x1f) for selection logic. Callers handling V5+
439/// transactions must use [`sighash`] instead so ZIP-244 strictness is enforced.
440///
441/// # Panics
442///
443/// Same preconditions as [`sighash`].
444pub(crate) fn sighash_v4_raw(
445    precomputed_tx_data: &PrecomputedTxData,
446    raw_hash_type: u8,
447    input_index_script_code: Option<(usize, Vec<u8>)>,
448) -> SigHash {
449    sighash_inner(
450        precomputed_tx_data,
451        zcash_transparent::sighash::SighashType::from_raw(raw_hash_type),
452        input_index_script_code,
453    )
454    .expect(
455        "sighash precondition violated: callers must pass an in-bounds \
456         input_index when computing a transparent sighash, and the transaction \
457         must contain the transparent input being signed",
458    )
459}
460
461/// Internal sighash computation that surfaces precondition violations through
462/// `Result` instead of spreading `.expect()` calls across multiple sites.
463///
464/// All callers in `zebra-chain` unwrap the returned `Result` at the public
465/// boundary, but funnelling the error variants through one type makes it
466/// obvious which preconditions each call site relies on.
467fn sighash_inner(
468    precomputed_tx_data: &PrecomputedTxData,
469    sighash_type: zcash_transparent::sighash::SighashType,
470    input_index_script_code: Option<(usize, Vec<u8>)>,
471) -> Result<SigHash, SighashError> {
472    let lock_script: zcash_transparent::address::Script;
473    let unlock_script: zcash_transparent::address::Script;
474    let signable_input = match input_index_script_code {
475        Some((input_index, script_code)) => {
476            // The `all_previous_outputs` vector is supplied by the caller in
477            // 1:1 correspondence with `tx.inputs()`, and the transparent
478            // bundle was produced by round-tripping the same transaction
479            // bytes through `zcash_primitives::Transaction::read`. Both have
480            // length equal to `tx.inputs().len()`, so an out-of-bounds index
481            // is a caller error that should be reported once here.
482            let all_prev_outputs_len = precomputed_tx_data.all_previous_outputs.len();
483            let output = precomputed_tx_data
484                .all_previous_outputs
485                .get(input_index)
486                .ok_or(SighashError::InputIndexOutOfBounds {
487                    input_index,
488                    input_count: all_prev_outputs_len,
489                })?;
490            // `zcash_primitives::Transaction::read` returns
491            // `transparent_bundle = None` only when both `vin` and `vout` are
492            // empty. The caller only reaches this branch with `Some(_)` when
493            // the transaction has at least one transparent input, so reaching
494            // a `None` here means the caller violated the precondition or
495            // librustzcash changed its behaviour.
496            let bundle = precomputed_tx_data
497                .sighash_data
498                .tx()
499                .transparent_bundle()
500                .ok_or(SighashError::NoTransparentBundle)?;
501            lock_script = output.lock_script.clone().into();
502            unlock_script = zcash_transparent::address::Script(script::Code(script_code));
503            let value = output
504                .value
505                .try_into()
506                .map_err(|_| SighashError::InvalidPreviousOutputAmount)?;
507            let from_parts = zcash_transparent::sighash::SignableInput::from_parts(
508                bundle,
509                sighash_type,
510                input_index,
511                &unlock_script,
512                &lock_script,
513                value,
514            )
515            .map_err(|_| SighashError::BundleInputCountMismatch {
516                input_index,
517                bundle_vin_len: bundle.vin.len(),
518                all_prev_outputs_len,
519            })?;
520            zp_tx::sighash::SignableInput::Transparent(from_parts)
521        }
522        None => zp_tx::sighash::SignableInput::Shielded,
523    };
524
525    Ok(SigHash(
526        *precomputed_tx_data
527            .sighash_data
528            .signature_hash(&signable_input)
529            .as_ref(),
530    ))
531}