zebra-script 16.0.0

Zebra transparent script verification with the Rust zcash_script interpreter
Documentation
//! Tests for the results and counts that Zebra takes from the Rust `zcash_script` interpreter.

use std::sync::Arc;

use zebra_chain::{
    block,
    parameters::NetworkUpgrade,
    transaction::{self, HashType, LockTime, SigHasher, Transaction},
    transparent::{self, Output},
};

use crate::{legacy_sigop_count, CachedFfiTransaction, Error};

/// Returns a v5 transaction with one input for each of `unlock_scripts`, and one output.
fn spend(unlock_scripts: &[&[u8]]) -> Transaction {
    let inputs = unlock_scripts
        .iter()
        .zip(0..)
        .map(|(unlock_script, index)| transparent::Input::PrevOut {
            outpoint: transparent::OutPoint {
                hash: transaction::Hash([0u8; 32]),
                index,
            },
            unlock_script: transparent::Script::new(unlock_script),
            sequence: u32::MAX,
        })
        .collect();

    Transaction::test_v5(
        NetworkUpgrade::Nu5,
        inputs,
        vec![Output {
            value: 1u64.try_into().expect("1 zatoshi is a valid amount"),
            lock_script: transparent::Script::new(&[0x00]),
        }],
        LockTime::unlocked(),
        block::Height(0),
    )
}

/// Returns the outputs that the inputs of a [`spend`] spend: `inputs` outputs locked by
/// `lock_script`.
fn previous_outputs(lock_script: &[u8], inputs: usize) -> Arc<Vec<Output>> {
    Arc::new(vec![
        Output {
            value: 1u64.try_into().expect("1 zatoshi is a valid amount"),
            lock_script: transparent::Script::new(lock_script),
        };
        inputs
    ])
}

/// Verifies input `input_index` of a [`spend`] with `unlock_scripts`, when each of its inputs
/// spends an output locked by `lock_script`.
fn is_valid(unlock_scripts: &[&[u8]], lock_script: &[u8], input_index: usize) -> Result<(), Error> {
    CachedFfiTransaction::new(
        Arc::new(spend(unlock_scripts)),
        previous_outputs(lock_script, unlock_scripts.len()),
        NetworkUpgrade::Nu5,
    )
    .expect("NU5 has a consensus branch ID, and each input has a spent output")
    .is_valid(input_index)
}

/// Returns the P2SH lock script for `redeem_script`: `OP_HASH160 <script hash> OP_EQUAL`.
fn p2sh_lock_script(redeem_script: &[u8]) -> Vec<u8> {
    use ripemd::{Digest as _, Ripemd160};
    use sha2::Sha256;

    let script_hash: [u8; 20] = Ripemd160::digest(Sha256::digest(redeem_script)).into();
    [&[0xa9, 0x14][..], &script_hash, &[0x87]].concat()
}

/// Checks that a signature whose sighash can't be computed fails only its own `OP_CHECKSIG`.
///
/// The lock script is `<pubkey> OP_CHECKSIG OP_NOT`, so the spend is valid exactly when the
/// signature check fails and the script keeps running. zcashd's `CheckSig` returns false when
/// `SignatureHash` throws, so it accepts a v5 spend whose signature has an undefined hash type, or
/// `SIGHASH_SINGLE` without an output at the input's index. An interpreter that aborted on those
/// signatures would reject both spends.
///
/// The same signature with `SIGHASH_ALL` passes its check, so `OP_NOT` leaves a false value. This
/// shows that the first two spends are accepted because of their hash types.
#[test]
fn unavailable_sighash_fails_only_its_signature_check() {
    use secp256k1::{Message, SecretKey};

    let _init_guard = zebra_test::init();

    let secret_key = SecretKey::from_secret_bytes([0xcd; 32]).expect("valid secret key");
    let pubkey_bytes = secp256k1::PublicKey::from_secret_key(&secret_key).serialize();

    // <0x21> <pubkey 33 bytes> OP_CHECKSIG (0xac) OP_NOT (0x91)
    let lock_script = [&[0x21][..], &pubkey_bytes, &[0xac, 0x91]].concat();

    // Two inputs and one output, so the second input has no output at its index. The v5 sighash
    // doesn't depend on the unlock scripts, so the signed transaction can be rebuilt with them.
    let sighasher = SigHasher::new(
        &spend(&[&[], &[]]),
        NetworkUpgrade::Nu5,
        previous_outputs(&lock_script, 2),
    )
    .expect("NU5 has a consensus branch ID, and each input has a spent output");

    // Signs `input_index` with `SIGHASH_ALL`, then replaces the hash type byte.
    let is_valid_with_hash_type = |input_index: usize, hash_type: u8| {
        let sighash = sighasher.sighash(HashType::ALL, Some((input_index, lock_script.clone())));
        let signature =
            secp256k1::ecdsa::sign(Message::from_digest(*sighash.as_ref()), &secret_key);
        let der_signature = signature.serialize_der();

        let mut unlock_script = vec![u8::try_from(der_signature.len() + 1)
            .expect("a DER signature and its hash type fit in a direct push")];
        unlock_script.extend_from_slice(&der_signature);
        unlock_script.push(hash_type);

        let mut unlock_scripts: [&[u8]; 2] = [&[], &[]];
        unlock_scripts[input_index] = &unlock_script;

        is_valid(&unlock_scripts, &lock_script, input_index)
    };

    assert_eq!(
        is_valid_with_hash_type(0, 0x50),
        Ok(()),
        "an undefined v5 hash type fails only its signature check, matching zcashd"
    );
    assert_eq!(
        is_valid_with_hash_type(1, 0x03),
        Ok(()),
        "SIGHASH_SINGLE without a corresponding output fails only its signature check, \
         matching zcashd"
    );

    for input_index in [0, 1] {
        assert_eq!(
            is_valid_with_hash_type(input_index, 0x01),
            Err(Error::ScriptInvalid),
            "the SIGHASH_ALL signature passes its check, so OP_NOT leaves a false value"
        );
    }
}

/// Checks each `GetOp` rule that zcashd's `CScript::GetSigOpCount(false)` depends on.
#[test]
fn legacy_sigop_count_follows_zcashd_get_op() {
    let push = |prefix: &[u8], len: usize| [prefix, &vec![0xac; len], &[0xac]].concat();
    let cases: Vec<(&str, Vec<u8>, u32)> = vec![
        ("empty", vec![], 0),
        ("CHECKSIG", vec![0xac], 1),
        ("CHECKSIGVERIFY", vec![0xad], 1),
        ("CHECKMULTISIG", vec![0xae], 20),
        ("CHECKMULTISIGVERIFY", vec![0xaf], 20),
        ("legacy mode ignores OP_N", vec![0x52, 0xae], 20),
        ("direct push payload", push(&[0x4b], 75), 1),
        ("PUSHDATA1 payload", push(&[0x4c, 0xff], 255), 1),
        (
            "PUSHDATA2 520-byte payload",
            push(&[0x4d, 0x08, 0x02], 520),
            1,
        ),
        (
            "PUSHDATA2 521-byte payload",
            push(&[0x4d, 0x09, 0x02], 521),
            1,
        ),
        (
            "PUSHDATA4 payload",
            push(&[0x4e, 0x00, 0x01, 0x00, 0x00], 256),
            1,
        ),
        ("truncated direct push", vec![0xac, 0x02, 0xac], 1),
        ("truncated PUSHDATA1 length", vec![0xac, 0x4c], 1),
        ("truncated PUSHDATA2 length", vec![0xac, 0x4d, 0x01], 1),
        (
            "truncated PUSHDATA4 length",
            vec![0xac, 0x4e, 0x00, 0x00, 0x00],
            1,
        ),
        (
            "PUSHDATA4 maximum length",
            vec![0xac, 0x4e, 0xff, 0xff, 0xff, 0xff, 0xac],
            1,
        ),
        ("disabled OP_CAT", vec![0x7e, 0xac], 1),
        ("OP_CODESEPARATOR", vec![0xab, 0xac], 1),
        (
            "reserved and invalid opcodes",
            vec![0x50, 0xba, 0xff, 0xac],
            1,
        ),
    ];
    for (name, script, expected) in cases {
        assert_eq!(legacy_sigop_count(&script), expected, "{name}");
    }
}

/// Checks how `is_valid` reports a script that passes, one that runs to completion and leaves a
/// false value, and one that the interpreter aborts in each script component.
#[test]
fn is_valid_reports_the_failed_script_component() {
    use std::error::Error as _;

    use zcash_script::script::ComponentType;

    let _init_guard = zebra_test::init();

    let verify =
        |unlock_script: &[u8], lock_script: &[u8]| is_valid(&[unlock_script], lock_script, 0);

    const OP_0: u8 = 0x00;
    const OP_1: u8 = 0x51;
    const OP_RETURN: u8 = 0x6a;

    assert_eq!(verify(&[], &[OP_1]), Ok(()));
    assert_eq!(verify(&[], &[OP_0]), Err(Error::ScriptInvalid));
    assert!(matches!(
        verify(&[], &[OP_RETURN]),
        Err(Error::Interpreter {
            component: ComponentType::PubKey,
            ..
        })
    ));
    assert!(matches!(
        verify(&[OP_RETURN], &[OP_1]),
        Err(Error::Interpreter {
            component: ComponentType::Sig,
            ..
        })
    ));

    // A P2SH spend of a one-byte redeem script, which the unlock script pushes.
    let verify_p2sh =
        |redeem_script: u8| verify(&[0x01, redeem_script], &p2sh_lock_script(&[redeem_script]));

    assert_eq!(verify_p2sh(OP_1), Ok(()));
    assert_eq!(verify_p2sh(OP_0), Err(Error::ScriptInvalid));
    let redeem_error = verify_p2sh(OP_RETURN).expect_err("OP_RETURN aborts the redeem script");
    assert!(matches!(
        redeem_error,
        Error::Interpreter {
            component: ComponentType::Redeem,
            ..
        }
    ));

    // The interpreter error is both part of the message and the source of the error.
    let Error::Interpreter { error, .. } = &redeem_error else {
        unreachable!("checked above");
    };
    assert!(redeem_error.to_string().contains(&error.to_string()));
    assert_eq!(
        redeem_error.source().map(ToString::to_string),
        Some(error.to_string())
    );
}