Skip to main content

zcash_primitives/transaction/
txid.rs

1use crate::encoding::{StateWrite, WriteBytesExt};
2use core::borrow::Borrow;
3use core::convert::TryFrom;
4use corez::io::Write;
5
6use blake2b_simd::{Hash as Blake2bHash, Params};
7use ff::PrimeField;
8
9use ::orchard::{
10    ValuePool,
11    bundle::{self as orchard, TxVersion as OrchardTxVersion},
12};
13use ::sapling::bundle::{OutputDescription, SpendDescription};
14use ::transparent::bundle::{self as transparent, TxIn, TxOut};
15use zcash_protocol::{
16    consensus::{BlockHeight, BranchId},
17    value::{ZatBalance, Zatoshis},
18};
19
20use super::{
21    Authorization, Authorized, TransactionDigest, TransparentDigests, TxId, TxVersion,
22    Zip244Digests,
23    components::transparent::{write_outpoint, write_script, write_txout},
24};
25
26/// TxId tree root personalization
27const ZCASH_TX_PERSONALIZATION_PREFIX: &[u8; 12] = b"ZcashTxHash_";
28
29// TxId level 1 node personalization
30const ZCASH_HEADERS_HASH_PERSONALIZATION: &[u8; 16] = b"ZTxIdHeadersHash";
31pub(crate) const ZCASH_TRANSPARENT_HASH_PERSONALIZATION: &[u8; 16] = b"ZTxIdTranspaHash";
32const ZCASH_SAPLING_HASH_PERSONALIZATION: &[u8; 16] = b"ZTxIdSaplingHash";
33
34// TxId transparent level 2 node personalization
35const ZCASH_PREVOUTS_HASH_PERSONALIZATION: &[u8; 16] = b"ZTxIdPrevoutHash";
36const ZCASH_SEQUENCE_HASH_PERSONALIZATION: &[u8; 16] = b"ZTxIdSequencHash";
37const ZCASH_OUTPUTS_HASH_PERSONALIZATION: &[u8; 16] = b"ZTxIdOutputsHash";
38
39// TxId sapling level 2 node personalization
40const ZCASH_SAPLING_SPENDS_HASH_PERSONALIZATION: &[u8; 16] = b"ZTxIdSSpendsHash";
41const ZCASH_SAPLING_SPENDS_COMPACT_HASH_PERSONALIZATION: &[u8; 16] = b"ZTxIdSSpendCHash";
42const ZCASH_SAPLING_SPENDS_NONCOMPACT_HASH_PERSONALIZATION: &[u8; 16] = b"ZTxIdSSpendNHash";
43const ZCASH_SAPLING_SPENDS_V6_NONCOMPACT_HASH_PERSONALIZATION: &[u8; 16] = b"ZTxIdSSpendNH_v6";
44
45const ZCASH_SAPLING_OUTPUTS_HASH_PERSONALIZATION: &[u8; 16] = b"ZTxIdSOutputHash";
46const ZCASH_SAPLING_OUTPUTS_COMPACT_HASH_PERSONALIZATION: &[u8; 16] = b"ZTxIdSOutC__Hash";
47const ZCASH_SAPLING_OUTPUTS_MEMOS_HASH_PERSONALIZATION: &[u8; 16] = b"ZTxIdSOutM__Hash";
48const ZCASH_SAPLING_OUTPUTS_NONCOMPACT_HASH_PERSONALIZATION: &[u8; 16] = b"ZTxIdSOutN__Hash";
49
50const ZCASH_AUTH_PERSONALIZATION_PREFIX: &[u8; 12] = b"ZTxAuthHash_";
51const ZCASH_TRANSPARENT_SCRIPTS_HASH_PERSONALIZATION: &[u8; 16] = b"ZTxAuthTransHash";
52const ZCASH_SAPLING_SIGS_HASH_PERSONALIZATION: &[u8; 16] = b"ZTxAuthSapliHash";
53const ZCASH_SAPLING_V6_SIGS_HASH_PERSONALIZATION: &[u8; 16] = b"ZTxAuthSapliH_v6";
54
55fn sapling_spends_noncompact_personalization(version: TxVersion) -> &'static [u8; 16] {
56    match version {
57        TxVersion::Sprout(_) | TxVersion::V3 | TxVersion::V4 | TxVersion::V5 => {
58            ZCASH_SAPLING_SPENDS_NONCOMPACT_HASH_PERSONALIZATION
59        }
60        TxVersion::V6 => ZCASH_SAPLING_SPENDS_V6_NONCOMPACT_HASH_PERSONALIZATION,
61        #[cfg(zcash_unstable = "nutachyon")]
62        TxVersion::V7 => ZCASH_SAPLING_SPENDS_V6_NONCOMPACT_HASH_PERSONALIZATION,
63    }
64}
65
66fn sapling_auth_personalization(version: TxVersion) -> &'static [u8; 16] {
67    match version {
68        TxVersion::Sprout(_) | TxVersion::V3 | TxVersion::V4 | TxVersion::V5 => {
69            ZCASH_SAPLING_SIGS_HASH_PERSONALIZATION
70        }
71        TxVersion::V6 => ZCASH_SAPLING_V6_SIGS_HASH_PERSONALIZATION,
72        #[cfg(zcash_unstable = "nutachyon")]
73        TxVersion::V7 => ZCASH_SAPLING_V6_SIGS_HASH_PERSONALIZATION,
74    }
75}
76
77fn sapling_auth_includes_anchor(version: TxVersion) -> bool {
78    match version {
79        TxVersion::Sprout(_) | TxVersion::V3 | TxVersion::V4 | TxVersion::V5 => false,
80        TxVersion::V6 => true,
81        #[cfg(zcash_unstable = "nutachyon")]
82        TxVersion::V7 => true,
83    }
84}
85
86/// Selects the `(value pool, orchard tx version)` pair identifying the
87/// `BundleCommitmentDomain` used for Orchard-slot commitments in the given
88/// transaction version. The value pool here is only used for empty-bundle
89/// commitments (which hash no flags); present bundles compute their commitments
90/// from the `BundleVersion` each bundle carries.
91fn orchard_commitment_domain(version: TxVersion) -> (ValuePool, OrchardTxVersion) {
92    match version {
93        TxVersion::Sprout(_) | TxVersion::V3 | TxVersion::V4 | TxVersion::V5 => {
94            (ValuePool::Orchard, OrchardTxVersion::V5)
95        }
96        TxVersion::V6 => (ValuePool::Orchard, OrchardTxVersion::V6),
97        #[cfg(zcash_unstable = "nutachyon")]
98        TxVersion::V7 => (ValuePool::Orchard, OrchardTxVersion::V6),
99    }
100}
101
102fn ironwood_v6_domain() -> (ValuePool, OrchardTxVersion) {
103    (ValuePool::Ironwood, OrchardTxVersion::V6)
104}
105
106fn hasher(personal: &[u8; 16]) -> StateWrite {
107    StateWrite(Params::new().hash_length(32).personal(personal).to_state())
108}
109
110/// Sequentially append the serialized value of each transparent input
111/// to a hash personalized by ZCASH_PREVOUTS_HASH_PERSONALIZATION.
112/// In the case that no inputs are provided, this produces a default
113/// hash from just the personalization string.
114pub(crate) fn transparent_prevout_hash<TransparentAuth: transparent::Authorization>(
115    vin: &[TxIn<TransparentAuth>],
116) -> Blake2bHash {
117    let mut h = hasher(ZCASH_PREVOUTS_HASH_PERSONALIZATION);
118    for t_in in vin {
119        write_outpoint(&mut h, t_in.prevout()).unwrap();
120    }
121    h.finalize()
122}
123
124/// Hash of the little-endian u32 interpretation of the
125/// `sequence` values for each TxIn record passed in vin.
126pub(crate) fn transparent_sequence_hash<TransparentAuth: transparent::Authorization>(
127    vin: &[TxIn<TransparentAuth>],
128) -> Blake2bHash {
129    let mut h = hasher(ZCASH_SEQUENCE_HASH_PERSONALIZATION);
130    for t_in in vin {
131        h.write_u32_le(t_in.sequence()).unwrap();
132    }
133    h.finalize()
134}
135
136/// Sequentially append the full serialized value of each transparent output
137/// to a hash personalized by ZCASH_OUTPUTS_HASH_PERSONALIZATION.
138/// In the case that no outputs are provided, this produces a default
139/// hash from just the personalization string.
140pub(crate) fn transparent_outputs_hash<T: Borrow<TxOut<Zatoshis>>>(vout: &[T]) -> Blake2bHash {
141    let mut h = hasher(ZCASH_OUTPUTS_HASH_PERSONALIZATION);
142    for t_out in vout {
143        write_txout(&mut h, t_out.borrow()).unwrap();
144    }
145    h.finalize()
146}
147
148/// Implements [ZIP 244 section T.3a](https://zips.z.cash/zip-0244#t-3a-sapling-spends-digest);
149/// the v6 variant is specified in [ZIP 229](https://zips.z.cash/zip-0229).
150///
151/// Write disjoint parts of each Sapling shielded spend to a pair of hashes:
152/// * \[nullifier*\] - personalized with ZCASH_SAPLING_SPENDS_COMPACT_HASH_PERSONALIZATION
153/// * \[(cv, anchor, rk)*\] for v5 transactions (v4 is not handled here), personalized with
154///   ZCASH_SAPLING_SPENDS_NONCOMPACT_HASH_PERSONALIZATION
155/// * \[(cv, rk)*\] for v6 transactions, personalized with
156///   ZCASH_SAPLING_SPENDS_V6_NONCOMPACT_HASH_PERSONALIZATION
157///
158/// Then, hash these together personalized by ZCASH_SAPLING_SPENDS_HASH_PERSONALIZATION
159pub(crate) fn hash_sapling_spends<A: sapling::bundle::Authorization>(
160    version: TxVersion,
161    shielded_spends: &[SpendDescription<A>],
162) -> Blake2bHash {
163    let mut h = hasher(ZCASH_SAPLING_SPENDS_HASH_PERSONALIZATION);
164    if !shielded_spends.is_empty() {
165        let mut ch = hasher(ZCASH_SAPLING_SPENDS_COMPACT_HASH_PERSONALIZATION);
166        let mut nh = hasher(sapling_spends_noncompact_personalization(version));
167        for s_spend in shielded_spends {
168            // we build the hash of nullifiers separately for compact blocks.
169            ch.write_all(s_spend.nullifier().as_ref()).unwrap();
170
171            nh.write_all(&s_spend.cv().to_bytes()).unwrap();
172            let write_anchor = match version {
173                TxVersion::Sprout(_) | TxVersion::V3 | TxVersion::V4 | TxVersion::V5 => true,
174                TxVersion::V6 => false,
175                #[cfg(zcash_unstable = "nutachyon")]
176                TxVersion::V7 => false,
177            };
178            if write_anchor {
179                nh.write_all(&s_spend.anchor().to_repr()).unwrap();
180            }
181            nh.write_all(&<[u8; 32]>::from(*s_spend.rk())).unwrap();
182        }
183
184        let compact_digest = ch.finalize();
185        h.write_all(compact_digest.as_bytes()).unwrap();
186        let noncompact_digest = nh.finalize();
187        h.write_all(noncompact_digest.as_bytes()).unwrap();
188    }
189    h.finalize()
190}
191
192/// Implements [ZIP 244 section T.3b](https://zips.z.cash/zip-0244#t-3b-sapling-outputs-digest)
193///
194/// Write disjoint parts of each Sapling shielded output as 3 separate hashes:
195/// * \[(cmu, epk, enc_ciphertext\[..52\])*\] personalized with ZCASH_SAPLING_OUTPUTS_COMPACT_HASH_PERSONALIZATION
196/// * \[enc_ciphertext\[52..564\]*\] (memo ciphertexts) personalized with ZCASH_SAPLING_OUTPUTS_MEMOS_HASH_PERSONALIZATION
197/// * \[(cv, enc_ciphertext\[564..\], out_ciphertext, zkproof)*\] personalized with ZCASH_SAPLING_OUTPUTS_NONCOMPACT_HASH_PERSONALIZATION
198///
199/// Then, hash these together personalized with ZCASH_SAPLING_OUTPUTS_HASH_PERSONALIZATION
200pub(crate) fn hash_sapling_outputs<A>(shielded_outputs: &[OutputDescription<A>]) -> Blake2bHash {
201    let mut h = hasher(ZCASH_SAPLING_OUTPUTS_HASH_PERSONALIZATION);
202    if !shielded_outputs.is_empty() {
203        let mut ch = hasher(ZCASH_SAPLING_OUTPUTS_COMPACT_HASH_PERSONALIZATION);
204        let mut mh = hasher(ZCASH_SAPLING_OUTPUTS_MEMOS_HASH_PERSONALIZATION);
205        let mut nh = hasher(ZCASH_SAPLING_OUTPUTS_NONCOMPACT_HASH_PERSONALIZATION);
206        for s_out in shielded_outputs {
207            ch.write_all(s_out.cmu().to_bytes().as_ref()).unwrap();
208            ch.write_all(s_out.ephemeral_key().as_ref()).unwrap();
209            ch.write_all(&s_out.enc_ciphertext()[..52]).unwrap();
210
211            mh.write_all(&s_out.enc_ciphertext()[52..564]).unwrap();
212
213            nh.write_all(&s_out.cv().to_bytes()).unwrap();
214            nh.write_all(&s_out.enc_ciphertext()[564..]).unwrap();
215            nh.write_all(&s_out.out_ciphertext()[..]).unwrap();
216        }
217
218        h.write_all(ch.finalize().as_bytes()).unwrap();
219        h.write_all(mh.finalize().as_bytes()).unwrap();
220        h.write_all(nh.finalize().as_bytes()).unwrap();
221    }
222    h.finalize()
223}
224
225/// The txid commits to the hash of all transparent outputs. The
226/// prevout and sequence_hash components of txid
227fn transparent_digests<A: transparent::Authorization>(
228    bundle: &transparent::Bundle<A, Zatoshis>,
229) -> TransparentDigests<Blake2bHash> {
230    TransparentDigests {
231        prevouts_digest: transparent_prevout_hash(&bundle.vin),
232        sequence_digest: transparent_sequence_hash(&bundle.vin),
233        outputs_digest: transparent_outputs_hash(&bundle.vout),
234    }
235}
236
237/// Implements [ZIP 244 section T.1](https://zips.z.cash/zip-0244#t-1-header-digest)
238fn hash_header_txid_data(
239    version: TxVersion,
240    // we commit to the consensus branch ID with the header
241    consensus_branch_id: BranchId,
242    lock_time: u32,
243    expiry_height: BlockHeight,
244) -> Blake2bHash {
245    let mut h = hasher(ZCASH_HEADERS_HASH_PERSONALIZATION);
246
247    h.write_u32_le(version.header()).unwrap();
248    h.write_u32_le(version.version_group_id()).unwrap();
249    h.write_u32_le(consensus_branch_id.into()).unwrap();
250    h.write_u32_le(lock_time).unwrap();
251    h.write_u32_le(expiry_height.into()).unwrap();
252
253    h.finalize()
254}
255
256/// Implements [ZIP 244 section T.2](https://zips.z.cash/zip-0244#t-2-transparent-digest)
257pub(crate) fn hash_transparent_txid_data(
258    t_digests: Option<&TransparentDigests<Blake2bHash>>,
259) -> Blake2bHash {
260    let mut h = hasher(ZCASH_TRANSPARENT_HASH_PERSONALIZATION);
261    if let Some(d) = t_digests {
262        h.write_all(d.prevouts_digest.as_bytes()).unwrap();
263        h.write_all(d.sequence_digest.as_bytes()).unwrap();
264        h.write_all(d.outputs_digest.as_bytes()).unwrap();
265    }
266    h.finalize()
267}
268
269/// Implements [ZIP 244 section T.3](https://zips.z.cash/zip-0244#t-3-sapling-digest);
270/// for v6 transactions the Sapling digest follows
271/// [ZIP 229](https://zips.z.cash/zip-0229).
272fn hash_sapling_txid_data<A: sapling::bundle::Authorization>(
273    version: TxVersion,
274    bundle: &sapling::Bundle<A, ZatBalance>,
275) -> Blake2bHash {
276    let mut h = hasher(ZCASH_SAPLING_HASH_PERSONALIZATION);
277    if !(bundle.shielded_spends().is_empty() && bundle.shielded_outputs().is_empty()) {
278        h.write_all(hash_sapling_spends(version, bundle.shielded_spends()).as_bytes())
279            .unwrap();
280
281        h.write_all(hash_sapling_outputs(bundle.shielded_outputs()).as_bytes())
282            .unwrap();
283
284        h.write_all(&bundle.value_balance().to_i64_le_bytes())
285            .unwrap();
286    }
287    h.finalize()
288}
289
290fn hash_sapling_txid_empty() -> Blake2bHash {
291    hasher(ZCASH_SAPLING_HASH_PERSONALIZATION).finalize()
292}
293
294/// A TransactionDigest implementation that commits to all of the effecting
295/// data of a transaction to produce a nonmalleable transaction identifier.
296///
297/// This expects and relies upon the existence of canonical encodings for
298/// each effecting component of a transaction.
299///
300/// This implements transaction ID digests for v5 transactions ([ZIP 244]) and for
301/// v6 transactions ([ZIP 229]). It cannot be used to compute the transaction ID for
302/// v4 or earlier transactions; those used `SHA-256(SHA-256(tx_encoding))` and are
303/// malleable.
304///
305/// [ZIP 244]: https://zips.z.cash/zip-0244#txid-digest
306/// [ZIP 229]: https://zips.z.cash/zip-0229#transactionidentifiersauthdigestsandsignaturedigests
307pub struct TxIdDigester;
308
309impl<A: Authorization> TransactionDigest<A> for TxIdDigester {
310    type HeaderDigest = Blake2bHash;
311    type TransparentDigest = Option<TransparentDigests<Blake2bHash>>;
312    type SaplingDigest = Option<Blake2bHash>;
313    type OrchardDigest = Option<Blake2bHash>;
314    type IronwoodDigest = Option<Blake2bHash>;
315
316    type Digest = Zip244Digests<Blake2bHash>;
317
318    fn digest_header(
319        &self,
320        version: TxVersion,
321        consensus_branch_id: BranchId,
322        lock_time: u32,
323        expiry_height: BlockHeight,
324    ) -> Self::HeaderDigest {
325        hash_header_txid_data(version, consensus_branch_id, lock_time, expiry_height)
326    }
327
328    fn digest_transparent(
329        &self,
330        transparent_bundle: Option<&transparent::Bundle<A::TransparentAuth, Zatoshis>>,
331    ) -> Self::TransparentDigest {
332        transparent_bundle.map(transparent_digests)
333    }
334
335    fn digest_sapling(
336        &self,
337        version: TxVersion,
338        sapling_bundle: Option<&sapling::Bundle<A::SaplingAuth, ZatBalance>>,
339    ) -> Self::SaplingDigest {
340        sapling_bundle.map(|bundle| hash_sapling_txid_data(version, bundle))
341    }
342
343    fn digest_orchard(
344        &self,
345        version: TxVersion,
346        orchard_bundle: Option<&orchard::Bundle<A::OrchardAuth, ZatBalance>>,
347    ) -> Self::OrchardDigest {
348        orchard_bundle.map(|b| {
349            let (_, tx_version) = orchard_commitment_domain(version);
350            b.commitment(tx_version)
351                .expect("Orchard bundle flags must be representable in their transaction format")
352                .0
353        })
354    }
355
356    fn digest_ironwood(
357        &self,
358        ironwood_bundle: Option<&orchard::Bundle<A::OrchardAuth, ZatBalance>>,
359    ) -> Self::IronwoodDigest {
360        ironwood_bundle.map(|b| {
361            let (_, tx_version) = ironwood_v6_domain();
362            b.commitment(tx_version)
363                .expect("Ironwood bundle flags must be representable")
364                .0
365        })
366    }
367
368    fn combine(
369        &self,
370        header_digest: Self::HeaderDigest,
371        transparent_digests: Self::TransparentDigest,
372        sapling_digest: Self::SaplingDigest,
373        orchard_digest: Self::OrchardDigest,
374        ironwood_digest: Self::IronwoodDigest,
375    ) -> Self::Digest {
376        Zip244Digests {
377            header_digest,
378            transparent_digests,
379            sapling_digest,
380            orchard_digest,
381            ironwood_digest,
382        }
383    }
384}
385
386pub(crate) fn to_hash(
387    _txversion: TxVersion,
388    consensus_branch_id: BranchId,
389    header_digest: Blake2bHash,
390    transparent_digest: Blake2bHash,
391    sapling_digest: Option<Blake2bHash>,
392    orchard_digest: Option<Blake2bHash>,
393) -> Blake2bHash {
394    let mut personal = [0; 16];
395    personal[..12].copy_from_slice(ZCASH_TX_PERSONALIZATION_PREFIX);
396    (&mut personal[12..])
397        .write_u32_le(consensus_branch_id.into())
398        .unwrap();
399
400    let mut h = hasher(&personal);
401    h.write_all(header_digest.as_bytes()).unwrap();
402    h.write_all(transparent_digest.as_bytes()).unwrap();
403    h.write_all(
404        sapling_digest
405            .unwrap_or_else(hash_sapling_txid_empty)
406            .as_bytes(),
407    )
408    .unwrap();
409    h.write_all(
410        orchard_digest
411            .unwrap_or_else(|| {
412                let (value_pool, tx_version) = orchard_commitment_domain(_txversion);
413                orchard::commitments::hash_bundle_txid_empty(value_pool, tx_version)
414                    .expect("empty Orchard bundle txid commitment is valid for its tx format")
415            })
416            .as_bytes(),
417    )
418    .unwrap();
419
420    h.finalize()
421}
422
423pub(crate) fn to_hash_v6(
424    consensus_branch_id: BranchId,
425    header_digest: Blake2bHash,
426    transparent_digest: Blake2bHash,
427    sapling_digest: Option<Blake2bHash>,
428    orchard_digest: Option<Blake2bHash>,
429    ironwood_digest: Option<Blake2bHash>,
430) -> Blake2bHash {
431    let mut personal = [0; 16];
432    personal[..12].copy_from_slice(ZCASH_TX_PERSONALIZATION_PREFIX);
433    (&mut personal[12..])
434        .write_u32_le(consensus_branch_id.into())
435        .unwrap();
436
437    let mut h = hasher(&personal);
438    h.write_all(header_digest.as_bytes()).unwrap();
439    h.write_all(transparent_digest.as_bytes()).unwrap();
440    h.write_all(
441        sapling_digest
442            .unwrap_or_else(hash_sapling_txid_empty)
443            .as_bytes(),
444    )
445    .unwrap();
446    h.write_all(
447        orchard_digest
448            .unwrap_or_else(|| {
449                let (value_pool, tx_version) = orchard_commitment_domain(TxVersion::V6);
450                orchard::commitments::hash_bundle_txid_empty(value_pool, tx_version)
451                    .expect("empty Orchard bundle txid commitment is valid for its tx format")
452            })
453            .as_bytes(),
454    )
455    .unwrap();
456    h.write_all(
457        ironwood_digest
458            .unwrap_or_else(|| {
459                let (value_pool, tx_version) = ironwood_v6_domain();
460                orchard::commitments::hash_bundle_txid_empty(value_pool, tx_version)
461                    .expect("empty Ironwood bundle txid commitment is valid")
462            })
463            .as_bytes(),
464    )
465    .unwrap();
466
467    h.finalize()
468}
469
470/// Combines transaction component digests into a transaction ID.
471///
472/// Returns `None` if `txversion` is incompatible with `digests`.
473///
474/// V6 and later transactions include the Ironwood bundle digest as a separate
475/// Orchard-shaped digest using Ironwood personalization. If any shielded bundle digest is
476/// absent, this substitutes the protocol-defined empty bundle digest for that pool.
477pub fn to_txid(
478    txversion: TxVersion,
479    consensus_branch_id: BranchId,
480    digests: &Zip244Digests<Blake2bHash>,
481) -> Option<TxId> {
482    match txversion {
483        // These versions cannot produce a txid just from digests, because they use
484        // SHA-256d over the entire tx encoding which is unavailable here.
485        TxVersion::Sprout(_) | TxVersion::V3 | TxVersion::V4 => return None,
486        // These versions are compatible with `Zip244Digests`.
487        TxVersion::V5 | TxVersion::V6 => (),
488        #[cfg(zcash_unstable = "nutachyon")]
489        TxVersion::V7 => (),
490    }
491
492    let txid_digest = if txversion.has_ironwood() {
493        to_hash_v6(
494            consensus_branch_id,
495            digests.header_digest,
496            hash_transparent_txid_data(digests.transparent_digests.as_ref()),
497            digests.sapling_digest,
498            digests.orchard_digest,
499            digests.ironwood_digest,
500        )
501    } else {
502        to_hash(
503            txversion,
504            consensus_branch_id,
505            digests.header_digest,
506            hash_transparent_txid_data(digests.transparent_digests.as_ref()),
507            digests.sapling_digest,
508            digests.orchard_digest,
509        )
510    };
511
512    Some(TxId::from_bytes(
513        <[u8; 32]>::try_from(txid_digest.as_bytes()).unwrap(),
514    ))
515}
516
517/// Digester which constructs a digest of only the witness data.
518/// This does not internally commit to the txid, so if that is
519/// desired it should be done using the result of this digest
520/// function.
521pub struct BlockTxCommitmentDigester;
522
523impl TransactionDigest<Authorized> for BlockTxCommitmentDigester {
524    /// We use the header digest to pass the transaction version and consensus
525    /// branch ID into where they need to be used for personalization string
526    /// construction.
527    type HeaderDigest = (TxVersion, BranchId);
528    type TransparentDigest = Blake2bHash;
529    type SaplingDigest = Blake2bHash;
530    type OrchardDigest = Blake2bHash;
531    type IronwoodDigest = Blake2bHash;
532
533    type Digest = Blake2bHash;
534
535    fn digest_header(
536        &self,
537        _version: TxVersion,
538        consensus_branch_id: BranchId,
539        _lock_time: u32,
540        _expiry_height: BlockHeight,
541    ) -> Self::HeaderDigest {
542        (_version, consensus_branch_id)
543    }
544
545    fn digest_transparent(
546        &self,
547        transparent_bundle: Option<&transparent::Bundle<transparent::Authorized, Zatoshis>>,
548    ) -> Blake2bHash {
549        let mut h = hasher(ZCASH_TRANSPARENT_SCRIPTS_HASH_PERSONALIZATION);
550        if let Some(bundle) = transparent_bundle {
551            for txin in &bundle.vin {
552                write_script(&mut h, txin.script_sig()).unwrap();
553            }
554        }
555        h.finalize()
556    }
557
558    fn digest_sapling(
559        &self,
560        version: TxVersion,
561        sapling_bundle: Option<&sapling::Bundle<sapling::bundle::Authorized, ZatBalance>>,
562    ) -> Blake2bHash {
563        let mut h = hasher(sapling_auth_personalization(version));
564        if let Some(bundle) = sapling_bundle {
565            for spend in bundle.shielded_spends() {
566                h.write_all(spend.zkproof()).unwrap();
567            }
568
569            for spend in bundle.shielded_spends() {
570                h.write_all(&<[u8; 64]>::from(*spend.spend_auth_sig()))
571                    .unwrap();
572            }
573
574            for output in bundle.shielded_outputs() {
575                h.write_all(output.zkproof()).unwrap();
576            }
577
578            h.write_all(&<[u8; 64]>::from(bundle.authorization().binding_sig))
579                .unwrap();
580
581            if sapling_auth_includes_anchor(version) && !bundle.shielded_spends().is_empty() {
582                h.write_all(bundle.shielded_spends()[0].anchor().to_repr().as_ref())
583                    .unwrap();
584            }
585        }
586        h.finalize()
587    }
588
589    fn digest_orchard(
590        &self,
591        version: TxVersion,
592        orchard_bundle: Option<&orchard::Bundle<orchard::Authorized, ZatBalance>>,
593    ) -> Self::OrchardDigest {
594        let (value_pool, tx_version) = orchard_commitment_domain(version);
595        orchard_bundle.map_or_else(
596            || {
597                orchard::commitments::hash_bundle_auth_empty(value_pool, tx_version)
598                    .expect("empty Orchard bundle auth commitment is valid for its tx format")
599            },
600            |b| {
601                b.authorizing_commitment(tx_version)
602                    .expect("Orchard bundle flags must be representable in their tx format")
603                    .0
604            },
605        )
606    }
607
608    fn digest_ironwood(
609        &self,
610        ironwood_bundle: Option<&orchard::Bundle<orchard::Authorized, ZatBalance>>,
611    ) -> Self::IronwoodDigest {
612        let (value_pool, tx_version) = ironwood_v6_domain();
613        ironwood_bundle.map_or_else(
614            || {
615                orchard::commitments::hash_bundle_auth_empty(value_pool, tx_version)
616                    .expect("empty Ironwood bundle auth commitment is valid")
617            },
618            |b| {
619                b.authorizing_commitment(tx_version)
620                    .expect("Ironwood bundle flags must be representable")
621                    .0
622            },
623        )
624    }
625
626    fn combine(
627        &self,
628        tx_context: Self::HeaderDigest,
629        transparent_digest: Self::TransparentDigest,
630        sapling_digest: Self::SaplingDigest,
631        orchard_digest: Self::OrchardDigest,
632        ironwood_digest: Self::IronwoodDigest,
633    ) -> Self::Digest {
634        let (_txversion, consensus_branch_id) = tx_context;
635        let mut personal = [0; 16];
636        personal[..12].copy_from_slice(ZCASH_AUTH_PERSONALIZATION_PREFIX);
637        (&mut personal[12..])
638            .write_u32_le(consensus_branch_id.into())
639            .unwrap();
640
641        let mut h = hasher(&personal);
642        h.write_all(transparent_digest.as_bytes()).unwrap();
643        h.write_all(sapling_digest.as_bytes()).unwrap();
644        h.write_all(orchard_digest.as_bytes()).unwrap();
645
646        if _txversion.has_ironwood() {
647            h.write_all(ironwood_digest.as_bytes()).unwrap();
648        }
649
650        h.finalize()
651    }
652}