Skip to main content

zebra_script/
lib.rs

1//! Zebra transparent script verification with the Rust `zcash_script` interpreter.
2#![doc(html_favicon_url = "https://zfnd.org/wp-content/uploads/2022/03/zebra-favicon-128.png")]
3#![doc(html_logo_url = "https://zfnd.org/wp-content/uploads/2022/03/zebra-icon.png")]
4#![doc(html_root_url = "https://docs.rs/zebra_script")]
5#![forbid(unsafe_code)]
6
7#[cfg(test)]
8mod tests;
9
10use core::fmt;
11use std::{io, sync::Arc};
12
13use thiserror::Error;
14
15use zcash_script::{
16    interpreter::{CallbackTransactionSignatureChecker, Flags},
17    opcode::PossiblyBad,
18    script::{self, Evaluable as _},
19    Opcode,
20};
21use zcash_transparent::bundle as zp_transparent;
22use zebra_chain::{
23    parameters::{ConsensusBranchId, NetworkUpgrade},
24    serialization::{sha256d, CompactSizeMessage, ZcashSerialize},
25    transaction::{HashType, SigHasher, UnminedTxId},
26    transparent,
27};
28
29/// Errors from transaction preparation and script verification.
30#[derive(Clone, Debug, Error, PartialEq, Eq)]
31#[non_exhaustive]
32pub enum Error {
33    /// script verification failed
34    ScriptInvalid,
35    /// input index out of bounds
36    TxIndex,
37    /// tx is a coinbase transaction and should not be verified
38    TxCoinbase,
39    /// The interpreter rejected a script component.
40    Interpreter {
41        /// The component that failed.
42        component: script::ComponentType,
43        /// The interpreter error.
44        #[source]
45        error: script::Error,
46    },
47    /// transaction is invalid according to zebra_chain (not a zcash_script error)
48    TxInvalid(#[from] zebra_chain::Error),
49}
50
51impl fmt::Display for Error {
52    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53        f.write_str(&match self {
54            Error::ScriptInvalid => "script verification failed".to_owned(),
55            Error::TxIndex => "input index out of bounds".to_owned(),
56            Error::TxCoinbase => {
57                "tx is a coinbase transaction and should not be verified".to_owned()
58            }
59            Error::Interpreter { component, error } => {
60                format!("{component:?} script failed: {error}")
61            }
62            Error::TxInvalid(e) => format!("tx is invalid: {e}"),
63        })
64    }
65}
66
67/// A preprocessed Transaction which can be used to verify scripts within said
68/// Transaction.
69#[derive(Debug)]
70pub struct CachedFfiTransaction {
71    /// The deserialized Zebra transaction.
72    ///
73    /// This field is private so that `transaction`, and `all_previous_outputs` always match.
74    transaction: Arc<zebra_chain::transaction::Transaction>,
75
76    /// The outputs from previous transactions that match each input in the transaction
77    /// being verified.
78    all_previous_outputs: Arc<Vec<transparent::Output>>,
79
80    /// The sighasher context to use to compute sighashes.
81    sighasher: SigHasher,
82
83    /// The commitment returned by [`Self::context_digest`], computed by [`Self::new`] when an
84    /// input script can pass verification.
85    context_digest: Option<[u8; 32]>,
86}
87
88impl CachedFfiTransaction {
89    /// Construct a `CachedFfiTransaction` from a `Transaction` and the outputs
90    /// from previous transactions that match each input in the transaction
91    /// being verified.
92    pub fn new(
93        transaction: Arc<zebra_chain::transaction::Transaction>,
94        all_previous_outputs: Arc<Vec<transparent::Output>>,
95        nu: NetworkUpgrade,
96    ) -> Result<Self, Error> {
97        let sighasher = SigHasher::new(&transaction, nu, all_previous_outputs.clone())?;
98        // `SigHasher::new` has already rejected network upgrades without a consensus branch ID.
99        let branch_id = nu
100            .branch_id()
101            .ok_or(zebra_chain::Error::InvalidConsensusBranchId)?;
102        let mut cached = Self {
103            transaction,
104            all_previous_outputs,
105            sighasher,
106            context_digest: None,
107        };
108
109        // `is_valid` rejects every input of a coinbase transaction, or of a transaction whose
110        // spent outputs don't match its inputs, so there is no success to commit to.
111        if !cached.transaction.is_coinbase()
112            && !cached.vin().is_empty()
113            && cached.all_previous_outputs.len() == cached.vin().len()
114        {
115            let mut digest = sha256d::Writer::default();
116            if cached.write_context(branch_id, &mut digest).is_ok() {
117                cached.context_digest = Some(digest.finish());
118            }
119        }
120
121        Ok(cached)
122    }
123
124    /// Returns the transparent inputs of this transaction, borrowed from the underlying
125    /// `zcash_primitives` transaction.
126    fn vin(&self) -> &[zp_transparent::TxIn<zp_transparent::Authorized>] {
127        self.transaction
128            .transparent_bundle()
129            .map(|bundle| bundle.vin.as_slice())
130            .unwrap_or_default()
131    }
132
133    /// Returns the number of transparent outputs of this transaction, read from the underlying
134    /// `zcash_primitives` transaction.
135    ///
136    /// `Transaction::outputs()` rebuilds and converts the whole output vector, which is far too
137    /// expensive for the per-signature-check sighash callback.
138    fn vout_len(&self) -> usize {
139        self.transaction
140            .transparent_bundle()
141            .map_or(0, |bundle| bundle.vout.len())
142    }
143
144    /// Returns the outputs from previous transactions that match each input in the transaction
145    /// being verified.
146    pub fn all_previous_outputs(&self) -> &Vec<transparent::Output> {
147        &self.all_previous_outputs
148    }
149
150    /// Return the sighasher being used for this transaction.
151    pub fn sighasher(&self) -> &SigHasher {
152        &self.sighasher
153    }
154
155    /// Returns a commitment to everything [`Self::is_valid`] reads except the input index.
156    ///
157    /// It commits to the transaction's [`UnminedTxId`], whose legacy hash or authorizing data
158    /// digest covers every signature script, to the consensus branch ID that sighashes are
159    /// computed under, and to the number of spent outputs and each one's value and length-prefixed
160    /// `scriptPubKey`, in input order. The script verification flags are fixed, so they need no
161    /// commitment. Callers can remember a successful [`Self::is_valid`] under this digest and the
162    /// input index.
163    ///
164    /// [`Self::new`] computes the digest alongside the sighash precomputation, so this only copies
165    /// it. It is `None` for coinbase transactions, transactions without transparent inputs, spent
166    /// outputs that don't match the inputs one to one, and spent outputs too large to encode.
167    pub fn context_digest(&self) -> Option<[u8; 32]> {
168        self.context_digest
169    }
170
171    /// Writes the verification context that [`Self::context_digest`] commits to, with sighashes
172    /// computed under `branch_id`.
173    ///
174    /// Every field is fixed-size or length-prefixed, so different contexts never write the same
175    /// bytes.
176    fn write_context(
177        &self,
178        branch_id: ConsensusBranchId,
179        mut writer: impl io::Write,
180    ) -> io::Result<()> {
181        match self.transaction.unmined_id() {
182            UnminedTxId::Legacy(id) => {
183                writer.write_all(&[0])?;
184                writer.write_all(&id.0)?;
185            }
186            UnminedTxId::Witnessed(id) => {
187                writer.write_all(&[1])?;
188                writer.write_all(&id.as_bytes())?;
189            }
190        }
191        writer.write_all(&u32::from(branch_id).to_le_bytes())?;
192        CompactSizeMessage::try_from(self.all_previous_outputs.len())?
193            .zcash_serialize(&mut writer)?;
194        for output in self.all_previous_outputs.iter() {
195            output.zcash_serialize(&mut writer)?;
196        }
197        Ok(())
198    }
199
200    /// Returns the total number of P2SH sigops across all inputs of this transaction.
201    ///
202    /// Mirrors zcashd's [`GetP2SHSigOpCount()`].
203    ///
204    /// For each P2SH input (where the spent `scriptPubKey` is P2SH), the redeem script (the last
205    /// data push in the `scriptSig`) is parsed in "accurate" mode and its sigops are counted.
206    /// Coinbase inputs contribute zero.
207    ///
208    /// This must be included in the block-wide `MAX_BLOCK_SIGOPS` total to match zcashd's consensus
209    /// behavior.
210    ///
211    /// [`GetP2SHSigOpCount()`]: https://github.com/zcash/zcash/blob/v6.11.0/src/main.cpp#L840-L852
212    pub fn p2sh_sigops(&self) -> u32 {
213        p2sh_sigop_count(&self.transaction, &self.all_previous_outputs)
214    }
215
216    /// Verify if the script in the input at `input_index` of a transaction correctly spends the
217    /// matching [`transparent::Output`] it refers to.
218    #[allow(clippy::unwrap_in_result)]
219    pub fn is_valid(&self, input_index: usize) -> Result<(), Error> {
220        let previous_output = self
221            .all_previous_outputs
222            .get(input_index)
223            .filter(|_| self.all_previous_outputs.len() == self.vin().len())
224            .ok_or(Error::TxIndex)?
225            .clone();
226
227        let transparent::Output {
228            value: _,
229            lock_script,
230        } = previous_output;
231        let script_pub_key: &[u8] = lock_script.as_raw_bytes();
232
233        let flags = Flags::P2SH | Flags::CHECKLOCKTIMEVERIFY;
234
235        let lock_time = self.transaction.raw_lock_time();
236        let txin = self.vin().get(input_index).ok_or(Error::TxIndex)?;
237        let is_final = txin.sequence() == u32::MAX;
238
239        if *txin.prevout() == zp_transparent::OutPoint::NULL {
240            Err(Error::TxCoinbase)?;
241        }
242
243        let signature_script: &[u8] = &txin.script_sig().0 .0;
244
245        let script =
246            script::Raw::from_raw_parts(signature_script.to_vec(), script_pub_key.to_vec());
247
248        // Returning `None` fails only this signature check, like zcashd's `CheckSig`: the
249        // interpreter pushes false, which later opcodes such as `OP_NOT` may consume.
250        let calculate_sighash =
251            |script_code: &script::Code, hash_type: &zcash_script::signature::HashType| {
252                // For v5+ transactions: reject undefined hash_type values,
253                // matching zcashd's SighashType::parse behavior.
254                // Valid values: {0x01, 0x02, 0x03, 0x81, 0x82, 0x83}.
255                if self.transaction.version() >= 5 {
256                    let valid_v5_types: &[i32] = &[0x01, 0x02, 0x03, 0x81, 0x82, 0x83];
257                    if !valid_v5_types.contains(&hash_type.raw_bits()) {
258                        return None;
259                    }
260                }
261
262                // For v5+ transactions: reject SIGHASH_SINGLE when there is
263                // no corresponding output (an output at the same index as
264                // the input being verified). ZIP-244 §S.2a marks this as a
265                // consensus failure; zcashd throws in `SignatureHash` and
266                // `CheckSig` catches the exception to fail the script.
267                if self.transaction.version() >= 5
268                    && hash_type.signed_outputs() == zcash_script::signature::SignedOutputs::Single
269                    && input_index >= self.vout_len()
270                {
271                    return None;
272                }
273
274                let script_code_vec = script_code.0.clone();
275
276                // For pre-v5 (v4) transactions: zcashd serializes the raw
277                // hash_type byte into the sighash preimage (only masking with
278                // 0x1f for selection logic). Use the raw byte to match.
279                if self.transaction.version() < 5 {
280                    let raw_byte = hash_type.raw_bits() as u8;
281                    return Some(
282                        self.sighasher()
283                            .sighash_v4_raw(raw_byte, Some((input_index, script_code_vec)))
284                            .0,
285                    );
286                }
287
288                let mut our_hash_type = match hash_type.signed_outputs() {
289                    zcash_script::signature::SignedOutputs::All => HashType::ALL,
290                    zcash_script::signature::SignedOutputs::Single => HashType::SINGLE,
291                    zcash_script::signature::SignedOutputs::None => HashType::NONE,
292                };
293                if hash_type.anyone_can_pay() {
294                    our_hash_type |= HashType::ANYONECANPAY;
295                }
296                Some(
297                    self.sighasher()
298                        .sighash(our_hash_type, Some((input_index, script_code_vec)))
299                        .0,
300                )
301            };
302        let checker = CallbackTransactionSignatureChecker {
303            sighash: &calculate_sighash,
304            lock_time: i64::from(lock_time),
305            is_final,
306        };
307        match script.eval(flags, &checker) {
308            Ok(true) => Ok(()),
309            Ok(false) => Err(Error::ScriptInvalid),
310            Err((component, error)) => Err(Error::Interpreter { component, error }),
311        }
312    }
313}
314
315/// Trait for counting the number of transparent signature operations in the transparent inputs and
316/// outputs of a transaction.
317///
318/// Mirrors zcashd's [`GetLegacySigOpCount()`].
319///
320/// All transparent inputs are included, including the coinbase input script. zcashd charges
321/// coinbase `scriptSig` sigops against the block `MAX_BLOCK_SIGOPS` limit, so Zebra must do the
322/// same to avoid a consensus split.
323///
324/// [`GetLegacySigOpCount()`]: https://github.com/zcash/zcash/blob/v6.11.0/src/main.cpp#L826-L836
325pub trait Sigops {
326    /// Returns the number of transparent signature operations in the
327    /// transparent inputs and outputs of the given transaction.
328    fn sigops(&self) -> u32 {
329        self.scripts()
330            .iter()
331            .map(|script| legacy_sigop_count(script))
332            .sum()
333    }
334
335    /// Returns the input and output scripts in the transaction as owned byte vectors.
336    ///
337    /// For consensus sigop accounting, this must include the coinbase input
338    /// script (height prefix followed by extra data), matching zcashd's
339    /// `GetLegacySigOpCount()`.
340    fn scripts(&self) -> Vec<Vec<u8>>;
341}
342
343impl Sigops for zebra_chain::transaction::Transaction {
344    fn scripts(&self) -> Vec<Vec<u8>> {
345        let mut scripts: Vec<Vec<u8>> = self
346            .inputs()
347            .into_iter()
348            .map(|input| match &input {
349                transparent::Input::PrevOut { unlock_script, .. } => {
350                    unlock_script.as_raw_bytes().to_vec()
351                }
352                // Coinbase scriptSig = encoded height || extra data, which must be reconstructed
353                // for sigop counting. `coinbase_script()` round-trips through
354                // `write_coinbase_height`, which only fails when called on a malformed in-memory
355                // genesis coinbase. Any coinbase that was successfully deserialized round-trips
356                // cleanly, so this `expect` cannot fire on validation paths.
357                transparent::Input::Coinbase { .. } => input
358                    .coinbase_script()
359                    .expect("coinbase_script reconstructs from a deserialized coinbase input"),
360            })
361            .collect();
362
363        scripts.extend(
364            self.outputs()
365                .into_iter()
366                .map(|o| o.lock_script.as_raw_bytes().to_vec()),
367        );
368
369        scripts
370    }
371}
372
373impl Sigops for zebra_chain::transaction::UnminedTx {
374    fn scripts(&self) -> Vec<Vec<u8>> {
375        self.transaction.scripts()
376    }
377}
378
379impl Sigops for CachedFfiTransaction {
380    fn scripts(&self) -> Vec<Vec<u8>> {
381        self.transaction.scripts()
382    }
383}
384
385impl Sigops for zcash_primitives::transaction::Transaction {
386    fn scripts(&self) -> Vec<Vec<u8>> {
387        self.transparent_bundle()
388            .into_iter()
389            .flat_map(|bundle| {
390                // `zcash_primitives` stores the coinbase input's full serialized scriptSig (height
391                // prefix + extra data) in the synthesized input's script_sig, so it is included
392                // as-is for sigop counting.
393                bundle
394                    .vin
395                    .iter()
396                    .map(|i| i.script_sig().0 .0.clone())
397                    .chain(bundle.vout.iter().map(|o| o.script_pubkey().0 .0.clone()))
398            })
399            .collect()
400    }
401}
402
403/// Counts the signature operations in `script` like zcashd's `CScript::GetSigOpCount(false)`.
404///
405/// Output scripts can contain pushes larger than the 520-byte execution limit, because creating an
406/// output never executes its script. zcashd keeps counting after such a push, and so does
407/// `zcash_script` from version 0.6.1, which is why Zebra requires at least that version.
408pub fn legacy_sigop_count(script: &[u8]) -> u32 {
409    script::Code(script.to_vec()).sig_op_count(false)
410}
411
412/// Extract the redeem script bytes from a P2SH scriptSig.
413///
414/// Mirrors zcashd's P2SH redeem-script extraction in
415/// [`CScript::GetSigOpCount(const CScript& scriptSig)`].
416///
417/// Iterates the scriptSig opcodes and returns the last successfully pushed data value. Returns
418/// `None` if any opcode fails to parse, OR if any opcode is not a push value (zcashd: `opcode >
419/// OP_16`). This matches zcashd's behavior of returning 0 P2SH sigops for malformed or
420/// non-push-only scriptSigs.
421///
422/// [`CScript::GetSigOpCount(const CScript& scriptSig)`]: https://github.com/zcash/zcash/blob/v6.11.0/src/script/script.cpp#L176-L199
423fn extract_p2sh_redeem_script(unlock_script: &transparent::Script) -> Option<Vec<u8>> {
424    let code = script::Code(unlock_script.as_raw_bytes().to_vec());
425    let mut last_push_data: Option<Vec<u8>> = None;
426    for opcode in code.parse() {
427        match opcode {
428            Ok(PossiblyBad::Good(Opcode::PushValue(pv))) => {
429                last_push_data = Some(pv.value());
430            }
431            // Non-push opcode (operation, control, or bad) or parse error: zcashd returns 0 sigops
432            // in this case. Match that behavior by discarding any data collected so far.
433            _ => return None,
434        }
435    }
436    last_push_data
437}
438
439/// Returns the P2SH sigop count for a single input.
440///
441/// `spent_output` must be the output spent by `input`.
442///
443/// Returns 0 for non-P2SH inputs, coinbase inputs, and P2SH inputs where no redeem script can be
444/// extracted from the scriptSig (mirroring zcashd's `CScript::GetSigOpCount(scriptSig)`, which
445/// returns 0 when the scriptSig is not push-only).
446///
447/// This is the per-input counting used by [`p2sh_sigop_count`] for the block-wide consensus sigop
448/// total, and by the mempool standardness gate that rejects high-sigop P2SH inputs before script
449/// verification.
450pub fn p2sh_input_sigop_count(
451    input: &transparent::Input,
452    spent_output: &transparent::Output,
453) -> u32 {
454    let unlock_script = match input {
455        transparent::Input::PrevOut { unlock_script, .. } => unlock_script,
456        transparent::Input::Coinbase { .. } => return 0,
457    };
458
459    let lock_code = script::Code(spent_output.lock_script.as_raw_bytes().to_vec());
460
461    if !lock_code.is_pay_to_script_hash() {
462        return 0;
463    }
464
465    let Some(redeemed_bytes) = extract_p2sh_redeem_script(unlock_script) else {
466        return 0;
467    };
468
469    // Count the redeem script's sigops in zcashd's "accurate" mode, matching
470    // `GetP2SHSigOpCount` -> `CScript::GetSigOpCount(scriptSig)` -> `subscript.GetSigOpCount(true)`.
471    // The redeem script is at most 520 bytes, so `zcash_script`'s execution push limit cannot stop
472    // this count early. Disabled opcodes, including OP_CODESEPARATOR, do not stop it either.
473    script::Code(redeemed_bytes).sig_op_count(true)
474}
475
476/// Returns the total number of P2SH sigops across all inputs of `tx`.
477///
478/// Mirrors zcashd's [`GetP2SHSigOpCount()`].
479///
480/// Coinbase transactions always return zero, matching zcashd's early-return for `tx.IsCoinBase()`.
481/// Callers are therefore permitted to pass an empty `spent_outputs` slice for coinbase transactions
482/// (which is what the block-verifier does, since coinbase inputs have no previous output).
483///
484/// # Correctness
485///
486/// For non-coinbase transactions, `spent_outputs.len()` must equal the number of transparent inputs
487/// in `tx`. If the lengths differ, `zip()` silently truncates the longer iterator, causing an
488/// incorrect (undercount) result.
489///
490/// [`GetP2SHSigOpCount()`]: https://github.com/zcash/zcash/blob/v6.11.0/src/main.cpp#L840-L852
491pub fn p2sh_sigop_count(
492    tx: &zebra_chain::transaction::Transaction,
493    spent_outputs: &[transparent::Output],
494) -> u32 {
495    if tx.is_coinbase() {
496        return 0;
497    }
498
499    debug_assert_eq!(
500        tx.inputs().len(),
501        spent_outputs.len(),
502        "spent_outputs must align with transaction inputs for non-coinbase txs"
503    );
504
505    tx.inputs()
506        .iter()
507        .zip(spent_outputs.iter())
508        .map(|(input, spent_output)| p2sh_input_sigop_count(input, spent_output))
509        .sum()
510}