Skip to main content

zebrad/components/mempool/storage/
policy.rs

1//! Mempool transaction standardness policy constants and helpers.
2//!
3//! These mirror zcashd's mempool policy for rejecting non-standard transactions
4//! (`IsStandardTx()` and `AreInputsStandard()`). The transparent-input checks now live in
5//! `zebra-consensus`, where the transaction verifier applies them before script verification;
6//! they are re-exported here and used by the storage-time policy in the parent module.
7
8#[cfg(test)]
9use zebra_chain::transparent;
10
11// The transparent-input standardness checks (`AreInputsStandard()` and the spent-output
12// classifier) live in `zebra-consensus`, where the transaction verifier also applies them to
13// mempool transactions *before* script verification (`check::mempool_standard_input_scripts`).
14// They are re-exported here for the storage-time policy checks, so the two paths can't drift apart.
15pub(super) use zebra_consensus::transaction::check::{
16    are_inputs_standard, standard_script_kind, MAX_STANDARD_SCRIPTSIG_SIZE, MAX_STANDARD_TX_SIGOPS,
17};
18
19/// Maximum number of public keys allowed in a standard multisig script.
20/// <https://github.com/zcash/zcash/blob/v6.11.0/src/policy/policy.cpp#L46-L48>
21pub(super) const MAX_STANDARD_MULTISIG_PUBKEYS: usize = 3;
22
23#[cfg(test)]
24pub(super) use zebra_script::p2sh_sigop_count;
25
26// -- Test helper functions shared across test modules --
27
28/// Build a P2PKH lock script: OP_DUP OP_HASH160 <20-byte hash> OP_EQUALVERIFY OP_CHECKSIG
29#[cfg(test)]
30pub(super) fn p2pkh_lock_script(hash: &[u8; 20]) -> transparent::Script {
31    let mut s = vec![0x76, 0xa9, 0x14];
32    s.extend_from_slice(hash);
33    s.push(0x88);
34    s.push(0xac);
35    transparent::Script::new(&s)
36}
37
38/// Build a P2SH lock script: OP_HASH160 <20-byte hash> OP_EQUAL
39#[cfg(test)]
40pub(super) fn p2sh_lock_script(hash: &[u8; 20]) -> transparent::Script {
41    let mut s = vec![0xa9, 0x14];
42    s.extend_from_slice(hash);
43    s.push(0x87);
44    transparent::Script::new(&s)
45}
46
47/// Build a P2PK lock script: <compressed_pubkey> OP_CHECKSIG
48#[cfg(test)]
49pub(super) fn p2pk_lock_script(pubkey: &[u8; 33]) -> transparent::Script {
50    let mut s = Vec::with_capacity(1 + 33 + 1);
51    s.push(0x21); // OP_PUSHBYTES_33
52    s.extend_from_slice(pubkey);
53    s.push(0xac); // OP_CHECKSIG
54    transparent::Script::new(&s)
55}
56
57#[cfg(test)]
58mod tests {
59    use zebra_chain::{
60        block::Height,
61        transaction::{self, LockTime, Transaction},
62    };
63
64    use super::*;
65
66    // -- Helper functions --
67
68    /// Build a scriptSig with the specified number of push operations.
69    /// Each push is a 1-byte constant value.
70    fn push_only_script_sig(n_pushes: usize) -> transparent::Script {
71        let mut bytes = Vec::with_capacity(n_pushes * 2);
72        for _ in 0..n_pushes {
73            // OP_PUSHBYTES_1 <byte>
74            bytes.push(0x01);
75            bytes.push(0x42);
76        }
77        transparent::Script::new(&bytes)
78    }
79
80    /// Build a P2SH scriptSig from a list of push data items.
81    /// Each item is pushed as a single OP_PUSHBYTES data push (max 75 bytes).
82    /// The last item should be the redeemed script.
83    fn p2sh_script_sig(push_items: &[&[u8]]) -> transparent::Script {
84        let mut bytes = Vec::new();
85        for item in push_items {
86            assert!(
87                item.len() <= 75,
88                "p2sh_script_sig only supports OP_PUSHBYTES (max 75 bytes), got {}",
89                item.len()
90            );
91            // OP_PUSHBYTES_N where N = item.len(), safe because len <= 75 < 256
92            bytes.push(item.len() as u8);
93            bytes.extend_from_slice(item);
94        }
95        transparent::Script::new(&bytes)
96    }
97
98    /// Build a simple V4 transaction with the given transparent inputs and outputs.
99    fn make_v4_tx(
100        inputs: Vec<transparent::Input>,
101        outputs: Vec<transparent::Output>,
102    ) -> Transaction {
103        Transaction::test_v4(
104            inputs,
105            outputs,
106            LockTime::min_lock_time_timestamp(),
107            Height(0),
108        )
109    }
110
111    /// Build a PrevOut input with the given unlock script.
112    fn prevout_input(unlock_script: transparent::Script) -> transparent::Input {
113        transparent::Input::PrevOut {
114            outpoint: transparent::OutPoint {
115                hash: transaction::Hash([0xaa; 32]),
116                index: 0,
117            },
118            unlock_script,
119            sequence: 0xffffffff,
120        }
121    }
122
123    /// Build a transparent output with the given lock script.
124    /// Uses a non-dust value to avoid false positives in standardness checks.
125    fn output_with_script(lock_script: transparent::Script) -> transparent::Output {
126        transparent::Output {
127            value: 100_000u64.try_into().unwrap(),
128            lock_script,
129        }
130    }
131
132    // -- are_inputs_standard tests --
133
134    #[test]
135    fn are_inputs_standard_accepts_valid_p2pkh() {
136        let _init_guard = zebra_test::init();
137
138        // P2PKH expects 2 scriptSig pushes: <sig> <pubkey>
139        let script_sig = push_only_script_sig(2);
140        let tx = make_v4_tx(vec![prevout_input(script_sig)], vec![]);
141        let spent_outputs = vec![output_with_script(p2pkh_lock_script(&[0xaa; 20]))];
142
143        assert!(
144            are_inputs_standard(&tx, &spent_outputs),
145            "valid P2PKH input with correct stack depth should be standard"
146        );
147    }
148
149    #[test]
150    fn are_inputs_standard_rejects_wrong_stack_depth() {
151        let _init_guard = zebra_test::init();
152
153        // P2PKH expects 2 pushes, but we provide 3
154        let script_sig = push_only_script_sig(3);
155        let tx = make_v4_tx(vec![prevout_input(script_sig)], vec![]);
156        let spent_outputs = vec![output_with_script(p2pkh_lock_script(&[0xaa; 20]))];
157
158        assert!(
159            !are_inputs_standard(&tx, &spent_outputs),
160            "P2PKH input with 3 pushes instead of 2 should be non-standard"
161        );
162    }
163
164    #[test]
165    fn are_inputs_standard_rejects_too_few_pushes() {
166        let _init_guard = zebra_test::init();
167
168        // P2PKH expects 2 pushes, but we provide 1
169        let script_sig = push_only_script_sig(1);
170        let tx = make_v4_tx(vec![prevout_input(script_sig)], vec![]);
171        let spent_outputs = vec![output_with_script(p2pkh_lock_script(&[0xaa; 20]))];
172
173        assert!(
174            !are_inputs_standard(&tx, &spent_outputs),
175            "P2PKH input with 1 push instead of 2 should be non-standard"
176        );
177    }
178
179    #[test]
180    fn are_inputs_standard_rejects_non_standard_spent_output() {
181        let _init_guard = zebra_test::init();
182
183        // OP_1 OP_2 OP_ADD -- not a recognized standard script type
184        let non_standard_lock = transparent::Script::new(&[0x51, 0x52, 0x93]);
185        let script_sig = push_only_script_sig(1);
186        let tx = make_v4_tx(vec![prevout_input(script_sig)], vec![]);
187        let spent_outputs = vec![output_with_script(non_standard_lock)];
188
189        assert!(
190            !are_inputs_standard(&tx, &spent_outputs),
191            "input spending a non-standard script should be non-standard"
192        );
193    }
194
195    #[test]
196    fn are_inputs_standard_accepts_p2sh_with_standard_redeemed_script() {
197        let _init_guard = zebra_test::init();
198
199        // Build a P2SH input where the redeemed script is a P2PKH script.
200        // The redeemed script itself is the serialized P2PKH:
201        //   OP_DUP OP_HASH160 <20 bytes> OP_EQUALVERIFY OP_CHECKSIG
202        let redeemed_script_bytes = {
203            let mut s = vec![0x76, 0xa9, 0x14];
204            s.extend_from_slice(&[0xcc; 20]);
205            s.push(0x88);
206            s.push(0xac);
207            s
208        };
209
210        // For P2SH with a P2PKH redeemed script:
211        //   script_sig_args_expected(ScriptHash) = 1  (the redeemed script push)
212        //   script_sig_args_expected(PubKeyHash) = 2  (sig + pubkey inside redeemed)
213        //   total expected = 1 + 2 = 3
214        //
215        // scriptSig: <sig_placeholder> <pubkey_placeholder> <redeemed_script>
216        let script_sig = p2sh_script_sig(&[&[0xaa], &[0xbb], &redeemed_script_bytes]);
217
218        // The policy check uses is_pay_to_script_hash() which only checks the
219        // script pattern (OP_HASH160 <20 bytes> OP_EQUAL), not the hash value.
220        // Any 20-byte hash works for testing the policy logic.
221        let lock_script = p2sh_lock_script(&[0xdd; 20]);
222        let tx = make_v4_tx(vec![prevout_input(script_sig)], vec![]);
223        let spent_outputs = vec![output_with_script(lock_script)];
224
225        assert!(
226            are_inputs_standard(&tx, &spent_outputs),
227            "P2SH input with standard P2PKH redeemed script and correct stack depth should be standard"
228        );
229    }
230
231    #[test]
232    fn are_inputs_standard_rejects_p2sh_with_too_many_sigops() {
233        let _init_guard = zebra_test::init();
234
235        // Build a redeemed script that has more than MAX_P2SH_SIGOPS (15) sigops.
236        // Use 16 consecutive OP_CHECKSIG (0xac) opcodes.
237        let redeemed_script_bytes: Vec<u8> = vec![0xac; 16];
238
239        // scriptSig: just push the redeemed script (1 push)
240        // Since the redeemed script is non-standard, are_inputs_standard
241        // checks sigops. With 16 > MAX_P2SH_SIGOPS (15), it should reject.
242        let script_sig = p2sh_script_sig(&[&redeemed_script_bytes]);
243
244        let lock_script = p2sh_lock_script(&[0xdd; 20]);
245        let tx = make_v4_tx(vec![prevout_input(script_sig)], vec![]);
246        let spent_outputs = vec![output_with_script(lock_script)];
247
248        assert!(
249            !are_inputs_standard(&tx, &spent_outputs),
250            "P2SH input with redeemed script exceeding MAX_P2SH_SIGOPS should be non-standard"
251        );
252    }
253
254    #[test]
255    fn are_inputs_standard_accepts_p2sh_with_non_standard_low_sigops() {
256        let _init_guard = zebra_test::init();
257
258        // Build a redeemed script that is non-standard but has <= MAX_P2SH_SIGOPS (15).
259        // Use exactly 15 OP_CHECKSIG (0xac) opcodes -- should be accepted.
260        let redeemed_script_bytes: Vec<u8> = vec![0xac; 15];
261
262        let script_sig = p2sh_script_sig(&[&redeemed_script_bytes]);
263
264        let lock_script = p2sh_lock_script(&[0xdd; 20]);
265        let tx = make_v4_tx(vec![prevout_input(script_sig)], vec![]);
266        let spent_outputs = vec![output_with_script(lock_script)];
267
268        assert!(
269            are_inputs_standard(&tx, &spent_outputs),
270            "P2SH input with non-standard redeemed script at exactly MAX_P2SH_SIGOPS should be accepted"
271        );
272    }
273
274    // -- p2sh_sigop_count tests --
275
276    #[test]
277    fn p2sh_sigop_count_returns_sigops_for_p2sh_input() {
278        let _init_guard = zebra_test::init();
279
280        // Build a P2SH input whose redeemed script has 5 OP_CHECKSIG opcodes.
281        let redeemed_script_bytes: Vec<u8> = vec![0xac; 5];
282
283        let script_sig = p2sh_script_sig(&[&redeemed_script_bytes]);
284
285        let lock_script = p2sh_lock_script(&[0xdd; 20]);
286        let tx = make_v4_tx(vec![prevout_input(script_sig)], vec![]);
287        let spent_outputs = vec![output_with_script(lock_script)];
288
289        let count = p2sh_sigop_count(&tx, &spent_outputs);
290        assert_eq!(
291            count, 5,
292            "p2sh_sigop_count should return 5 for a redeemed script with 5 OP_CHECKSIG"
293        );
294    }
295
296    #[test]
297    fn p2sh_sigop_count_returns_zero_for_non_p2sh() {
298        let _init_guard = zebra_test::init();
299
300        // P2PKH spent output -- not P2SH, so p2sh_sigop_count should return 0.
301        let script_sig = push_only_script_sig(2);
302        let tx = make_v4_tx(vec![prevout_input(script_sig)], vec![]);
303        let spent_outputs = vec![output_with_script(p2pkh_lock_script(&[0xaa; 20]))];
304
305        let count = p2sh_sigop_count(&tx, &spent_outputs);
306        assert_eq!(
307            count, 0,
308            "p2sh_sigop_count should return 0 for non-P2SH inputs"
309        );
310    }
311
312    #[test]
313    fn p2sh_sigop_count_sums_across_multiple_inputs() {
314        let _init_guard = zebra_test::init();
315
316        // Input 0: P2SH with redeemed script having 3 OP_CHECKSIG
317        let redeemed_1: Vec<u8> = vec![0xac; 3];
318        let script_sig_1 = p2sh_script_sig(&[&redeemed_1]);
319        let lock_1 = p2sh_lock_script(&[0xdd; 20]);
320
321        // Input 1: P2PKH (non-P2SH, contributes 0)
322        let script_sig_2 = push_only_script_sig(2);
323        let lock_2 = p2pkh_lock_script(&[0xaa; 20]);
324
325        // Input 2: P2SH with redeemed script having 7 OP_CHECKSIG
326        let redeemed_3: Vec<u8> = vec![0xac; 7];
327        let script_sig_3 = p2sh_script_sig(&[&redeemed_3]);
328        let lock_3 = p2sh_lock_script(&[0xee; 20]);
329
330        let tx = make_v4_tx(
331            vec![
332                prevout_input(script_sig_1),
333                prevout_input(script_sig_2),
334                prevout_input(script_sig_3),
335            ],
336            vec![],
337        );
338        let spent_outputs = vec![
339            output_with_script(lock_1),
340            output_with_script(lock_2),
341            output_with_script(lock_3),
342        ];
343
344        let count = p2sh_sigop_count(&tx, &spent_outputs);
345        assert_eq!(
346            count, 10,
347            "p2sh_sigop_count should sum sigops across all P2SH inputs (3 + 0 + 7)"
348        );
349    }
350
351    #[test]
352    fn are_inputs_standard_rejects_second_non_standard_input() {
353        let _init_guard = zebra_test::init();
354
355        // Input 0: valid P2PKH (2 pushes)
356        let script_sig_ok = push_only_script_sig(2);
357        let lock_ok = p2pkh_lock_script(&[0xaa; 20]);
358
359        // Input 1: P2PKH with wrong stack depth (3 pushes instead of 2)
360        let script_sig_bad = push_only_script_sig(3);
361        let lock_bad = p2pkh_lock_script(&[0xbb; 20]);
362
363        let tx = make_v4_tx(
364            vec![prevout_input(script_sig_ok), prevout_input(script_sig_bad)],
365            vec![],
366        );
367        let spent_outputs = vec![output_with_script(lock_ok), output_with_script(lock_bad)];
368
369        assert!(
370            !are_inputs_standard(&tx, &spent_outputs),
371            "should reject when second input is non-standard even if first is valid"
372        );
373    }
374}