Skip to content

Commit b9e0ea0

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 b9e0ea0

File tree

5 files changed

+333
-6
lines changed

5 files changed

+333
-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: 194 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,197 @@
33

44
mod cxx;
55
pub use cxx::*;
6+
7+
mod interpreter;
8+
pub use interpreter::{HashType, VerificationFlags};
9+
mod zcash_script;
10+
pub use zcash_script::*;
11+
12+
use std::os::raw::{c_int, c_uint, c_void};
13+
14+
pub enum Cxx {}
15+
16+
impl From<zcash_script_error_t> for Error {
17+
#[allow(non_upper_case_globals)]
18+
fn from(err_code: zcash_script_error_t) -> Error {
19+
match err_code {
20+
zcash_script_error_t_zcash_script_ERR_OK => Error::Ok,
21+
zcash_script_error_t_zcash_script_ERR_VERIFY_SCRIPT => Error::VerifyScript,
22+
unknown => Error::Unknown(unknown),
23+
}
24+
}
25+
}
26+
27+
/// The sighash callback to use with zcash_script.
28+
extern "C" fn sighash(
29+
sighash_out: *mut u8,
30+
sighash_out_len: c_uint,
31+
ctx: *const c_void,
32+
script_code: *const u8,
33+
script_code_len: c_uint,
34+
hash_type: c_int,
35+
) {
36+
// SAFETY: `ctx` is a valid SighashCallbackt because it is always passed to
37+
// `verify_callback` which simply forwards it to the callback.
38+
// `script_code` and `sighash_out` are valid buffers since they are always
39+
// specified when the callback is called.
40+
unsafe {
41+
let ctx = ctx as *const &SighashCallback;
42+
let script_code_vec =
43+
std::slice::from_raw_parts(script_code, script_code_len as usize);
44+
let sighash = (*ctx)(
45+
&script_code_vec,
46+
HashType::from_bits(hash_type).expect("was built from HashType")
47+
);
48+
sighash.map(|sighash| {
49+
// Sanity check; must always be true.
50+
assert_eq!(sighash_out_len, sighash.len() as c_uint);
51+
std::ptr::copy_nonoverlapping(sighash.as_ptr(), sighash_out, sighash.len());
52+
});
53+
}
54+
}
55+
56+
/// This steals a bit of the wrapper code from zebra_script, to provide the API that they want.
57+
impl ZcashScript for Cxx {
58+
fn verify_callback(
59+
sighash_callback: &SighashCallback,
60+
lock_time: i64,
61+
is_final: bool,
62+
script_pub_key: &[u8],
63+
signature_script: &[u8],
64+
flags: VerificationFlags,
65+
) -> Result<(), Error> {
66+
let mut err = 0;
67+
68+
let flags = flags.bits();
69+
70+
let is_final = if is_final {
71+
1
72+
} else {
73+
0
74+
};
75+
76+
let ctx = Box::new(sighash_callback);
77+
// SAFETY: The `script_*` fields are created from a valid Rust `slice`.
78+
let ret = unsafe {
79+
zcash_script_verify_callback(
80+
(&*ctx as *const &SighashCallback) as *const c_void,
81+
Some(sighash),
82+
lock_time,
83+
is_final,
84+
script_pub_key.as_ptr(),
85+
script_pub_key.len() as u32,
86+
signature_script.as_ptr(),
87+
signature_script.len() as u32,
88+
flags,
89+
&mut err,
90+
)
91+
};
92+
93+
if ret == 1 {
94+
Ok(())
95+
} else {
96+
Err(Error::from(err))
97+
}
98+
}
99+
100+
/// Returns the number of transparent signature operations in the
101+
/// transparent inputs and outputs of this transaction.
102+
fn legacy_sigop_count_script(script: &[u8]) -> u32 {
103+
unsafe {
104+
zcash_script_legacy_sigop_count_script(
105+
script.as_ptr(),
106+
script.len() as u32,
107+
)
108+
}
109+
}
110+
}
111+
112+
#[cfg(test)]
113+
mod tests {
114+
pub use super::*;
115+
use hex::FromHex;
116+
117+
lazy_static::lazy_static! {
118+
pub static ref SCRIPT_PUBKEY: Vec<u8> = <Vec<u8>>::from_hex("a914c117756dcbe144a12a7c33a77cfa81aa5aeeb38187").unwrap();
119+
pub static ref SCRIPT_SIG: Vec<u8> = <Vec<u8>>::from_hex("00483045022100d2ab3e6258fe244fa442cfb38f6cef9ac9a18c54e70b2f508e83fa87e20d040502200eead947521de943831d07a350e45af8e36c2166984a8636f0a8811ff03ed09401473044022013e15d865010c257eef133064ef69a780b4bc7ebe6eda367504e806614f940c3022062fdbc8c2d049f91db2042d6c9771de6f1ef0b3b1fea76c1ab5542e44ed29ed8014c69522103b2cc71d23eb30020a4893982a1e2d352da0d20ee657fa02901c432758909ed8f21029d1e9a9354c0d2aee9ffd0f0cea6c39bbf98c4066cf143115ba2279d0ba7dabe2103e32096b63fd57f3308149d238dcbb24d8d28aad95c0e4e74e3e5e6a11b61bcc453ae").expect("Block bytes are in valid hex representation");
120+
}
121+
122+
fn sighash(_script_code: &[u8], _hash_type: HashType) -> Option<[u8; 32]> {
123+
hex::decode("e8c7bdac77f6bb1f3aba2eaa1fada551a9c8b3b5ecd1ef86e6e58a5f1aab952c")
124+
.unwrap()
125+
.as_slice()
126+
.first_chunk::<32>()
127+
.map(|hash| *hash)
128+
}
129+
130+
fn invalid_sighash(_script_code: &[u8], _hash_type: HashType) -> Option<[u8; 32]> {
131+
hex::decode("08c7bdac77f6bb1f3aba2eaa1fada551a9c8b3b5ecd1ef86e6e58a5f1aab952c")
132+
.unwrap()
133+
.as_slice()
134+
.first_chunk::<32>()
135+
.map(|hash| *hash)
136+
}
137+
138+
fn missing_sighash(_script_code: &[u8], _hash_type: HashType) -> Option<[u8; 32]> { None }
139+
140+
#[test]
141+
fn it_works() {
142+
let n_lock_time: i64 = 2410374;
143+
let is_final: bool = true;
144+
let script_pub_key = &SCRIPT_PUBKEY;
145+
let script_sig = &SCRIPT_SIG;
146+
let flags = VerificationFlags::P2SH | VerificationFlags::CHECKLOCKTIMEVERIFY;
147+
148+
let ret = Cxx::verify_callback(
149+
&sighash,
150+
n_lock_time,
151+
is_final,
152+
script_pub_key,
153+
script_sig,
154+
flags,
155+
);
156+
157+
assert!(ret.is_ok());
158+
}
159+
160+
#[test]
161+
fn it_fails_on_invalid_sighash() {
162+
let n_lock_time: i64 = 2410374;
163+
let is_final: bool = true;
164+
let script_pub_key = &SCRIPT_PUBKEY;
165+
let script_sig = &SCRIPT_SIG;
166+
let flags = VerificationFlags::P2SH | VerificationFlags::CHECKLOCKTIMEVERIFY;
167+
168+
let ret = Cxx::verify_callback(
169+
&invalid_sighash,
170+
n_lock_time,
171+
is_final,
172+
script_pub_key,
173+
script_sig,
174+
flags,
175+
);
176+
177+
assert_eq!(ret, Err(Error::Ok));
178+
}
179+
180+
#[test]
181+
fn it_fails_on_missing_sighash() {
182+
let n_lock_time: i64 = 2410374;
183+
let is_final: bool = true;
184+
let script_pub_key = &SCRIPT_PUBKEY;
185+
let script_sig = &SCRIPT_SIG;
186+
let flags = VerificationFlags::P2SH | VerificationFlags::CHECKLOCKTIMEVERIFY;
187+
188+
let ret = Cxx::verify_callback(
189+
&missing_sighash,
190+
n_lock_time,
191+
is_final,
192+
script_pub_key,
193+
script_sig,
194+
flags,
195+
);
196+
197+
assert_eq!(ret, Err(Error::Ok));
198+
}
199+
}

src/zcash_script.rs

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
use super::interpreter::*;
2+
3+
/// This maps to `zcash_script_error_t`, but most of those cases aren’t used any more. This only
4+
/// replicates the still-used cases, and then an `Unknown` bucket for anything else that might
5+
/// happen.
6+
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
7+
#[repr(u32)]
8+
pub enum Error {
9+
Ok = 0,
10+
VerifyScript = 7,
11+
Unknown(u32),
12+
}
13+
14+
/// A function which is called to obtain the sighash.
15+
/// - script_code: the scriptCode being validated. Note that this not always
16+
/// matches script_sig, i.e. for P2SH.
17+
/// - hash_type: the hash type being used.
18+
///
19+
/// The underlying C++ callback doesn’t give much opportunity for rich failure reporting, but
20+
/// returning `None` indicates _some_ failure to produce the desired hash.
21+
///
22+
/// TODO: Can we get the “32” from somewhere rather than hardcoding it?
23+
pub type SighashCallback = dyn Fn(&[u8], HashType) -> Option<[u8; 32]>;
24+
25+
/// The external API of zcash_script. This is defined to make it possible to compare the C++ and
26+
/// Rust implementations.
27+
pub trait ZcashScript {
28+
/// Returns `Ok(())` if the a transparent input correctly spends the matching output
29+
/// under the additional constraints specified by `flags`. This function
30+
/// receives only the required information to validate the spend and not
31+
/// the transaction itself. In particular, the sighash for the spend
32+
/// is obtained using a callback function.
33+
///
34+
/// - sighash_callback: a callback function which is called to obtain the sighash.
35+
/// - n_lock_time: the lock time of the transaction being validated.
36+
/// - is_final: a boolean indicating whether the input being validated is final
37+
/// (i.e. its sequence number is 0xFFFFFFFF).
38+
/// - script_pub_key: the scriptPubKey of the output being spent.
39+
/// - script_sig: the scriptSig of the input being validated.
40+
/// - flags: the script verification flags to use.
41+
/// - err: if not NULL, err will contain an error/success code for the operation.
42+
///
43+
/// Note that script verification failure is indicated by `Err(Error::Ok)`.
44+
fn verify_callback(
45+
sighash_callback: &SighashCallback,
46+
n_lock_time: i64,
47+
is_final: bool,
48+
script_pub_key: &[u8],
49+
script_sig: &[u8],
50+
flags: VerificationFlags,
51+
) -> Result<(), Error>;
52+
53+
/// Returns the number of transparent signature operations in the input or
54+
/// output script pointed to by script.
55+
fn legacy_sigop_count_script(script: &[u8]) -> u32;
56+
}

0 commit comments

Comments
 (0)