zebra_script/lib.rs
1//! Zebra script verification wrapping zcashd's zcash_script library
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// We allow unsafe code, so we can call zcash_script
6#![allow(unsafe_code)]
7
8#[cfg(test)]
9mod tests;
10
11use core::fmt;
12use std::sync::Arc;
13
14use thiserror::Error;
15
16use libzcash_script::ZcashScript;
17
18use zcash_script::{opcode::PossiblyBad, script, script::Evaluable as _, Opcode};
19use zcash_transparent::bundle as zp_transparent;
20use zebra_chain::{
21 parameters::NetworkUpgrade,
22 transaction::{HashType, SigHasher},
23 transparent,
24};
25
26/// An Error type representing the error codes returned from zcash_script.
27#[derive(Clone, Debug, Error, PartialEq, Eq)]
28#[non_exhaustive]
29pub enum Error {
30 /// script verification failed
31 ScriptInvalid,
32 /// input index out of bounds
33 TxIndex,
34 /// tx is a coinbase transaction and should not be verified
35 TxCoinbase,
36 /// unknown error from zcash_script: {0}
37 Unknown(libzcash_script::Error),
38 /// transaction is invalid according to zebra_chain (not a zcash_script error)
39 TxInvalid(#[from] zebra_chain::Error),
40}
41
42impl fmt::Display for Error {
43 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44 f.write_str(&match self {
45 Error::ScriptInvalid => "script verification failed".to_owned(),
46 Error::TxIndex => "input index out of bounds".to_owned(),
47 Error::TxCoinbase => {
48 "tx is a coinbase transaction and should not be verified".to_owned()
49 }
50 Error::Unknown(e) => format!("unknown error from zcash_script: {e:?}"),
51 Error::TxInvalid(e) => format!("tx is invalid: {e}"),
52 })
53 }
54}
55
56impl From<libzcash_script::Error> for Error {
57 #[allow(non_upper_case_globals)]
58 fn from(err_code: libzcash_script::Error) -> Error {
59 Error::Unknown(err_code)
60 }
61}
62
63/// Get the interpreter according to the feature flag
64fn get_interpreter(
65 sighash: zcash_script::interpreter::SighashCalculator<'_>,
66 lock_time: u32,
67 is_final: bool,
68) -> impl ZcashScript + use<'_> {
69 #[cfg(feature = "comparison-interpreter")]
70 return libzcash_script::cxx_rust_comparison_interpreter(sighash, lock_time, is_final);
71 #[cfg(not(feature = "comparison-interpreter"))]
72 libzcash_script::CxxInterpreter {
73 sighash,
74 lock_time,
75 is_final,
76 }
77}
78
79/// A preprocessed Transaction which can be used to verify scripts within said
80/// Transaction.
81#[derive(Debug)]
82pub struct CachedFfiTransaction {
83 /// The deserialized Zebra transaction.
84 ///
85 /// This field is private so that `transaction`, and `all_previous_outputs` always match.
86 transaction: Arc<zebra_chain::transaction::Transaction>,
87
88 /// The outputs from previous transactions that match each input in the transaction
89 /// being verified.
90 all_previous_outputs: Arc<Vec<transparent::Output>>,
91
92 /// The sighasher context to use to compute sighashes.
93 sighasher: SigHasher,
94}
95
96impl CachedFfiTransaction {
97 /// Construct a `CachedFfiTransaction` from a `Transaction` and the outputs
98 /// from previous transactions that match each input in the transaction
99 /// being verified.
100 pub fn new(
101 transaction: Arc<zebra_chain::transaction::Transaction>,
102 all_previous_outputs: Arc<Vec<transparent::Output>>,
103 nu: NetworkUpgrade,
104 ) -> Result<Self, Error> {
105 let sighasher = SigHasher::new(&transaction, nu, all_previous_outputs.clone())?;
106 Ok(Self {
107 transaction,
108 all_previous_outputs,
109 sighasher,
110 })
111 }
112
113 /// Returns the transparent inputs of this transaction, borrowed from the underlying
114 /// `zcash_primitives` transaction.
115 fn vin(&self) -> &[zp_transparent::TxIn<zp_transparent::Authorized>] {
116 self.transaction
117 .transparent_bundle()
118 .map(|bundle| bundle.vin.as_slice())
119 .unwrap_or_default()
120 }
121
122 /// Returns the number of transparent outputs of this transaction, read from the underlying
123 /// `zcash_primitives` transaction.
124 ///
125 /// `Transaction::outputs()` rebuilds and converts the whole output vector, which is far too
126 /// expensive for the per-signature-check sighash callback.
127 fn vout_len(&self) -> usize {
128 self.transaction
129 .transparent_bundle()
130 .map_or(0, |bundle| bundle.vout.len())
131 }
132
133 /// Returns the outputs from previous transactions that match each input in the transaction
134 /// being verified.
135 pub fn all_previous_outputs(&self) -> &Vec<transparent::Output> {
136 &self.all_previous_outputs
137 }
138
139 /// Return the sighasher being used for this transaction.
140 pub fn sighasher(&self) -> &SigHasher {
141 &self.sighasher
142 }
143
144 /// Returns the total number of P2SH sigops across all inputs of this transaction.
145 ///
146 /// Mirrors zcashd's [`GetP2SHSigOpCount()`].
147 ///
148 /// For each P2SH input (where the spent `scriptPubKey` is P2SH), the redeem script (the last
149 /// data push in the `scriptSig`) is parsed in "accurate" mode and its sigops are counted.
150 /// Coinbase inputs contribute zero.
151 ///
152 /// This must be included in the block-wide `MAX_BLOCK_SIGOPS` total to match zcashd's consensus
153 /// behavior.
154 ///
155 /// [`GetP2SHSigOpCount()`]: https://github.com/zcash/zcash/blob/v6.11.0/src/main.cpp#L840-L852
156 pub fn p2sh_sigops(&self) -> u32 {
157 p2sh_sigop_count(&self.transaction, &self.all_previous_outputs)
158 }
159
160 /// Verify if the script in the input at `input_index` of a transaction correctly spends the
161 /// matching [`transparent::Output`] it refers to.
162 #[allow(clippy::unwrap_in_result)]
163 pub fn is_valid(&self, input_index: usize) -> Result<(), Error> {
164 let previous_output = self
165 .all_previous_outputs
166 .get(input_index)
167 .filter(|_| self.all_previous_outputs.len() == self.vin().len())
168 .ok_or(Error::TxIndex)?
169 .clone();
170
171 let transparent::Output {
172 value: _,
173 lock_script,
174 } = previous_output;
175 let script_pub_key: &[u8] = lock_script.as_raw_bytes();
176
177 let flags = zcash_script::interpreter::Flags::P2SH
178 | zcash_script::interpreter::Flags::CHECKLOCKTIMEVERIFY;
179
180 let lock_time = self.transaction.raw_lock_time();
181 let txin = self.vin().get(input_index).ok_or(Error::TxIndex)?;
182 let is_final = txin.sequence() == u32::MAX;
183
184 if *txin.prevout() == zp_transparent::OutPoint::NULL {
185 Err(Error::TxCoinbase)?;
186 }
187
188 let signature_script: &[u8] = &txin.script_sig().0 .0;
189
190 let script =
191 script::Raw::from_raw_parts(signature_script.to_vec(), script_pub_key.to_vec());
192
193 let calculate_sighash =
194 |script_code: &script::Code, hash_type: &zcash_script::signature::HashType| {
195 // Inner helper: returns None when the hash type is invalid
196 // and the callback should signal failure.
197 let computed: Option<[u8; 32]> = (|| {
198 // For v5+ transactions: reject undefined hash_type values,
199 // matching zcashd's SighashType::parse behavior.
200 // Valid values: {0x01, 0x02, 0x03, 0x81, 0x82, 0x83}.
201 if self.transaction.version() >= 5 {
202 let valid_v5_types: &[i32] = &[0x01, 0x02, 0x03, 0x81, 0x82, 0x83];
203 if !valid_v5_types.contains(&hash_type.raw_bits()) {
204 return None;
205 }
206 }
207
208 // For v5+ transactions: reject SIGHASH_SINGLE when there is
209 // no corresponding output (an output at the same index as
210 // the input being verified). ZIP-244 §S.2a marks this as a
211 // consensus failure; zcashd throws in `SignatureHash` and
212 // `CheckSig` catches the exception to fail the script.
213 if self.transaction.version() >= 5
214 && hash_type.signed_outputs()
215 == zcash_script::signature::SignedOutputs::Single
216 && input_index >= self.vout_len()
217 {
218 return None;
219 }
220
221 let script_code_vec = script_code.0.clone();
222
223 // For pre-v5 (v4) transactions: zcashd serializes the raw
224 // hash_type byte into the sighash preimage (only masking with
225 // 0x1f for selection logic). Use the raw byte to match.
226 if self.transaction.version() < 5 {
227 let raw_byte = hash_type.raw_bits() as u8;
228 return Some(
229 self.sighasher()
230 .sighash_v4_raw(raw_byte, Some((input_index, script_code_vec)))
231 .0,
232 );
233 }
234
235 let mut our_hash_type = match hash_type.signed_outputs() {
236 zcash_script::signature::SignedOutputs::All => HashType::ALL,
237 zcash_script::signature::SignedOutputs::Single => HashType::SINGLE,
238 zcash_script::signature::SignedOutputs::None => HashType::NONE,
239 };
240 if hash_type.anyone_can_pay() {
241 our_hash_type |= HashType::ANYONECANPAY;
242 }
243 Some(
244 self.sighasher()
245 .sighash(our_hash_type, Some((input_index, script_code_vec)))
246 .0,
247 )
248 })();
249
250 // Workaround for the libzcash_script callback API: returning
251 // `None` from this callback does not propagate failure to the
252 // C++ verifier.
253 //
254 // Instead of returning `None` to indicate an error, we return a
255 // per-call randomly-generated dummy sighash so any signature
256 // fails to verify with overwhelming probability. Note that a
257 // fixed sentinel value would be unsafe: an attacker who knows
258 // it can construct an ECDSA signature that verifies against any
259 // 32-byte value under a chosen pubkey.
260 //
261 // This shim can be removed once libzcash_script propagates
262 // callback failure to the C++ verifier.
263 Some(computed.unwrap_or_else(|| {
264 use rand::{rand_core::UnwrapErr, rngs::SysRng, Rng};
265 let mut bytes = [0u8; 32];
266 UnwrapErr(SysRng).fill_bytes(&mut bytes);
267 bytes
268 }))
269 };
270 let interpreter = get_interpreter(&calculate_sighash, lock_time, is_final);
271 interpreter
272 .verify_callback(&script, flags)
273 .map_err(|(_, e)| Error::from(e))
274 .and_then(|res| {
275 if res {
276 Ok(())
277 } else {
278 Err(Error::ScriptInvalid)
279 }
280 })
281 }
282}
283
284/// Trait for counting the number of transparent signature operations in the transparent inputs and
285/// outputs of a transaction.
286///
287/// Mirrors zcashd's [`GetLegacySigOpCount()`].
288///
289/// All transparent inputs are included, including the coinbase input script. zcashd charges
290/// coinbase `scriptSig` sigops against the block `MAX_BLOCK_SIGOPS` limit, so Zebra must do the
291/// same to avoid a consensus split.
292///
293/// [`GetLegacySigOpCount()`]: https://github.com/zcash/zcash/blob/v6.11.0/src/main.cpp#L826-L836
294pub trait Sigops {
295 /// Returns the number of transparent signature operations in the
296 /// transparent inputs and outputs of the given transaction.
297 fn sigops(&self) -> Result<u32, libzcash_script::Error> {
298 let interpreter = get_interpreter(&|_, _| None, 0, true);
299
300 Ok(self.scripts().into_iter().try_fold(0, |acc, s| {
301 interpreter
302 .legacy_sigop_count_script(&script::Code(s))
303 .map(|n| acc + n)
304 })?)
305 }
306
307 /// Returns the input and output scripts in the transaction as owned byte vectors.
308 ///
309 /// For consensus sigop accounting, this must include the coinbase input
310 /// script (height prefix followed by extra data), matching zcashd's
311 /// `GetLegacySigOpCount()`.
312 fn scripts(&self) -> Vec<Vec<u8>>;
313}
314
315impl Sigops for zebra_chain::transaction::Transaction {
316 fn scripts(&self) -> Vec<Vec<u8>> {
317 let mut scripts: Vec<Vec<u8>> = self
318 .inputs()
319 .into_iter()
320 .map(|input| match &input {
321 transparent::Input::PrevOut { unlock_script, .. } => {
322 unlock_script.as_raw_bytes().to_vec()
323 }
324 // Coinbase scriptSig = encoded height || extra data, which must be reconstructed
325 // for sigop counting. `coinbase_script()` round-trips through
326 // `write_coinbase_height`, which only fails when called on a malformed in-memory
327 // genesis coinbase. Any coinbase that was successfully deserialized round-trips
328 // cleanly, so this `expect` cannot fire on validation paths.
329 transparent::Input::Coinbase { .. } => input
330 .coinbase_script()
331 .expect("coinbase_script reconstructs from a deserialized coinbase input"),
332 })
333 .collect();
334
335 scripts.extend(
336 self.outputs()
337 .into_iter()
338 .map(|o| o.lock_script.as_raw_bytes().to_vec()),
339 );
340
341 scripts
342 }
343}
344
345impl Sigops for zebra_chain::transaction::UnminedTx {
346 fn scripts(&self) -> Vec<Vec<u8>> {
347 self.transaction.scripts()
348 }
349}
350
351impl Sigops for CachedFfiTransaction {
352 fn scripts(&self) -> Vec<Vec<u8>> {
353 self.transaction.scripts()
354 }
355}
356
357impl Sigops for zcash_primitives::transaction::Transaction {
358 fn scripts(&self) -> Vec<Vec<u8>> {
359 self.transparent_bundle()
360 .into_iter()
361 .flat_map(|bundle| {
362 // `zcash_primitives` stores the coinbase input's full serialized scriptSig (height
363 // prefix + extra data) in the synthesized input's script_sig, so it is included
364 // as-is for sigop counting.
365 bundle
366 .vin
367 .iter()
368 .map(|i| i.script_sig().0 .0.clone())
369 .chain(bundle.vout.iter().map(|o| o.script_pubkey().0 .0.clone()))
370 })
371 .collect()
372 }
373}
374
375/// Extract the redeem script bytes from a P2SH scriptSig.
376///
377/// Mirrors zcashd's P2SH redeem-script extraction in
378/// [`CScript::GetSigOpCount(const CScript& scriptSig)`].
379///
380/// Iterates the scriptSig opcodes and returns the last successfully pushed data value. Returns
381/// `None` if any opcode fails to parse, OR if any opcode is not a push value (zcashd: `opcode >
382/// OP_16`). This matches zcashd's behavior of returning 0 P2SH sigops for malformed or
383/// non-push-only scriptSigs.
384///
385/// [`CScript::GetSigOpCount(const CScript& scriptSig)`]: https://github.com/zcash/zcash/blob/v6.11.0/src/script/script.cpp#L176-L199
386fn extract_p2sh_redeem_script(unlock_script: &transparent::Script) -> Option<Vec<u8>> {
387 let code = script::Code(unlock_script.as_raw_bytes().to_vec());
388 let mut last_push_data: Option<Vec<u8>> = None;
389 for opcode in code.parse() {
390 match opcode {
391 Ok(PossiblyBad::Good(Opcode::PushValue(pv))) => {
392 last_push_data = Some(pv.value());
393 }
394 // Non-push opcode (operation, control, or bad) or parse error: zcashd returns 0 sigops
395 // in this case. Match that behavior by discarding any data collected so far.
396 _ => return None,
397 }
398 }
399 last_push_data
400}
401
402/// Returns the P2SH sigop count for a single input.
403///
404/// `spent_output` must be the output spent by `input`.
405///
406/// Returns 0 for non-P2SH inputs, coinbase inputs, and P2SH inputs where no redeem script can be
407/// extracted from the scriptSig (mirroring zcashd's `CScript::GetSigOpCount(scriptSig)`, which
408/// returns 0 when the scriptSig is not push-only).
409///
410/// This is the per-input counting used by [`p2sh_sigop_count`] for the block-wide consensus sigop
411/// total, and by the mempool standardness gate that rejects high-sigop P2SH inputs before script
412/// verification.
413pub fn p2sh_input_sigop_count(
414 input: &transparent::Input,
415 spent_output: &transparent::Output,
416) -> u32 {
417 let unlock_script = match input {
418 transparent::Input::PrevOut { unlock_script, .. } => unlock_script,
419 transparent::Input::Coinbase { .. } => return 0,
420 };
421
422 let lock_code = script::Code(spent_output.lock_script.as_raw_bytes().to_vec());
423
424 if !lock_code.is_pay_to_script_hash() {
425 return 0;
426 }
427
428 let Some(redeemed_bytes) = extract_p2sh_redeem_script(unlock_script) else {
429 return 0;
430 };
431
432 // Count the redeem script's sigops in zcashd's "accurate" mode, matching
433 // `GetP2SHSigOpCount` -> `CScript::GetSigOpCount(scriptSig)` -> `subscript.GetSigOpCount(true)`.
434 // Relies on the patched `zcash_script` (see `[patch.crates-io]`) whose `sig_op_count` no longer
435 // short-circuits on disabled opcodes (incl. OP_CODESEPARATOR), which would otherwise undercount.
436 script::Code(redeemed_bytes).sig_op_count(true)
437}
438
439/// Returns the total number of P2SH sigops across all inputs of `tx`.
440///
441/// Mirrors zcashd's [`GetP2SHSigOpCount()`].
442///
443/// Coinbase transactions always return zero, matching zcashd's early-return for `tx.IsCoinBase()`.
444/// Callers are therefore permitted to pass an empty `spent_outputs` slice for coinbase transactions
445/// (which is what the block-verifier does, since coinbase inputs have no previous output).
446///
447/// # Correctness
448///
449/// For non-coinbase transactions, `spent_outputs.len()` must equal the number of transparent inputs
450/// in `tx`. If the lengths differ, `zip()` silently truncates the longer iterator, causing an
451/// incorrect (undercount) result.
452///
453/// [`GetP2SHSigOpCount()`]: https://github.com/zcash/zcash/blob/v6.11.0/src/main.cpp#L840-L852
454pub fn p2sh_sigop_count(
455 tx: &zebra_chain::transaction::Transaction,
456 spent_outputs: &[transparent::Output],
457) -> u32 {
458 if tx.is_coinbase() {
459 return 0;
460 }
461
462 debug_assert_eq!(
463 tx.inputs().len(),
464 spent_outputs.len(),
465 "spent_outputs must align with transaction inputs for non-coinbase txs"
466 );
467
468 tx.inputs()
469 .iter()
470 .zip(spent_outputs.iter())
471 .map(|(input, spent_output)| p2sh_input_sigop_count(input, spent_output))
472 .sum()
473}