zebra-chain 7.0.0

Core Zcash data structures
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
//! Contains code that interfaces with the zcash_primitives crate from
//! librustzcash.

use std::{io, ops::Deref, sync::Arc};

use zcash_primitives::transaction::{self as zp_tx, TxDigests};
use zcash_protocol::value::{BalanceError, ZatBalance, Zatoshis};
use zcash_script::script;

use crate::{
    amount::{Amount, NonNegative},
    parameters::NetworkUpgrade,
    serialization::ZcashSerialize,
    transaction::{AuthDigest, HashType, SigHash, Transaction},
    transparent::{self, Script},
    Error,
};

// TODO: move copied and modified code to a separate module.
//
// Used by boilerplate code below.

#[derive(Clone, Debug)]
struct TransparentAuth {
    all_prev_outputs: Arc<Vec<transparent::Output>>,
}

impl zcash_transparent::bundle::Authorization for TransparentAuth {
    type ScriptSig = zcash_transparent::address::Script;
}

// In this block we convert our Output to a librustzcash to TxOut.
// (We could do the serialize/deserialize route but it's simple enough to convert manually)
impl zcash_transparent::sighash::TransparentAuthorizingContext for TransparentAuth {
    fn input_amounts(&self) -> Vec<Zatoshis> {
        self.all_prev_outputs
            .iter()
            .map(|prevout| {
                prevout
                    .value
                    .try_into()
                    .expect("will not fail since it was previously validated")
            })
            .collect()
    }

    fn input_scriptpubkeys(&self) -> Vec<zcash_transparent::address::Script> {
        self.all_prev_outputs
            .iter()
            .map(|prevout| {
                zcash_transparent::address::Script(script::Code(
                    prevout.lock_script.as_raw_bytes().into(),
                ))
            })
            .collect()
    }
}

// Boilerplate mostly copied from `zcash/src/rust/src/transaction_ffi.rs` which is required
// to compute sighash.
// TODO: remove/change if they improve the API to not require this.

struct MapTransparent {
    auth: TransparentAuth,
}

impl zcash_transparent::bundle::MapAuth<zcash_transparent::bundle::Authorized, TransparentAuth>
    for MapTransparent
{
    fn map_script_sig(
        &self,
        s: <zcash_transparent::bundle::Authorized as zcash_transparent::bundle::Authorization>::ScriptSig,
    ) -> <TransparentAuth as zcash_transparent::bundle::Authorization>::ScriptSig {
        s
    }

    fn map_authorization(&self, _: zcash_transparent::bundle::Authorized) -> TransparentAuth {
        // TODO: This map should consume self, so we can move self.auth
        self.auth.clone()
    }
}

struct IdentityMap;

impl
    zp_tx::components::sapling::MapAuth<
        sapling_crypto::bundle::Authorized,
        sapling_crypto::bundle::Authorized,
    > for IdentityMap
{
    fn map_spend_proof(
        &mut self,
        p: <sapling_crypto::bundle::Authorized as sapling_crypto::bundle::Authorization>::SpendProof,
    ) -> <sapling_crypto::bundle::Authorized as sapling_crypto::bundle::Authorization>::SpendProof
    {
        p
    }

    fn map_output_proof(
        &mut self,
        p: <sapling_crypto::bundle::Authorized as sapling_crypto::bundle::Authorization>::OutputProof,
    ) -> <sapling_crypto::bundle::Authorized as sapling_crypto::bundle::Authorization>::OutputProof
    {
        p
    }

    fn map_auth_sig(
        &mut self,
        s: <sapling_crypto::bundle::Authorized as sapling_crypto::bundle::Authorization>::AuthSig,
    ) -> <sapling_crypto::bundle::Authorized as sapling_crypto::bundle::Authorization>::AuthSig
    {
        s
    }

    fn map_authorization(
        &mut self,
        a: sapling_crypto::bundle::Authorized,
    ) -> sapling_crypto::bundle::Authorized {
        a
    }
}

impl zp_tx::components::orchard::MapAuth<orchard::bundle::Authorized, orchard::bundle::Authorized>
    for IdentityMap
{
    fn map_spend_auth(
        &self,
        s: <orchard::bundle::Authorized as orchard::bundle::Authorization>::SpendAuth,
    ) -> <orchard::bundle::Authorized as orchard::bundle::Authorization>::SpendAuth {
        s
    }

    fn map_authorization(&self, a: orchard::bundle::Authorized) -> orchard::bundle::Authorized {
        a
    }
}

#[derive(Debug)]
struct PrecomputedAuth {}

impl zp_tx::Authorization for PrecomputedAuth {
    type TransparentAuth = TransparentAuth;
    type SaplingAuth = sapling_crypto::bundle::Authorized;
    type OrchardAuth = orchard::bundle::Authorized;

    #[cfg(zcash_unstable = "zfuture")]
    type TzeAuth = zp_tx::components::tze::Authorized;
}

// End of (mostly) copied code

/// Convert a Zebra transparent::Output into a librustzcash one.
impl TryFrom<&transparent::Output> for zcash_transparent::bundle::TxOut {
    type Error = io::Error;

    #[allow(clippy::unwrap_in_result)]
    fn try_from(output: &transparent::Output) -> Result<Self, Self::Error> {
        let serialized_output_bytes = output
            .zcash_serialize_to_vec()
            .expect("zcash_primitives and Zebra transparent output formats must be compatible");

        zcash_transparent::bundle::TxOut::read(&mut serialized_output_bytes.as_slice())
    }
}

/// Convert a Zebra transparent::Output into a librustzcash one.
impl TryFrom<transparent::Output> for zcash_transparent::bundle::TxOut {
    type Error = io::Error;

    // The borrow is actually needed to use TryFrom<&transparent::Output>
    #[allow(clippy::needless_borrow)]
    fn try_from(output: transparent::Output) -> Result<Self, Self::Error> {
        (&output).try_into()
    }
}

/// Convert a Zebra non-negative Amount into a librustzcash one.
impl TryFrom<Amount<NonNegative>> for zcash_protocol::value::Zatoshis {
    type Error = BalanceError;

    fn try_from(amount: Amount<NonNegative>) -> Result<Self, Self::Error> {
        zcash_protocol::value::Zatoshis::from_nonnegative_i64(amount.into())
    }
}

impl TryFrom<Amount> for ZatBalance {
    type Error = BalanceError;

    fn try_from(amount: Amount) -> Result<Self, Self::Error> {
        ZatBalance::from_i64(amount.into())
    }
}

/// Convert a Zebra Script into a librustzcash one.
impl From<&Script> for zcash_transparent::address::Script {
    fn from(script: &Script) -> Self {
        zcash_transparent::address::Script(script::Code(script.as_raw_bytes().to_vec()))
    }
}

/// Convert a Zebra Script into a librustzcash one.
impl From<Script> for zcash_transparent::address::Script {
    // The borrow is actually needed to use From<&Script>
    #[allow(clippy::needless_borrow)]
    fn from(script: Script) -> Self {
        (&script).into()
    }
}

/// Precomputed data used for sighash or txid computation.
#[derive(Debug)]
pub(crate) struct PrecomputedTxData {
    tx_data: zp_tx::TransactionData<PrecomputedAuth>,
    txid_parts: TxDigests<blake2b_simd::Hash>,
    all_previous_outputs: Arc<Vec<transparent::Output>>,
}

impl PrecomputedTxData {
    /// Computes the data used for sighash or txid computation.
    ///
    /// # Inputs
    ///
    /// - `tx`: the relevant transaction.
    /// - `nu`: the network upgrade to which the transaction belongs.
    /// - `all_previous_outputs`: the transparent Output matching each transparent input in `tx`.
    ///
    /// # Errors
    ///
    /// - If `tx` can't be converted to its `librustzcash` equivalent.
    /// - If `nu` doesn't contain a consensus branch id convertible to its `librustzcash`
    ///   equivalent.
    ///
    /// # Consensus
    ///
    /// > [NU5 only, pre-NU6] All transactions MUST use the NU5 consensus branch ID `0xF919A198` as
    /// > defined in [ZIP-252].
    ///
    /// > [NU6 only] All transactions MUST use the NU6 consensus branch ID `0xC8E71055` as defined
    /// > in  [ZIP-253].
    ///
    /// # Notes
    ///
    /// The check that ensures compliance with the two consensus rules stated above takes place in
    /// the [`Transaction::to_librustzcash`] method. If the check fails, the tx can't be converted
    /// to its `librustzcash` equivalent, which leads to an error. The check relies on the passed
    /// `nu` parameter, which uniquely represents a consensus branch id and can, therefore, be used
    /// as an equivalent to a consensus branch id. The desired `nu` is set either by the script or
    /// tx verifier in `zebra-consensus`.
    ///
    /// [ZIP-252]: <https://zips.z.cash/zip-0252>
    /// [ZIP-253]: <https://zips.z.cash/zip-0253>
    pub(crate) fn new(
        tx: &Transaction,
        nu: NetworkUpgrade,
        all_previous_outputs: Arc<Vec<transparent::Output>>,
    ) -> Result<PrecomputedTxData, Error> {
        let tx = tx.to_librustzcash(nu)?;

        let txid_parts = tx.deref().digest(zp_tx::txid::TxIdDigester);

        let f_transparent = MapTransparent {
            auth: TransparentAuth {
                all_prev_outputs: all_previous_outputs.clone(),
            },
        };

        let tx_data: zp_tx::TransactionData<PrecomputedAuth> = tx.into_data().map_authorization(
            f_transparent,
            IdentityMap,
            IdentityMap,
            #[cfg(zcash_unstable = "zfuture")]
            (),
        );

        Ok(PrecomputedTxData {
            tx_data,
            txid_parts,
            all_previous_outputs,
        })
    }

    /// Returns the Orchard bundle in `tx_data`.
    pub fn orchard_bundle(
        &self,
    ) -> Option<orchard::bundle::Bundle<orchard::bundle::Authorized, ZatBalance>> {
        self.tx_data.orchard_bundle().cloned()
    }

    /// Returns the Sapling bundle in `tx_data`.
    pub fn sapling_bundle(
        &self,
    ) -> Option<sapling_crypto::Bundle<sapling_crypto::bundle::Authorized, ZatBalance>> {
        self.tx_data.sapling_bundle().cloned()
    }
}

/// Internal error type returned by [`sighash_inner`] when a sighash request
/// violates one of the documented preconditions of [`sighash`] or
/// [`sighash_v4_raw`].
///
/// Public callers (`SigHasher::sighash`, `SigHasher::sighash_v4_raw`) document
/// these conditions as panics, so they unwrap the result at the public
/// boundary. Keeping the internal code `Result`-shaped avoids spreading
/// `.expect()` calls across multiple locations whose justifications all
/// depend on the same caller invariants.
#[derive(Debug)]
enum SighashError {
    /// Caller passed an `input_index` greater than or equal to the number of
    /// transparent inputs the caller declared in `all_previous_outputs`.
    InputIndexOutOfBounds {
        input_index: usize,
        input_count: usize,
    },
    /// Caller asked for a transparent sighash on a transaction that
    /// `zcash_primitives` parsed without a transparent bundle. This contradicts
    /// the precondition that `Some((input_index, _))` is only passed for
    /// transactions with at least one transparent input.
    NoTransparentBundle,
    /// `input_index` is within bounds for `all_previous_outputs` but out of
    /// bounds for the transparent bundle's `vin` returned by
    /// `zcash_primitives`. Reaching this branch indicates a serialize /
    /// deserialize round-trip inconsistency between Zebra's `Transaction` and
    /// the parsed `zcash_primitives::Transaction`, which would be a bug in
    /// either crate.
    BundleInputCountMismatch {
        input_index: usize,
        bundle_vin_len: usize,
        all_prev_outputs_len: usize,
    },
    /// The previous output's value could not be converted to `Zatoshis`.
    /// Reaching this branch means the caller passed an output whose amount
    /// was not validated by the consensus rules before sighash computation.
    InvalidPreviousOutputAmount,
}

impl std::fmt::Display for SighashError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InputIndexOutOfBounds {
                input_index,
                input_count,
            } => write!(
                f,
                "input_index {input_index} is out of bounds (transaction has \
                 {input_count} transparent inputs)"
            ),
            Self::NoTransparentBundle => f.write_str(
                "transparent sighash requested for a transaction with no \
                 transparent bundle (vin and vout both empty)",
            ),
            Self::BundleInputCountMismatch {
                input_index,
                bundle_vin_len,
                all_prev_outputs_len,
            } => write!(
                f,
                "input_index {input_index} valid for all_previous_outputs (len \
                 {all_prev_outputs_len}) but out of bounds for the parsed \
                 transparent bundle (vin len {bundle_vin_len}); this indicates \
                 a serialize/deserialize round-trip inconsistency"
            ),
            Self::InvalidPreviousOutputAmount => f.write_str(
                "previous output amount could not be converted to Zatoshis; \
                 the amount should have been validated before sighash \
                 computation",
            ),
        }
    }
}

impl std::error::Error for SighashError {}

/// Compute a signature hash using librustzcash.
///
/// # Inputs
///
/// - `precomputed_tx_data`: precomputed data for the transaction whose
///   signature hash is being computed.
/// - `hash_type`: the type of hash (SIGHASH) being used.
/// - `input_index_script_code`: a tuple with the index of the transparent Input
///   for which we are producing a sighash and the respective script code being
///   validated, or None if it's a shielded input.
///
/// # Panics
///
/// - if `input_index_script_code` is `Some((input_index, _))` and `input_index`
///   is out of bounds for `precomputed_tx_data.all_previous_outputs`. The
///   public callers in `zebra-chain` document this as a precondition.
/// - if the previous output at `input_index` has a value that cannot be
///   converted to `Zatoshis`. Output values are validated before sighash
///   computation, so this branch is unreachable in practice.
pub(crate) fn sighash(
    precomputed_tx_data: &PrecomputedTxData,
    hash_type: HashType,
    input_index_script_code: Option<(usize, Vec<u8>)>,
) -> SigHash {
    sighash_inner(
        precomputed_tx_data,
        hash_type.try_into().expect("hash type should be canonical"),
        input_index_script_code,
    )
    .expect(
        "sighash precondition violated: callers must pass an in-bounds \
         input_index when computing a transparent sighash, and the transaction \
         must contain the transparent input being signed",
    )
}

/// Compute a pre-V5 (V4) signature hash using the raw `hash_type` byte.
///
/// `zcashd` serializes the full raw byte into the V4 sighash preimage and only
/// masks with `SIGHASH_MASK` (0x1f) for selection logic. Callers handling V5+
/// transactions must use [`sighash`] instead so ZIP-244 strictness is enforced.
///
/// # Panics
///
/// Same preconditions as [`sighash`].
pub(crate) fn sighash_v4_raw(
    precomputed_tx_data: &PrecomputedTxData,
    raw_hash_type: u8,
    input_index_script_code: Option<(usize, Vec<u8>)>,
) -> SigHash {
    sighash_inner(
        precomputed_tx_data,
        zcash_transparent::sighash::SighashType::from_raw(raw_hash_type),
        input_index_script_code,
    )
    .expect(
        "sighash precondition violated: callers must pass an in-bounds \
         input_index when computing a transparent sighash, and the transaction \
         must contain the transparent input being signed",
    )
}

/// Internal sighash computation that surfaces precondition violations through
/// `Result` instead of spreading `.expect()` calls across multiple sites.
///
/// All callers in `zebra-chain` unwrap the returned `Result` at the public
/// boundary, but funnelling the error variants through one type makes it
/// obvious which preconditions each call site relies on.
fn sighash_inner(
    precomputed_tx_data: &PrecomputedTxData,
    sighash_type: zcash_transparent::sighash::SighashType,
    input_index_script_code: Option<(usize, Vec<u8>)>,
) -> Result<SigHash, SighashError> {
    let lock_script: zcash_transparent::address::Script;
    let unlock_script: zcash_transparent::address::Script;
    let signable_input = match input_index_script_code {
        Some((input_index, script_code)) => {
            // The `all_previous_outputs` vector is supplied by the caller in
            // 1:1 correspondence with `tx.inputs()`, and the transparent
            // bundle was produced by round-tripping the same transaction
            // bytes through `zcash_primitives::Transaction::read`. Both have
            // length equal to `tx.inputs().len()`, so an out-of-bounds index
            // is a caller error that should be reported once here.
            let all_prev_outputs_len = precomputed_tx_data.all_previous_outputs.len();
            let output = precomputed_tx_data
                .all_previous_outputs
                .get(input_index)
                .ok_or(SighashError::InputIndexOutOfBounds {
                    input_index,
                    input_count: all_prev_outputs_len,
                })?;
            // `zcash_primitives::Transaction::read` returns
            // `transparent_bundle = None` only when both `vin` and `vout` are
            // empty. The caller only reaches this branch with `Some(_)` when
            // the transaction has at least one transparent input, so reaching
            // a `None` here means the caller violated the precondition or
            // librustzcash changed its behaviour.
            let bundle = precomputed_tx_data
                .tx_data
                .transparent_bundle()
                .ok_or(SighashError::NoTransparentBundle)?;
            lock_script = output.lock_script.clone().into();
            unlock_script = zcash_transparent::address::Script(script::Code(script_code));
            let value = output
                .value
                .try_into()
                .map_err(|_| SighashError::InvalidPreviousOutputAmount)?;
            let from_parts = zcash_transparent::sighash::SignableInput::from_parts(
                bundle,
                sighash_type,
                input_index,
                &unlock_script,
                &lock_script,
                value,
            )
            .map_err(|_| SighashError::BundleInputCountMismatch {
                input_index,
                bundle_vin_len: bundle.vin.len(),
                all_prev_outputs_len,
            })?;
            zp_tx::sighash::SignableInput::Transparent(from_parts)
        }
        None => zp_tx::sighash::SignableInput::Shielded,
    };

    Ok(SigHash(
        *zp_tx::sighash::signature_hash(
            &precomputed_tx_data.tx_data,
            &signable_input,
            &precomputed_tx_data.txid_parts,
        )
        .as_ref(),
    ))
}

/// Compute the authorizing data commitment of this transaction as specified in [ZIP-244].
///
/// # Panics
///
/// If passed a pre-v5 transaction.
///
/// [ZIP-244]: https://zips.z.cash/zip-0244
pub(crate) fn auth_digest(tx: &Transaction) -> AuthDigest {
    let nu = tx.network_upgrade().expect("V5 tx has a network upgrade");

    AuthDigest(
        tx.to_librustzcash(nu)
            .expect("V5 tx is convertible to its `zcash_params` equivalent")
            .auth_commitment()
            .as_ref()
            .try_into()
            .expect("digest has the correct size"),
    )
}