Skip to main content

zcash_primitives/transaction/
sighash.rs

1use alloc::boxed::Box;
2use core::fmt;
3
4use blake2b_simd::Hash as Blake2bHash;
5
6use super::{
7    Authorization, TransactionData, TxDigests, TxVersion,
8    sighash_v4::{v4_signature_hash, zip143_digests},
9    sighash_v5::{TransparentInputsDigests, v5_signature_hash},
10    sighash_v6::v6_signature_hash,
11    txid::TxIdDigester,
12};
13use ::sapling::bundle::GrothProofBytes;
14use ::transparent::sighash::TransparentAuthorizingContext;
15use zcash_protocol::value::Zatoshis;
16
17pub enum SignableInput<'a> {
18    Shielded,
19    Transparent(transparent::sighash::SignableInput<'a, Zatoshis>),
20}
21
22impl SignableInput<'_> {
23    pub fn hash_type(&self) -> u8 {
24        match self {
25            SignableInput::Shielded => ::transparent::sighash::SIGHASH_ALL,
26            SignableInput::Transparent(input) => input.hash_type().encode(),
27        }
28    }
29}
30
31pub struct SignatureHash(Blake2bHash);
32
33impl AsRef<[u8; 32]> for SignatureHash {
34    fn as_ref(&self) -> &[u8; 32] {
35        self.0.as_ref().try_into().unwrap()
36    }
37}
38
39/// A transaction, together with the digests over its data that the signature hash of
40/// every input of the transaction commits to.
41///
42/// Computing a value of this type takes time linear in the size of the transaction. Given
43/// it, [`PrecomputedSighashData::signature_hash`] computes the signature hash of an input
44/// in time independent of the number of inputs and outputs, so computing the signature
45/// hashes of all inputs of a transaction takes linear time in total.
46#[derive(Debug)]
47pub struct PrecomputedSighashData<A: Authorization> {
48    tx: TransactionData<A>,
49    tx_digests: TxDigests<Blake2bHash>,
50    /// The digests of the transparent input amounts and `scriptPubKey`s. This is `Some`
51    /// only for a transaction of version 5 or later that has non-coinbase transparent
52    /// inputs.
53    transparent_inputs_digests: Option<TransparentInputsDigests>,
54}
55
56impl<TA, SA, A> PrecomputedSighashData<A>
57where
58    TA: TransparentAuthorizingContext<Zatoshis>,
59    SA: sapling::bundle::Authorization<SpendProof = GrothProofBytes, OutputProof = GrothProofBytes>,
60    A: Authorization<SaplingAuth = SA, TransparentAuth = TA>,
61{
62    /// Computes the digests for `tx`.
63    pub fn new(tx: TransactionData<A>) -> Self {
64        let tx_digests = match tx.version {
65            TxVersion::Sprout(_) | TxVersion::V3 | TxVersion::V4 => {
66                TxDigests::Zip143(zip143_digests(&tx))
67            }
68            TxVersion::V5 | TxVersion::V6 => TxDigests::Zip244(tx.digest(TxIdDigester)),
69            #[cfg(zcash_unstable = "nutachyon")]
70            TxVersion::V7 => TxDigests::Zip244(tx.digest(TxIdDigester)),
71        };
72        Self::from_tx_digests(tx, tx_digests)
73    }
74}
75
76impl<TA, A> PrecomputedSighashData<A>
77where
78    TA: TransparentAuthorizingContext<Zatoshis>,
79    A: Authorization<TransparentAuth = TA>,
80{
81    /// Computes the digests for `tx`, which must be of version 5 or later.
82    ///
83    /// Unlike [`PrecomputedSighashData::new`], this does not require the Sapling proofs of
84    /// `tx` to be serialized, because [ZIP 244] and [ZIP 229] signature hashes do not commit
85    /// to them.
86    ///
87    /// Returns [`Zip244Error::NotZip244`] if `tx` is of version 4 or earlier.
88    ///
89    /// [ZIP 244]: https://zips.z.cash/zip-0244
90    /// [ZIP 229]: https://zips.z.cash/zip-0229#transactionidentifiersauthdigestsandsignaturedigests
91    pub fn new_zip244(tx: TransactionData<A>) -> Result<Self, Zip244Error<A>> {
92        match tx.version {
93            TxVersion::Sprout(_) | TxVersion::V3 | TxVersion::V4 => {
94                Err(Zip244Error::NotZip244(Box::new(tx)))
95            }
96            TxVersion::V5 | TxVersion::V6 => {
97                let tx_digests = TxDigests::Zip244(tx.digest(TxIdDigester));
98                Ok(Self::from_tx_digests(tx, tx_digests))
99            }
100            #[cfg(zcash_unstable = "nutachyon")]
101            TxVersion::V7 => {
102                let tx_digests = TxDigests::Zip244(tx.digest(TxIdDigester));
103                Ok(Self::from_tx_digests(tx, tx_digests))
104            }
105        }
106    }
107
108    /// Combines `tx` with the `tx_digests` computed from it, and computes the digests of
109    /// its transparent inputs if its signature hashes commit to them.
110    fn from_tx_digests(tx: TransactionData<A>, tx_digests: TxDigests<Blake2bHash>) -> Self {
111        let transparent_inputs_digests = match tx_digests {
112            TxDigests::Zip143(_) => None,
113            TxDigests::Zip244(_) => tx
114                .transparent_bundle
115                .as_ref()
116                .and_then(TransparentInputsDigests::for_bundle),
117        };
118        PrecomputedSighashData {
119            tx,
120            tx_digests,
121            transparent_inputs_digests,
122        }
123    }
124
125    /// Returns the transaction.
126    pub fn tx(&self) -> &TransactionData<A> {
127        &self.tx
128    }
129
130    /// Returns the digests of the transaction's effecting data.
131    pub fn tx_digests(&self) -> &TxDigests<Blake2bHash> {
132        &self.tx_digests
133    }
134
135    /// Returns the transaction, discarding the digests.
136    pub fn into_tx(self) -> TransactionData<A> {
137        self.tx
138    }
139
140    /// Computes the signature hash for an input to the transaction.
141    ///
142    /// This runs in time independent of the number of inputs and outputs of the
143    /// transaction.
144    ///
145    /// # Panics
146    ///
147    /// Panics if the transaction is a pre-Overwinter transaction, or if it is version 4
148    /// or earlier and `signable_input` is a transparent input but the transaction has
149    /// no transparent bundle. (In the latter case for v5 and later, the result is the
150    /// same as if `SignableInput::Shielded` were provided.)
151    pub fn signature_hash(&self, signable_input: &SignableInput) -> SignatureHash {
152        let inputs_digests = self.transparent_inputs_digests.as_ref();
153        SignatureHash(match &self.tx_digests {
154            TxDigests::Zip143(digests) => v4_signature_hash(&self.tx, signable_input, digests),
155            TxDigests::Zip244(txid_parts) if self.tx.version.has_ironwood() => {
156                v6_signature_hash(&self.tx, signable_input, txid_parts, inputs_digests)
157            }
158            TxDigests::Zip244(txid_parts) => {
159                v5_signature_hash(&self.tx, signable_input, txid_parts, inputs_digests)
160            }
161        })
162    }
163}
164
165/// An error returned by [`PrecomputedSighashData::new_zip244`].
166#[non_exhaustive]
167pub enum Zip244Error<A: Authorization> {
168    /// The transaction is of version 4 or earlier, so its signature hashes are not
169    /// [ZIP 244] or [ZIP 229] signature hashes. This holds the transaction, unchanged.
170    ///
171    /// [ZIP 244]: https://zips.z.cash/zip-0244
172    /// [ZIP 229]: https://zips.z.cash/zip-0229#transactionidentifiersauthdigestsandsignaturedigests
173    NotZip244(Box<TransactionData<A>>),
174}
175
176impl<A: Authorization> fmt::Debug for Zip244Error<A> {
177    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178        match self {
179            Zip244Error::NotZip244(tx) => f
180                .debug_struct("NotZip244")
181                .field("version", &tx.version)
182                .finish_non_exhaustive(),
183        }
184    }
185}
186
187impl<A: Authorization> fmt::Display for Zip244Error<A> {
188    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189        match self {
190            Zip244Error::NotZip244(tx) => write!(
191                f,
192                "transaction version {:?} does not use ZIP 244 or ZIP 229 signature hashes",
193                tx.version
194            ),
195        }
196    }
197}
198
199impl<A: Authorization> core::error::Error for Zip244Error<A> {}