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::script;
19use zebra_chain::{
20    parameters::NetworkUpgrade,
21    transaction::{HashType, SigHasher},
22    transparent,
23};
24
25/// An Error type representing the error codes returned from zcash_script.
26#[derive(Clone, Debug, Error, PartialEq, Eq)]
27#[non_exhaustive]
28pub enum Error {
29    /// script verification failed
30    ScriptInvalid,
31    /// input index out of bounds
32    TxIndex,
33    /// tx is a coinbase transaction and should not be verified
34    TxCoinbase,
35    /// unknown error from zcash_script: {0}
36    Unknown(libzcash_script::Error),
37    /// transaction is invalid according to zebra_chain (not a zcash_script error)
38    TxInvalid(#[from] zebra_chain::Error),
39}
40
41impl fmt::Display for Error {
42    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43        f.write_str(&match self {
44            Error::ScriptInvalid => "script verification failed".to_owned(),
45            Error::TxIndex => "input index out of bounds".to_owned(),
46            Error::TxCoinbase => {
47                "tx is a coinbase transaction and should not be verified".to_owned()
48            }
49            Error::Unknown(e) => format!("unknown error from zcash_script: {e:?}"),
50            Error::TxInvalid(e) => format!("tx is invalid: {e}"),
51        })
52    }
53}
54
55impl From<libzcash_script::Error> for Error {
56    #[allow(non_upper_case_globals)]
57    fn from(err_code: libzcash_script::Error) -> Error {
58        Error::Unknown(err_code)
59    }
60}
61
62/// Get the interpreter according to the feature flag
63fn get_interpreter(
64    sighash: zcash_script::interpreter::SighashCalculator<'_>,
65    lock_time: u32,
66    is_final: bool,
67) -> impl ZcashScript + use<'_> {
68    #[cfg(feature = "comparison-interpreter")]
69    return libzcash_script::cxx_rust_comparison_interpreter(sighash, lock_time, is_final);
70    #[cfg(not(feature = "comparison-interpreter"))]
71    libzcash_script::CxxInterpreter {
72        sighash,
73        lock_time,
74        is_final,
75    }
76}
77
78/// A preprocessed Transaction which can be used to verify scripts within said
79/// Transaction.
80#[derive(Debug)]
81pub struct CachedFfiTransaction {
82    /// The deserialized Zebra transaction.
83    ///
84    /// This field is private so that `transaction`, and `all_previous_outputs` always match.
85    transaction: Arc<zebra_chain::transaction::Transaction>,
86
87    /// The outputs from previous transactions that match each input in the transaction
88    /// being verified.
89    all_previous_outputs: Arc<Vec<transparent::Output>>,
90
91    /// The sighasher context to use to compute sighashes.
92    sighasher: SigHasher,
93}
94
95impl CachedFfiTransaction {
96    /// Construct a `CachedFfiTransaction` from a `Transaction` and the outputs
97    /// from previous transactions that match each input in the transaction
98    /// being verified.
99    pub fn new(
100        transaction: Arc<zebra_chain::transaction::Transaction>,
101        all_previous_outputs: Arc<Vec<transparent::Output>>,
102        nu: NetworkUpgrade,
103    ) -> Result<Self, Error> {
104        let sighasher = transaction.sighasher(nu, all_previous_outputs.clone())?;
105        Ok(Self {
106            transaction,
107            all_previous_outputs,
108            sighasher,
109        })
110    }
111
112    /// Returns the transparent inputs for this transaction.
113    pub fn inputs(&self) -> &[transparent::Input] {
114        self.transaction.inputs()
115    }
116
117    /// Returns the outputs from previous transactions that match each input in the transaction
118    /// being verified.
119    pub fn all_previous_outputs(&self) -> &Vec<transparent::Output> {
120        &self.all_previous_outputs
121    }
122
123    /// Return the sighasher being used for this transaction.
124    pub fn sighasher(&self) -> &SigHasher {
125        &self.sighasher
126    }
127
128    /// Verify if the script in the input at `input_index` of a transaction correctly spends the
129    /// matching [`transparent::Output`] it refers to.
130    #[allow(clippy::unwrap_in_result)]
131    pub fn is_valid(&self, input_index: usize) -> Result<(), Error> {
132        let previous_output = self
133            .all_previous_outputs
134            .get(input_index)
135            .ok_or(Error::TxIndex)?
136            .clone();
137        let transparent::Output {
138            value: _,
139            lock_script,
140        } = previous_output;
141        let script_pub_key: &[u8] = lock_script.as_raw_bytes();
142
143        let flags = zcash_script::interpreter::Flags::P2SH
144            | zcash_script::interpreter::Flags::CHECKLOCKTIMEVERIFY;
145
146        let lock_time = self.transaction.raw_lock_time();
147        let is_final = self.transaction.inputs()[input_index].sequence() == u32::MAX;
148        let signature_script = match &self.transaction.inputs()[input_index] {
149            transparent::Input::PrevOut {
150                outpoint: _,
151                unlock_script,
152                sequence: _,
153            } => unlock_script.as_raw_bytes(),
154            transparent::Input::Coinbase { .. } => Err(Error::TxCoinbase)?,
155        };
156
157        let script =
158            script::Raw::from_raw_parts(signature_script.to_vec(), script_pub_key.to_vec());
159
160        let calculate_sighash =
161            |script_code: &script::Code, hash_type: &zcash_script::signature::HashType| {
162                let script_code_vec = script_code.0.clone();
163                let mut our_hash_type = match hash_type.signed_outputs() {
164                    zcash_script::signature::SignedOutputs::All => HashType::ALL,
165                    zcash_script::signature::SignedOutputs::Single => HashType::SINGLE,
166                    zcash_script::signature::SignedOutputs::None => HashType::NONE,
167                };
168                if hash_type.anyone_can_pay() {
169                    our_hash_type |= HashType::ANYONECANPAY;
170                }
171                Some(
172                    self.sighasher()
173                        .sighash(our_hash_type, Some((input_index, script_code_vec)))
174                        .0,
175                )
176            };
177        let interpreter = get_interpreter(&calculate_sighash, lock_time, is_final);
178        interpreter
179            .verify_callback(&script, flags)
180            .map_err(|(_, e)| Error::from(e))
181            .and_then(|res| {
182                if res {
183                    Ok(())
184                } else {
185                    Err(Error::ScriptInvalid)
186                }
187            })
188    }
189}
190
191/// Trait for counting the number of transparent signature operations
192/// in the transparent inputs and outputs of a transaction.
193pub trait Sigops {
194    /// Returns the number of transparent signature operations in the
195    /// transparent inputs and outputs of the given transaction.
196    fn sigops(&self) -> Result<u32, libzcash_script::Error> {
197        let interpreter = get_interpreter(&|_, _| None, 0, true);
198
199        Ok(self.scripts().try_fold(0, |acc, s| {
200            interpreter
201                .legacy_sigop_count_script(&script::Code(s.to_vec()))
202                .map(|n| acc + n)
203        })?)
204    }
205
206    /// Returns an iterator over the input and output scripts in the transaction.
207    ///
208    /// The number of input scripts in a coinbase tx is zero.
209    fn scripts(&self) -> impl Iterator<Item = &[u8]>;
210}
211
212impl Sigops for zebra_chain::transaction::Transaction {
213    fn scripts(&self) -> impl Iterator<Item = &[u8]> {
214        self.inputs()
215            .iter()
216            .filter_map(|input| match input {
217                transparent::Input::PrevOut { unlock_script, .. } => {
218                    Some(unlock_script.as_raw_bytes())
219                }
220                transparent::Input::Coinbase { .. } => None,
221            })
222            .chain(self.outputs().iter().map(|o| o.lock_script.as_raw_bytes()))
223    }
224}
225
226impl Sigops for zebra_chain::transaction::UnminedTx {
227    fn scripts(&self) -> impl Iterator<Item = &[u8]> {
228        self.transaction.scripts()
229    }
230}
231
232impl Sigops for CachedFfiTransaction {
233    fn scripts(&self) -> impl Iterator<Item = &[u8]> {
234        self.transaction.scripts()
235    }
236}
237
238impl Sigops for zcash_primitives::transaction::Transaction {
239    fn scripts(&self) -> impl Iterator<Item = &[u8]> {
240        self.transparent_bundle().into_iter().flat_map(|bundle| {
241            (!bundle.is_coinbase())
242                .then(|| bundle.vin.iter().map(|i| i.script_sig().0 .0.as_slice()))
243                .into_iter()
244                .flatten()
245                .chain(
246                    bundle
247                        .vout
248                        .iter()
249                        .map(|o| o.script_pubkey().0 .0.as_slice()),
250                )
251        })
252    }
253}