subcoin_script/
lib.rs

1//! # Bitcoin Script Interpreter
2//!
3//! This crate implements a Bitcoin Script interpreter in Rust. It provides functionality to
4//! interpret and evaluate Bitcoin scripts, similar to the Bitcoin Core implementation, but with a
5//! focus on readability and compatibility with Rust. Performance optimizations will be pursued
6//! in future updates.
7//!
8//! ## Key Points
9//!
10//! - Some functions are directly ported from Bitcoin Core and may not follow typical Rust idioms.
11//!   They are intentionally written in a way that is closer to the original C++ code to preserve
12//!   functionality and logic.
13//!
14//! - Several components, including tests prior to the Taproot upgrade, are ported from the
15//!   Parity-Bitcoin project to reuse their valuable work for Bitcoin's older features and standards.
16//!
17//! ## Caveats
18//!
19//! This library is **not widely used** and **lacks comprehensive tests**. As a result, **never use it for production use**!
20//! Please use it with caution, and only in non-critical applications or for experimentation purposes.
21
22mod constants;
23mod error;
24mod interpreter;
25mod num;
26mod opcode;
27mod signature_checker;
28pub mod solver;
29mod stack;
30#[cfg(test)]
31mod tests;
32
33use bitcoin::hashes::Hash;
34use bitcoin::{TapLeafHash, secp256k1};
35use bitflags::bitflags;
36
37pub use self::error::Error;
38pub use self::interpreter::verify_script;
39pub use self::signature_checker::{
40    NoSignatureCheck, SignatureChecker, SignatureError, TransactionSignatureChecker,
41};
42
43pub type H256 = bitcoin::hashes::sha256::Hash;
44pub type SchnorrSignature = bitcoin::taproot::Signature;
45
46/// Same semantic with [`bitcoin::ecdsa::Signature`] with the following differences:
47///
48/// - `sighash_type` uses u32 instead of [`bitcoin::EcdsaSighashType`].
49/// - Ensure lower S via `normalize_s()`.
50#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
51pub struct EcdsaSignature {
52    /// The underlying ECDSA Signature.
53    pub signature: secp256k1::ecdsa::Signature,
54    /// The corresponding hash type.
55    pub sighash_type: u32,
56}
57
58impl EcdsaSignature {
59    /// Constructs a [`EcdsaSignature`] from the full sig bytes.
60    ///
61    /// https://github.com/bitcoin/bitcoin/blob/82ba50513425bf0568d4f9456282dc9713132490/src/pubkey.cpp#L285
62    /// https://github.com/bitcoin/bitcoin/blob/82ba50513425bf0568d4f9456282dc9713132490/src/pubkey.cpp#L290
63    pub fn parse_der_lax(full_sig_bytes: &[u8]) -> Result<Self, bitcoin::ecdsa::Error> {
64        let (sighash_type, sig) = full_sig_bytes
65            .split_last()
66            .ok_or(bitcoin::ecdsa::Error::EmptySignature)?;
67        let sighash_type = *sighash_type as u32;
68
69        let mut signature = secp256k1::ecdsa::Signature::from_der_lax(sig)?;
70
71        // libsecp256k1's ECDSA verification requires lower-S signatures, which have
72        // not historically been enforced in Bitcoin, so normalize them first.
73        signature.normalize_s();
74
75        Ok(Self {
76            signature,
77            sighash_type,
78        })
79    }
80}
81
82bitflags! {
83    /// Script verification flags.
84    ///
85    /// https://github.com/bitcoin/bitcoin/blob/6f9db1ebcab4064065ccd787161bf2b87e03cc1f/src/script/interpreter.h#L45
86    #[derive(Debug, Clone)]
87    pub struct VerifyFlags: u32 {
88        const NONE = 0;
89
90        /// Evaluate P2SH subscripts (BIP16).
91        const P2SH = 1 << 0;
92
93        /// Passing a non-strict-DER signature or one with undefined hashtype to a checksig operation causes script failure.
94        /// Evaluating a pubkey that is not (0x04 + 64 bytes) or (0x02 or 0x03 + 32 bytes) by checksig causes script failure.
95        /// (not used or intended as a consensus rule).
96        const STRICTENC = 1 << 1;
97
98        // Passing a non-strict-DER signature to a checksig operation causes script failure (BIP62 rule 1)
99        const DERSIG = 1 << 2;
100
101        // Passing a non-strict-DER signature or one with S > order/2 to a checksig operation causes script failure
102        // (BIP62 rule 5)
103        const LOW_S = 1 << 3;
104
105        // verify dummy stack item consumed by CHECKMULTISIG is of zero-length (BIP62 rule 7).
106        const NULLDUMMY = 1 << 4;
107
108        // Using a non-push operator in the scriptSig causes script failure (BIP62 rule 2).
109        const SIGPUSHONLY = 1 << 5;
110
111        // Require minimal encodings for all push operations (OP_0... OP_16, OP_1NEGATE where possible, direct
112        // pushes up to 75 bytes, OP_PUSHDATA up to 255 bytes, OP_PUSHDATA2 for anything larger). Evaluating
113        // any other push causes the script to fail (BIP62 rule 3).
114        // In addition, whenever a stack element is interpreted as a number, it must be of minimal length (BIP62 rule 4).
115        const MINIMALDATA = 1 << 6;
116
117        // Discourage use of NOPs reserved for upgrades (NOP1-10)
118        //
119        // Provided so that nodes can avoid accepting or mining transactions
120        // containing executed NOP's whose meaning may change after a soft-fork,
121        // thus rendering the script invalid; with this flag set executing
122        // discouraged NOPs fails the script. This verification flag will never be
123        // a mandatory flag applied to scripts in a block. NOPs that are not
124        // executed, e.g.  within an unexecuted IF ENDIF block, are *not* rejected.
125        // NOPs that have associated forks to give them new meaning (CLTV, CSV)
126        // are not subject to this rule.
127        const DISCOURAGE_UPGRADABLE_NOPS = 1 << 7;
128
129        // Require that only a single stack element remains after evaluation. This changes the success criterion from
130        // "At least one stack element must remain, and when interpreted as a boolean, it must be true" to
131        // "Exactly one stack element must remain, and when interpreted as a boolean, it must be true".
132        // (BIP62 rule 6)
133        // Note: CLEANSTACK should never be used without P2SH or WITNESS.
134        // Note: WITNESS_V0 and TAPSCRIPT script execution have behavior similar to CLEANSTACK as part of their
135        //       consensus rules. It is automatic there and does not need this flag.
136        const CLEANSTACK = 1 << 8;
137
138        // Verify CHECKLOCKTIMEVERIFY
139        //
140        // See BIP65 for details.
141        const CHECKLOCKTIMEVERIFY = 1 << 9;
142
143        // support CHECKSEQUENCEVERIFY opcode
144        //
145        // See BIP112 for details
146        const CHECKSEQUENCEVERIFY = 1 << 10;
147
148        // Support segregated witness
149        const WITNESS = 1 << 11;
150
151        // Making v1-v16 witness program non-standard
152        const DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM = 1 << 12;
153
154        // Segwit script only: Require the argument of OP_IF/NOTIF to be exactly 0x01 or empty vector
155        //
156        // Note: TAPSCRIPT script execution has behavior similar to MINIMALIF as part of its consensus
157        //       rules. It is automatic there and does not depend on this flag.
158        const MINIMALIF = 1 << 13;
159
160        // Signature(s) must be empty vector if a CHECK(MULTI)SIG operation failed
161        const NULLFAIL = 1 << 14;
162
163        // Public keys in segregated witness scripts must be compressed
164        const WITNESS_PUBKEYTYPE = 1 << 15;
165
166        // Making OP_CODESEPARATOR and FindAndDelete fail any non-segwit scripts
167        const CONST_SCRIPTCODE = 1 << 16;
168
169        // Taproot/Tapscript validation (BIPs 341 & 342)
170        const TAPROOT = 1 << 17;
171
172        // Making unknown Taproot leaf versions non-standard
173        const DISCOURAGE_UPGRADABLE_TAPROOT_VERSION = 1 << 18;
174
175        // Making unknown OP_SUCCESS non-standard
176        const DISCOURAGE_OP_SUCCESS = 1 << 19;
177
178        // Making unknown public key versions (in BIP 342 scripts) non-standard
179        const DISCOURAGE_UPGRADABLE_PUBKEYTYPE = 1 << 20;
180    }
181}
182
183impl VerifyFlags {
184    pub fn verify_minimaldata(&self) -> bool {
185        self.contains(Self::MINIMALDATA)
186    }
187
188    pub fn verify_sigpushonly(&self) -> bool {
189        self.contains(Self::SIGPUSHONLY)
190    }
191
192    pub fn verify_p2sh(&self) -> bool {
193        self.contains(Self::P2SH)
194    }
195
196    pub fn verify_witness(&self) -> bool {
197        self.contains(Self::WITNESS)
198    }
199
200    pub fn verify_discourage_upgradable_witness_program(&self) -> bool {
201        self.contains(Self::DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM)
202    }
203}
204
205/// Represents different signature verification schemes used in Bitcoin
206///
207/// https://github.com/bitcoin/bitcoin/blob/6f9db1ebcab4064065ccd787161bf2b87e03cc1f/src/script/interpreter.h#L190
208#[derive(Debug, Clone, Copy, PartialEq, Eq)]
209pub enum SigVersion {
210    /// Bare scripts and BIP16 P2SH-wrapped redeemscripts
211    Base,
212    /// Witness v0 (P2WPKH and P2WSH); see BIP 141
213    WitnessV0,
214    /// Witness v1 with 32-byte program, not BIP16 P2SH-wrapped, key path spending; see BIP 341
215    Taproot,
216    /// Witness v1 with 32-byte program, not BIP16 P2SH-wrapped, script path spending,
217    /// leaf version 0xc0; see BIP 342
218    Tapscript,
219}
220
221// https://github.com/bitcoin/bitcoin/blob/6f9db1ebcab4064065ccd787161bf2b87e03cc1f/src/script/interpreter.h#L198
222#[derive(Debug)]
223pub struct ScriptExecutionData {
224    /// Whether m_tapleaf_hash is initialized
225    pub tapleaf_hash_init: bool,
226    /// The tapleaf hash
227    pub tapleaf_hash: TapLeafHash,
228
229    /// Whether m_codeseparator_pos is initialized
230    pub codeseparator_pos_init: bool,
231    /// Opcode position of the last executed OP_CODESEPARATOR (or 0xFFFFFFFF if none executed)
232    pub codeseparator_pos: u32,
233
234    /// Whether m_annex_present and m_annex_hash are initialized
235    pub annex_init: bool,
236    /// Whether an annex is present
237    pub annex_present: bool,
238    /// Hash of the annex data
239    pub annex_hash: H256,
240    /// Annex data.
241    ///
242    /// We store the annex data for signature_checker.
243    pub annex: Option<Vec<u8>>,
244
245    /// Whether m_validation_weight_left is initialized
246    pub validation_weight_left_init: bool,
247    /// How much validation weight is left (decremented for every successful non-empty signature check)
248    pub validation_weight_left: i64,
249
250    /// The hash of the corresponding output
251    pub output_hash: Option<H256>,
252}
253
254impl Default for ScriptExecutionData {
255    fn default() -> Self {
256        Self {
257            tapleaf_hash_init: false,
258            tapleaf_hash: TapLeafHash::from_slice(H256::all_zeros().as_byte_array())
259                .expect("Static value must be correct; qed"),
260            codeseparator_pos_init: false,
261            codeseparator_pos: 0,
262            annex_init: false,
263            annex_present: false,
264            annex_hash: H256::all_zeros(),
265            annex: None,
266            validation_weight_left_init: false,
267            validation_weight_left: 0,
268            output_hash: None,
269        }
270    }
271}