Skip to content

Commit 5ba9fe5

Browse files
committed
Provide a Rustier wrapper for zcash_script
This adds a `Script` trait that exposes slightly Rustier types in order to have a common interface for the existing C++ implementation as well as the upcoming Rust implementation (and a third instance that runs both and checks that the Rust result matches the C++ one).
1 parent 59642ca commit 5ba9fe5

File tree

4 files changed

+330
-6
lines changed

4 files changed

+330
-6
lines changed

Cargo.lock

Lines changed: 6 additions & 5 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "zcash_script"
3-
version = "0.2.0"
3+
version = "0.3.0"
44
authors = ["Tamas Blummer <[email protected]>", "Zcash Foundation <[email protected]>"]
55
license = "Apache-2.0"
66
readme = "README.md"
@@ -60,6 +60,7 @@ path = "src/lib.rs"
6060
external-secp = []
6161

6262
[dependencies]
63+
bitflags = "2.5.0"
6364

6465
[build-dependencies]
6566
# The `bindgen` dependency should automatically upgrade to match the version used by zebra-state's `rocksdb` dependency in:

src/interpreter.rs

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
bitflags::bitflags! {
2+
/// The different SigHash types, as defined in <https://zips.z.cash/zip-0143>
3+
///
4+
/// TODO: There are three implementations of this (with three distinct primitive types):
5+
/// - u8 constants in librustzcash,
6+
/// - i32 (well, c_int) bitflags from the C++ constants here, and
7+
/// - u32 bitflags in zebra-chain.
8+
///
9+
/// Ideally we could unify on bitflags in librustzcash.
10+
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
11+
pub struct HashType: i32 {
12+
/// Sign all the outputs
13+
const All = 1;
14+
/// Sign none of the outputs - anyone can spend
15+
const None = 2;
16+
/// Sign one of the outputs - anyone can spend the rest
17+
const Single = 3;
18+
/// Anyone can add inputs to this transaction
19+
const AnyoneCanPay = 0x80;
20+
}
21+
}
22+
23+
bitflags::bitflags! {
24+
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
25+
pub struct VerificationFlags: u32 {
26+
const None = 0;
27+
28+
/// Evaluate P2SH subscripts (softfork safe, BIP16).
29+
const P2SH = 1 << 0;
30+
31+
/// Passing a non-strict-DER signature or one with undefined hashtype to a checksig operation causes script failure.
32+
/// Evaluating a pubkey that is not (0x04 + 64 bytes) or (0x02 or 0x03 + 32 bytes) by checksig causes script failure.
33+
/// (softfork safe, but not used or intended as a consensus rule).
34+
const StrictEnc = 1 << 1;
35+
36+
/// Passing a non-strict-DER signature or one with S > order/2 to a checksig operation causes script failure
37+
/// (softfork safe, BIP62 rule 5).
38+
const LowS = 1 << 3;
39+
40+
/// verify dummy stack item consumed by CHECKMULTISIG is of zero-length (softfork safe, BIP62 rule 7).
41+
const NullDummy = 1 << 4;
42+
43+
/// Using a non-push operator in the scriptSig causes script failure (softfork safe, BIP62 rule 2).
44+
const SigPushOnly = 1 << 5;
45+
46+
/// Require minimal encodings for all push operations (OP_0... OP_16, OP_1NEGATE where possible, direct
47+
/// pushes up to 75 bytes, OP_PUSHDATA up to 255 bytes, OP_PUSHDATA2 for anything larger). Evaluating
48+
/// any other push causes the script to fail (BIP62 rule 3).
49+
/// In addition, whenever a stack element is interpreted as a number, it must be of minimal length (BIP62 rule 4).
50+
/// (softfork safe)
51+
const MinimalData = 1 << 6;
52+
53+
/// Discourage use of NOPs reserved for upgrades (NOP1-10)
54+
///
55+
/// Provided so that nodes can avoid accepting or mining transactions
56+
/// containing executed NOP's whose meaning may change after a soft-fork,
57+
/// thus rendering the script invalid; with this flag set executing
58+
/// discouraged NOPs fails the script. This verification flag will never be
59+
/// a mandatory flag applied to scripts in a block. NOPs that are not
60+
/// executed, e.g. within an unexecuted IF ENDIF block, are *not* rejected.
61+
const DiscourageUpgradableNOPs = 1 << 7;
62+
63+
/// Require that only a single stack element remains after evaluation. This changes the success criterion from
64+
/// "At least one stack element must remain, and when interpreted as a boolean, it must be true" to
65+
/// "Exactly one stack element must remain, and when interpreted as a boolean, it must be true".
66+
/// (softfork safe, BIP62 rule 6)
67+
/// Note: CLEANSTACK should never be used without P2SH.
68+
const CleanStack = 1 << 8;
69+
70+
/// Verify CHECKLOCKTIMEVERIFY
71+
///
72+
/// See BIP65 for details.
73+
const CHECKLOCKTIMEVERIFY = 1 << 9;
74+
}
75+
}

src/lib.rs

Lines changed: 247 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,250 @@
33

44
mod cxx;
55
pub use cxx::*;
6+
7+
mod interpreter;
8+
use interpreter::*;
9+
10+
use std::os::raw::{c_int, c_uint, c_void};
11+
12+
/// This maps to `zcash_script_error_t`, but most of those cases aren’t used any more. This only
13+
/// replicates the still-used cases, and then an `Unknown` bucket for anything else that might
14+
/// happen.
15+
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
16+
#[repr(u32)]
17+
pub enum Error {
18+
Ok = 0,
19+
VerifyScript = 7,
20+
Unknown(u32),
21+
}
22+
23+
/// A function which is called to obtain the sighash.
24+
/// - script_code: the scriptCode being validated. Note that this not always
25+
/// matches script_sig, i.e. for P2SH.
26+
/// - hash_type: the hash type being used.
27+
///
28+
/// The underlying C++ callback doesn’t give much opportunity for rich failure reporting, but
29+
/// returning `None` indicates _some_ failure to produce the desired hash.
30+
///
31+
/// TODO: Can we get the “32” from somewhere rather than hardcoding it?
32+
pub type SighashCallback = dyn Fn(&[u8], HashType) -> Option<[u8; 32]>;
33+
34+
/// The external API of zcash_script. This is defined to make it possible to compare the C++ and
35+
/// Rust implementations.
36+
pub trait ZcashScript {
37+
/// Returns `Ok(())` if the a transparent input correctly spends the matching output
38+
/// under the additional constraints specified by `flags`. This function
39+
/// receives only the required information to validate the spend and not
40+
/// the transaction itself. In particular, the sighash for the spend
41+
/// is obtained using a callback function.
42+
///
43+
/// - sighash_callback: a callback function which is called to obtain the sighash.
44+
/// - n_lock_time: the lock time of the transaction being validated.
45+
/// - is_final: a boolean indicating whether the input being validated is final
46+
/// (i.e. its sequence number is 0xFFFFFFFF).
47+
/// - script_pub_key: the scriptPubKey of the output being spent.
48+
/// - script_sig: the scriptSig of the input being validated.
49+
/// - flags: the script verification flags to use.
50+
/// - err: if not NULL, err will contain an error/success code for the operation.
51+
///
52+
/// Note that script verification failure is indicated by `Err(Error::Ok)`.
53+
fn verify_callback(
54+
sighash_callback: &SighashCallback,
55+
n_lock_time: i64,
56+
is_final: bool,
57+
script_pub_key: &[u8],
58+
script_sig: &[u8],
59+
flags: VerificationFlags,
60+
) -> Result<(), Error>;
61+
62+
/// Returns the number of transparent signature operations in the input or
63+
/// output script pointed to by script.
64+
fn legacy_sigop_count_script(script: &[u8]) -> u32;
65+
}
66+
67+
pub enum Cxx {}
68+
69+
impl From<zcash_script_error_t> for Error {
70+
#[allow(non_upper_case_globals)]
71+
fn from(err_code: zcash_script_error_t) -> Error {
72+
match err_code {
73+
zcash_script_error_t_zcash_script_ERR_OK => Error::Ok,
74+
zcash_script_error_t_zcash_script_ERR_VERIFY_SCRIPT => Error::VerifyScript,
75+
unknown => Error::Unknown(unknown),
76+
}
77+
}
78+
}
79+
80+
/// The sighash callback to use with zcash_script.
81+
extern "C" fn sighash(
82+
sighash_out: *mut u8,
83+
sighash_out_len: c_uint,
84+
ctx: *const c_void,
85+
script_code: *const u8,
86+
script_code_len: c_uint,
87+
hash_type: c_int,
88+
) {
89+
// SAFETY: `ctx` is a valid SighashCallbackt because it is always passed to
90+
// `verify_callback` which simply forwards it to the callback.
91+
// `script_code` and `sighash_out` are valid buffers since they are always
92+
// specified when the callback is called.
93+
unsafe {
94+
let ctx = ctx as *const &SighashCallback;
95+
let script_code_vec =
96+
std::slice::from_raw_parts(script_code, script_code_len as usize);
97+
let sighash = (*ctx)(
98+
&script_code_vec,
99+
HashType::from_bits(hash_type).expect("was built from HashType")
100+
);
101+
sighash.map(|sighash| {
102+
// Sanity check; must always be true.
103+
assert_eq!(sighash_out_len, sighash.len() as c_uint);
104+
std::ptr::copy_nonoverlapping(sighash.as_ptr(), sighash_out, sighash.len());
105+
});
106+
}
107+
}
108+
109+
/// This steals a bit of the wrapper code from zebra_script, to provide the API that they want.
110+
impl ZcashScript for Cxx {
111+
fn verify_callback(
112+
sighash_callback: &SighashCallback,
113+
lock_time: i64,
114+
is_final: bool,
115+
script_pub_key: &[u8],
116+
signature_script: &[u8],
117+
flags: VerificationFlags,
118+
) -> Result<(), Error> {
119+
let mut err = 0;
120+
121+
let flags = flags.bits();
122+
123+
let is_final = if is_final {
124+
1
125+
} else {
126+
0
127+
};
128+
129+
let ctx = Box::new(sighash_callback);
130+
// SAFETY: The `script_*` fields are created from a valid Rust `slice`.
131+
let ret = unsafe {
132+
zcash_script_verify_callback(
133+
(&*ctx as *const &SighashCallback) as *const c_void,
134+
Some(sighash),
135+
lock_time,
136+
is_final,
137+
script_pub_key.as_ptr(),
138+
script_pub_key.len() as u32,
139+
signature_script.as_ptr(),
140+
signature_script.len() as u32,
141+
flags,
142+
&mut err,
143+
)
144+
};
145+
146+
if ret == 1 {
147+
Ok(())
148+
} else {
149+
Err(Error::from(err))
150+
}
151+
}
152+
153+
/// Returns the number of transparent signature operations in the
154+
/// transparent inputs and outputs of this transaction.
155+
fn legacy_sigop_count_script(script: &[u8]) -> u32 {
156+
unsafe {
157+
zcash_script_legacy_sigop_count_script(
158+
script.as_ptr(),
159+
script.len() as u32,
160+
)
161+
}
162+
}
163+
}
164+
165+
#[cfg(test)]
166+
mod tests {
167+
pub use super::*;
168+
use hex::FromHex;
169+
170+
lazy_static::lazy_static! {
171+
pub static ref SCRIPT_PUBKEY: Vec<u8> = <Vec<u8>>::from_hex("a914c117756dcbe144a12a7c33a77cfa81aa5aeeb38187").unwrap();
172+
pub static ref SCRIPT_SIG: Vec<u8> = <Vec<u8>>::from_hex("00483045022100d2ab3e6258fe244fa442cfb38f6cef9ac9a18c54e70b2f508e83fa87e20d040502200eead947521de943831d07a350e45af8e36c2166984a8636f0a8811ff03ed09401473044022013e15d865010c257eef133064ef69a780b4bc7ebe6eda367504e806614f940c3022062fdbc8c2d049f91db2042d6c9771de6f1ef0b3b1fea76c1ab5542e44ed29ed8014c69522103b2cc71d23eb30020a4893982a1e2d352da0d20ee657fa02901c432758909ed8f21029d1e9a9354c0d2aee9ffd0f0cea6c39bbf98c4066cf143115ba2279d0ba7dabe2103e32096b63fd57f3308149d238dcbb24d8d28aad95c0e4e74e3e5e6a11b61bcc453ae").expect("Block bytes are in valid hex representation");
173+
}
174+
175+
fn sighash(_script_code: &[u8], _hash_type: HashType) -> Option<[u8; 32]> {
176+
hex::decode("e8c7bdac77f6bb1f3aba2eaa1fada551a9c8b3b5ecd1ef86e6e58a5f1aab952c")
177+
.unwrap()
178+
.as_slice()
179+
.first_chunk::<32>()
180+
.map(|hash| *hash)
181+
}
182+
183+
fn invalid_sighash(_script_code: &[u8], _hash_type: HashType) -> Option<[u8; 32]> {
184+
hex::decode("08c7bdac77f6bb1f3aba2eaa1fada551a9c8b3b5ecd1ef86e6e58a5f1aab952c")
185+
.unwrap()
186+
.as_slice()
187+
.first_chunk::<32>()
188+
.map(|hash| *hash)
189+
}
190+
191+
fn missing_sighash(_script_code: &[u8], _hash_type: HashType) -> Option<[u8; 32]> { None }
192+
193+
#[test]
194+
fn it_works() {
195+
let n_lock_time: i64 = 2410374;
196+
let is_final: bool = true;
197+
let script_pub_key = &SCRIPT_PUBKEY;
198+
let script_sig = &SCRIPT_SIG;
199+
let flags = VerificationFlags::P2SH | VerificationFlags::CHECKLOCKTIMEVERIFY;
200+
201+
let ret = Cxx::verify_callback(
202+
&sighash,
203+
n_lock_time,
204+
is_final,
205+
script_pub_key,
206+
script_sig,
207+
flags,
208+
);
209+
210+
assert!(ret.is_ok());
211+
}
212+
213+
#[test]
214+
fn it_fails_on_invalid_sighash() {
215+
let n_lock_time: i64 = 2410374;
216+
let is_final: bool = true;
217+
let script_pub_key = &SCRIPT_PUBKEY;
218+
let script_sig = &SCRIPT_SIG;
219+
let flags = VerificationFlags::P2SH | VerificationFlags::CHECKLOCKTIMEVERIFY;
220+
221+
let ret = Cxx::verify_callback(
222+
&invalid_sighash,
223+
n_lock_time,
224+
is_final,
225+
script_pub_key,
226+
script_sig,
227+
flags,
228+
);
229+
230+
assert_eq!(ret, Err(Error::Ok));
231+
}
232+
233+
#[test]
234+
fn it_fails_on_missing_sighash() {
235+
let n_lock_time: i64 = 2410374;
236+
let is_final: bool = true;
237+
let script_pub_key = &SCRIPT_PUBKEY;
238+
let script_sig = &SCRIPT_SIG;
239+
let flags = VerificationFlags::P2SH | VerificationFlags::CHECKLOCKTIMEVERIFY;
240+
241+
let ret = Cxx::verify_callback(
242+
&missing_sighash,
243+
n_lock_time,
244+
is_final,
245+
script_pub_key,
246+
script_sig,
247+
flags,
248+
);
249+
250+
assert_eq!(ret, Err(Error::Ok));
251+
}
252+
}

0 commit comments

Comments
 (0)