Skip to main content

pczt/
roles.rs

1//! Implementations of the PCZT roles.
2//!
3//! The roles currently without an implementation are:
4//! - Constructor (anyone can contribute)
5//!   - Adds spends and outputs to the PCZT.
6//!   - Before any input or output may be added, the constructor must check the
7//!     `Global.tx_modifiable` field. Inputs may only be added if the Inputs Modifiable
8//!     flag is True. Outputs may only be added if the Outputs Modifiable flag is True.
9//!   - A single entity is likely to be both a Creator and Constructor.
10
11pub mod creator;
12
13#[cfg(feature = "io-finalizer")]
14pub mod io_finalizer;
15
16pub mod verifier;
17
18pub mod updater;
19
20pub mod redactor;
21
22#[cfg(feature = "prover")]
23pub mod prover;
24
25#[cfg(feature = "signer")]
26pub mod signer;
27
28pub mod low_level_signer;
29
30pub mod combiner;
31
32#[cfg(feature = "spend-finalizer")]
33pub mod spend_finalizer;
34
35#[cfg(feature = "tx-extractor")]
36pub mod tx_extractor;
37
38#[cfg(test)]
39mod tests {
40    #[cfg(any(feature = "io-finalizer", feature = "tx-extractor"))]
41    use {
42        crate::roles::creator::Creator,
43        rand::{rand_core::UnwrapErr, rngs::SysRng},
44        zcash_protocol::consensus::BranchId,
45    };
46
47    #[cfg(feature = "io-finalizer")]
48    use crate::roles::io_finalizer::{self, IoFinalizer};
49
50    #[cfg(feature = "tx-extractor")]
51    use crate::roles::tx_extractor::{self, TransactionExtractor};
52
53    #[cfg(feature = "tx-extractor")]
54    #[test]
55    fn extract_fails_on_empty() {
56        let pczt = Creator::new(
57            BranchId::Nu6.into(),
58            10_000_000,
59            133,
60            Some([0; 32]),
61            Some([0; 32]),
62        )
63        .unwrap()
64        .build()
65        .unwrap();
66
67        // Extraction fails because we haven't run the IO Finalizer.
68        // Extraction fails in Sapling because we happen to extract it before Orchard.
69        assert!(matches!(
70            TransactionExtractor::new(pczt)
71                .extract(UnwrapErr(SysRng))
72                .unwrap_err(),
73            tx_extractor::Error::Sapling(tx_extractor::SaplingError::Extract(
74                sapling::pczt::TxExtractorError::MissingBindingSignatureSigningKey
75            )),
76        ));
77    }
78
79    #[cfg(feature = "io-finalizer")]
80    #[test]
81    fn io_finalizer_fails_on_empty() {
82        let pczt = Creator::new(
83            BranchId::Nu6.into(),
84            10_000_000,
85            133,
86            Some([0; 32]),
87            Some([0; 32]),
88        )
89        .unwrap()
90        .build()
91        .unwrap();
92
93        // IO finalization fails on spends because we happen to check them first.
94        assert!(matches!(
95            IoFinalizer::new(pczt)
96                .finalize_io(UnwrapErr(SysRng))
97                .unwrap_err(),
98            io_finalizer::Error::NoSpends,
99        ));
100    }
101
102    /// Tests that a hostile Creator, Updater, or Combiner cannot induce the Signer or the
103    /// Spend Finalizer into producing a spend authorization over data that the coin being
104    /// spent does not commit to.
105    ///
106    /// These use a transparent-only PCZT so that the IO Finalizer does no shielded work
107    /// and no proving keys are needed.
108    #[cfg(all(
109        feature = "io-finalizer",
110        feature = "signer",
111        feature = "spend-finalizer",
112        feature = "zcp-builder"
113    ))]
114    mod transparent_authentication {
115        use alloc::vec::Vec;
116
117        use ::transparent::{
118            address::TransparentAddress,
119            bundle::{OutPoint, TxOut},
120            pczt::{SignerError, SpendFinalizerError, VerifyError},
121            sighash::{
122                SIGHASH_ALL, SIGHASH_ANYONECANPAY, SIGHASH_NONE, SIGHASH_SINGLE, SighashPolicy,
123            },
124        };
125        use rand::{rand_core::UnwrapErr, rngs::SysRng};
126        use zcash_primitives::transaction::{
127            builder::{BuildConfig, Builder, BundlePadding, PcztResult},
128            fees::zip317,
129        };
130        use zcash_protocol::{
131            consensus::{BlockHeight, MainNetwork},
132            value::Zatoshis,
133        };
134
135        use crate::{
136            Pczt,
137            roles::{
138                creator::Creator, io_finalizer::IoFinalizer, signer, signer::Signer,
139                spend_finalizer, spend_finalizer::SpendFinalizer,
140            },
141        };
142
143        const SIGHASH_ALL_ANYONECANPAY: u8 = SIGHASH_ALL | SIGHASH_ANYONECANPAY;
144
145        /// The height the test transactions are built for.
146        const TARGET_HEIGHT: BlockHeight = BlockHeight::from_u32(10_000_000);
147
148        /// The value of every coin the test transactions spend.
149        const COIN_VALUE: Zatoshis = Zatoshis::const_from_u64(1_000_000);
150
151        /// The single output of a transaction spending `coins` coins into one output: their value
152        /// less the ZIP 317 minimum fee at [`TARGET_HEIGHT`], which a transaction of at most two
153        /// transparent inputs and one transparent output pays.
154        fn output_after_fee(coins: u64) -> Zatoshis {
155            (COIN_VALUE * coins)
156                .and_then(|value| value - zip317::minimum_fee(&MainNetwork, TARGET_HEIGHT))
157                .expect("the coins cover the fee")
158        }
159
160        fn secret_key() -> secp256k1::SecretKey {
161            secp256k1::SecretKey::from_secret_bytes([1; 32]).expect("valid")
162        }
163
164        fn public_key(sk: &secp256k1::SecretKey) -> secp256k1::PublicKey {
165            sk.public_key()
166        }
167
168        /// The coin the victim is being asked to spend.
169        fn victim_coin() -> (OutPoint, TxOut<Zatoshis>) {
170            let addr = TransparentAddress::from_pubkey(&public_key(&secret_key()));
171            (
172                OutPoint::new([1; 32], 1),
173                TxOut::new(COIN_VALUE, addr.script().into()),
174            )
175        }
176
177        fn builder() -> Builder<MainNetwork, ()> {
178            Builder::new(
179                MainNetwork,
180                TARGET_HEIGHT,
181                BuildConfig::Standard {
182                    sapling_anchor: None,
183                    orchard_anchor: None,
184                    ironwood_anchor: None,
185                    orchard_padding: BundlePadding::DEFAULT,
186                    ironwood_padding: BundlePadding::DEFAULT,
187                },
188            )
189        }
190
191        fn finalize(builder: Builder<MainNetwork, ()>) -> Pczt {
192            let PcztResult { pczt_parts, .. } = builder
193                .build_for_pczt(UnwrapErr(SysRng), &zip317::FeeRule::standard())
194                .unwrap();
195
196            IoFinalizer::new(Creator::build_from_parts(pczt_parts).unwrap())
197                .finalize_io(UnwrapErr(SysRng))
198                .unwrap()
199        }
200
201        /// A PCZT spending a single P2PKH coin back to the victim's own address: the
202        /// transaction the victim believes it is authorizing.
203        fn transparent_pczt() -> Pczt {
204            let pubkey = public_key(&secret_key());
205            let addr = TransparentAddress::from_pubkey(&pubkey);
206            let (utxo, coin) = victim_coin();
207
208            let mut builder = builder();
209            builder
210                .add_transparent_p2pkh_input(pubkey, utxo, coin)
211                .unwrap();
212            builder
213                .add_transparent_output(&addr, output_after_fee(1))
214                .unwrap();
215            finalize(builder)
216        }
217
218        /// A PCZT whose single input has been tampered with by a hostile counterparty.
219        fn tampered_pczt(f: impl FnOnce(&mut crate::transparent::Input)) -> Pczt {
220            let mut pczt = transparent_pczt();
221            f(&mut pczt.transparent.inputs[0]);
222            pczt
223        }
224
225        /// A Signer over a PCZT tampered with by `f`, under `sighash_policy`.
226        fn signer(
227            f: impl FnOnce(&mut crate::transparent::Input),
228            sighash_policy: SighashPolicy,
229        ) -> Signer {
230            Signer::new(tampered_pczt(f))
231                .unwrap()
232                .with_transparent_sighash_policy(sighash_policy)
233        }
234
235        /// The sighash for the single input of `pczt`, computed under a policy wide
236        /// enough to admit whatever sighash type it carries.
237        fn unguarded_sighash(pczt: Pczt) -> [u8; 32] {
238            Signer::new(pczt)
239                .unwrap()
240                .with_transparent_sighash_policy(SighashPolicy::ANY)
241                .transparent_sighash(0)
242                .unwrap()
243        }
244
245        /// Signs `sighash` externally — as the counterparty who chose the input's
246        /// sighash type would — and offers the signature to a Signer with the default
247        /// policy.
248        fn append(pczt: Pczt, sighash: [u8; 32]) -> Result<(), signer::Error> {
249            let sig =
250                secp256k1::ecdsa::sign(secp256k1::Message::from_digest(sighash), &secret_key());
251            Signer::new(pczt)
252                .unwrap()
253                .append_transparent_signature(0, sig)
254        }
255
256        #[test]
257        fn signer_rejects_unauthenticated_redeem_script() {
258            // The coin being spent is P2PKH, so it commits to no redeem script at all;
259            // `Input::sign` would otherwise search this one for the signer’s pubkey and
260            // commit to it in the sighash.
261            let mut signer = signer(
262                |input| input.redeem_script = Some(vec![0x51]),
263                SighashPolicy::ALL_ONLY,
264            );
265
266            assert!(matches!(
267                signer.sign_transparent(0, &secret_key()),
268                Err(signer::Error::TransparentSign(SignerError::InvalidInput(
269                    VerifyError::NotP2sh
270                ))),
271            ));
272        }
273
274        /// The external-signature path has to authenticate the input for the same reason.
275        #[test]
276        fn signer_rejects_unauthenticated_redeem_script_when_appending() {
277            // The input is refused before the signature is examined, so what was signed
278            // does not matter — and the Signer will not compute a sighash over this input
279            // for us to sign in the first place.
280            assert!(matches!(
281                append(
282                    tampered_pczt(|input| input.redeem_script = Some(vec![0x51])),
283                    [0; 32],
284                ),
285                Err(signer::Error::TransparentSign(SignerError::InvalidInput(
286                    VerifyError::NotP2sh
287                ))),
288            ));
289        }
290
291        /// The same holds for the sighash the Signer hands to an external signer: whoever
292        /// signs it is authorizing whatever it commits to.
293        #[test]
294        fn signer_rejects_unauthenticated_redeem_script_when_computing_sighash() {
295            let signer = signer(
296                |input| input.redeem_script = Some(vec![0x51]),
297                SighashPolicy::ALL_ONLY,
298            );
299
300            assert!(matches!(
301                signer.transparent_sighash(0),
302                Err(signer::Error::TransparentSign(SignerError::InvalidInput(
303                    VerifyError::NotP2sh
304                ))),
305            ));
306        }
307
308        #[test]
309        fn signer_rejects_hostile_sighash_type() {
310            let mut signer = signer(
311                |input| input.sighash_type = SIGHASH_NONE | SIGHASH_ANYONECANPAY,
312                SighashPolicy::ALL_ONLY,
313            );
314
315            assert!(matches!(
316                signer.sign_transparent(0, &secret_key()),
317                Err(signer::Error::TransparentSign(
318                    SignerError::DisallowedSighashType(_)
319                )),
320            ));
321        }
322
323        #[test]
324        fn signer_rejects_hostile_sighash_type_when_appending() {
325            let pczt =
326                tampered_pczt(|input| input.sighash_type = SIGHASH_NONE | SIGHASH_ANYONECANPAY);
327            let sighash = unguarded_sighash(pczt.clone());
328
329            assert!(matches!(
330                append(pczt, sighash),
331                Err(signer::Error::TransparentSign(
332                    SignerError::DisallowedSighashType(_)
333                )),
334            ));
335        }
336
337        #[test]
338        fn signer_rejects_hostile_sighash_type_when_computing_sighash() {
339            let signer = signer(
340                |input| input.sighash_type = SIGHASH_NONE | SIGHASH_ANYONECANPAY,
341                SighashPolicy::ALL_ONLY,
342            );
343
344            assert!(matches!(
345                signer.transparent_sighash(0),
346                Err(signer::Error::TransparentSign(
347                    SignerError::DisallowedSighashType(_)
348                )),
349            ));
350        }
351
352        #[test]
353        fn signer_accepts_hostile_sighash_type_under_explicit_policy() {
354            let mut signer = signer(
355                |input| input.sighash_type = SIGHASH_NONE | SIGHASH_ANYONECANPAY,
356                SighashPolicy::ANY,
357            );
358
359            assert!(signer.sign_transparent(0, &secret_key()).is_ok());
360        }
361
362        /// Signs the single input of a PCZT tampered with by `f`, under `sighash_policy`.
363        fn signed(
364            f: impl FnOnce(&mut crate::transparent::Input),
365            sighash_policy: SighashPolicy,
366        ) -> Pczt {
367            let mut signer = signer(f, sighash_policy);
368            signer.sign_transparent(0, &secret_key()).unwrap();
369            signer.finish()
370        }
371
372        /// A signed PCZT whose input uses `SIGHASH_NONE`.
373        fn signed_sighash_none() -> Pczt {
374            signed(
375                |input| input.sighash_type = SIGHASH_NONE,
376                SighashPolicy::ANY,
377            )
378        }
379
380        #[test]
381        fn finalizer_rejects_non_all_sighash_type() {
382            assert!(matches!(
383                SpendFinalizer::new(signed_sighash_none()).finalize_spends(),
384                Err(spend_finalizer::Error::TransparentFinalize(
385                    SpendFinalizerError::DisallowedSighashType(_)
386                )),
387            ));
388        }
389
390        #[test]
391        fn finalizer_accepts_non_all_sighash_type_under_explicit_policy() {
392            assert!(
393                SpendFinalizer::new(signed_sighash_none())
394                    .with_sighash_policy(SighashPolicy::ANY)
395                    .finalize_spends()
396                    .is_ok()
397            );
398        }
399
400        #[test]
401        fn finalizer_accepts_all_sighash_type() {
402            let pczt = signed(|_| (), SighashPolicy::ALL_ONLY);
403            assert!(SpendFinalizer::new(pczt).finalize_spends().is_ok());
404        }
405
406        /// The attacker's own coin, which they contribute to their own transaction.
407        fn attacker_coin() -> (secp256k1::PublicKey, OutPoint, TxOut<Zatoshis>) {
408            let pubkey =
409                public_key(&secp256k1::SecretKey::from_secret_bytes([2; 32]).expect("valid"));
410            let addr = TransparentAddress::from_pubkey(&pubkey);
411            (
412                pubkey,
413                OutPoint::new([2; 32], 0),
414                TxOut::new(COIN_VALUE, addr.script().into()),
415            )
416        }
417
418        /// A PCZT for a *different* transaction, which the victim never sees: it spends
419        /// the same coin of theirs alongside one of the attacker's, and pays the whole
420        /// balance to the attacker.
421        fn attacker_pczt(sighash_type: u8) -> Pczt {
422            let (attacker_pubkey, attacker_utxo, attacker_coin) = attacker_coin();
423            let attacker_addr = TransparentAddress::from_pubkey(&attacker_pubkey);
424            let (victim_utxo, victim_coin) = victim_coin();
425
426            let mut builder = builder();
427            builder
428                .add_transparent_p2pkh_input(public_key(&secret_key()), victim_utxo, victim_coin)
429                .unwrap();
430            builder
431                .add_transparent_p2pkh_input(attacker_pubkey, attacker_utxo, attacker_coin)
432                .unwrap();
433            builder
434                .add_transparent_output(&attacker_addr, output_after_fee(2))
435                .unwrap();
436
437            let mut pczt = finalize(builder);
438            pczt.transparent.inputs[0].sighash_type = sighash_type;
439            pczt
440        }
441
442        /// The victim's signature over the single input of the transaction they were
443        /// shown, with the trailing sighash byte stripped.
444        fn victim_signature(sighash_type: u8, sighash_policy: SighashPolicy) -> Vec<u8> {
445            let pczt = signed(|input| input.sighash_type = sighash_type, sighash_policy);
446            let mut sig = pczt.transparent.inputs[0]
447                .partial_signatures
448                .get(&public_key(&secret_key()).serialize())
449                .expect("the victim signed")
450                .clone();
451            assert_eq!(
452                sig.pop(),
453                Some(sighash_type),
454                "signature carries its sighash type"
455            );
456            sig
457        }
458
459        /// Whether `sig` authorizes the victim's input of `pczt`.
460        fn authorizes(sig: &[u8], pczt: Pczt) -> bool {
461            let sighash = unguarded_sighash(pczt);
462
463            secp256k1::ecdsa::verify(
464                &secp256k1::ecdsa::Signature::from_der(sig).expect("DER-encoded"),
465                secp256k1::Message::from_digest(sighash),
466                &public_key(&secret_key()),
467            )
468            .is_ok()
469        }
470
471        /// Why `SighashPolicy::ALL_ONLY` is the default: a signature the victim was
472        /// induced to make under `SIGHASH_NONE | SIGHASH_ANYONECANPAY` commits to
473        /// neither the outputs nor the other inputs, so it is equally a valid
474        /// authorization of a transaction the victim never saw, which pays the attacker.
475        ///
476        /// The Signer refuses to produce this signature at all unless the caller opts in,
477        /// which is what `signer_rejects_hostile_sighash_type` covers; this test is what
478        /// makes that refusal worth having.
479        #[test]
480        fn a_non_all_signature_authorizes_the_attackers_transaction() {
481            let hostile = SIGHASH_NONE | SIGHASH_ANYONECANPAY;
482            let sig = victim_signature(hostile, SighashPolicy::ANY);
483
484            assert!(
485                authorizes(&sig, tampered_pczt(|input| input.sighash_type = hostile)),
486                "the victim's signature should authorize the transaction they were shown",
487            );
488            assert!(
489                authorizes(&sig, attacker_pczt(hostile)),
490                "and, because it commits to neither the outputs nor the other inputs, \
491                 the attacker's transaction as well",
492            );
493        }
494
495        /// The contrast: a `SIGHASH_ALL` signature over the same input commits to the
496        /// whole transaction the victim was shown, so it authorizes nothing else.
497        #[test]
498        fn an_all_signature_authorizes_nothing_else() {
499            let sig = victim_signature(SIGHASH_ALL, SighashPolicy::ALL_ONLY);
500
501            // Establishes that the negative below is a real refusal rather than, say, a
502            // signature that fails to verify against anything at all.
503            assert!(
504                authorizes(&sig, transparent_pczt()),
505                "the victim's signature should authorize the transaction they were shown",
506            );
507            assert!(
508                !authorizes(&sig, attacker_pczt(SIGHASH_ALL)),
509                "but not the attacker's",
510            );
511        }
512
513        #[test]
514        fn finalizer_accepts_sighash_single() {
515            let pczt = signed(
516                |input| input.sighash_type = SIGHASH_SINGLE,
517                SighashPolicy::ANY,
518            );
519
520            assert!(
521                SpendFinalizer::new(pczt)
522                    .with_sighash_policy(SighashPolicy::ANY)
523                    .finalize_spends()
524                    .is_ok()
525            );
526        }
527
528        /// Inputs of a single transaction may deliberately use different sighash types:
529        /// contributors sign `SIGHASH_ALL | SIGHASH_ANYONECANPAY` so that the input set
530        /// stays open, and whoever assembles the transaction fixes it with a
531        /// `SIGHASH_ALL` signature over their own input.
532        #[test]
533        fn finalizer_accepts_mixed_sighash_types() {
534            let contributor_sk = secp256k1::SecretKey::from_secret_bytes([3; 32]).expect("valid");
535            let contributor_pubkey = public_key(&contributor_sk);
536            let contributor_utxo = OutPoint::new([3; 32], 0);
537            let contributor_coin = TxOut::new(
538                COIN_VALUE,
539                TransparentAddress::from_pubkey(&contributor_pubkey)
540                    .script()
541                    .into(),
542            );
543            let (assembler_utxo, assembler_coin) = victim_coin();
544            let addr = TransparentAddress::from_pubkey(&public_key(&secret_key()));
545
546            let mut builder = builder();
547            builder
548                .add_transparent_p2pkh_input(
549                    public_key(&secret_key()),
550                    assembler_utxo,
551                    assembler_coin,
552                )
553                .unwrap();
554            builder
555                .add_transparent_p2pkh_input(contributor_pubkey, contributor_utxo, contributor_coin)
556                .unwrap();
557            builder
558                .add_transparent_output(&addr, output_after_fee(2))
559                .unwrap();
560
561            let mut pczt = finalize(builder);
562            pczt.transparent.inputs[1].sighash_type = SIGHASH_ALL_ANYONECANPAY;
563
564            let mut signer = Signer::new(pczt)
565                .unwrap()
566                .with_transparent_sighash_policy(SighashPolicy::ANY);
567            signer.sign_transparent(0, &secret_key()).unwrap();
568            signer.sign_transparent(1, &contributor_sk).unwrap();
569
570            assert!(
571                SpendFinalizer::new(signer.finish())
572                    .with_sighash_policy(SighashPolicy::ANY)
573                    .finalize_spends()
574                    .is_ok()
575            );
576        }
577    }
578}