1use std::{io, ops::Deref, sync::Arc};
5
6use zcash_primitives::transaction::{self as zp_tx, sighash::PrecomputedSighashData};
7use zcash_protocol::value::{BalanceError, ZatBalance, Zatoshis};
8use zcash_script::script;
9
10use crate::{
11 amount::{Amount, NonNegative},
12 serialization::ZcashSerialize,
13 transaction::{HashType, SigHash},
14 transparent::{self, Script},
15 Error,
16};
17
18use crate::{parameters::NetworkUpgrade, transaction::Transaction};
19
20#[derive(Clone, Debug)]
25struct TransparentAuth {
26 all_prev_outputs: Arc<Vec<transparent::Output>>,
27}
28
29impl zcash_transparent::bundle::Authorization for TransparentAuth {
30 type ScriptSig = zcash_transparent::address::Script;
31}
32
33impl zcash_transparent::sighash::TransparentAuthorizingContext for TransparentAuth {
36 fn input_amounts(&self) -> Vec<Zatoshis> {
37 self.all_prev_outputs
38 .iter()
39 .map(|prevout| {
40 prevout
41 .value
42 .try_into()
43 .expect("will not fail since it was previously validated")
44 })
45 .collect()
46 }
47
48 fn input_scriptpubkeys(&self) -> Vec<zcash_transparent::address::Script> {
49 self.all_prev_outputs
50 .iter()
51 .map(|prevout| {
52 zcash_transparent::address::Script(script::Code(
53 prevout.lock_script.as_raw_bytes().into(),
54 ))
55 })
56 .collect()
57 }
58}
59
60struct MapTransparent {
65 auth: TransparentAuth,
66}
67
68impl zcash_transparent::bundle::MapAuth<zcash_transparent::bundle::Authorized, TransparentAuth>
69 for MapTransparent
70{
71 fn map_script_sig(
72 &self,
73 s: <zcash_transparent::bundle::Authorized as zcash_transparent::bundle::Authorization>::ScriptSig,
74 ) -> <TransparentAuth as zcash_transparent::bundle::Authorization>::ScriptSig {
75 s
76 }
77
78 fn map_authorization(&self, _: zcash_transparent::bundle::Authorized) -> TransparentAuth {
79 self.auth.clone()
81 }
82}
83
84struct IdentityMap;
85
86impl
87 zp_tx::components::sapling::MapAuth<
88 sapling_crypto::bundle::Authorized,
89 sapling_crypto::bundle::Authorized,
90 > for IdentityMap
91{
92 fn map_spend_proof(
93 &mut self,
94 p: <sapling_crypto::bundle::Authorized as sapling_crypto::bundle::Authorization>::SpendProof,
95 ) -> <sapling_crypto::bundle::Authorized as sapling_crypto::bundle::Authorization>::SpendProof
96 {
97 p
98 }
99
100 fn map_output_proof(
101 &mut self,
102 p: <sapling_crypto::bundle::Authorized as sapling_crypto::bundle::Authorization>::OutputProof,
103 ) -> <sapling_crypto::bundle::Authorized as sapling_crypto::bundle::Authorization>::OutputProof
104 {
105 p
106 }
107
108 fn map_auth_sig(
109 &mut self,
110 s: <sapling_crypto::bundle::Authorized as sapling_crypto::bundle::Authorization>::AuthSig,
111 ) -> <sapling_crypto::bundle::Authorized as sapling_crypto::bundle::Authorization>::AuthSig
112 {
113 s
114 }
115
116 fn map_authorization(
117 &mut self,
118 a: sapling_crypto::bundle::Authorized,
119 ) -> sapling_crypto::bundle::Authorized {
120 a
121 }
122}
123
124impl zp_tx::components::orchard::MapAuth<orchard::bundle::Authorized, orchard::bundle::Authorized>
125 for IdentityMap
126{
127 fn map_spend_auth(
128 &self,
129 s: <orchard::bundle::Authorized as orchard::bundle::Authorization>::SpendAuth,
130 ) -> <orchard::bundle::Authorized as orchard::bundle::Authorization>::SpendAuth {
131 s
132 }
133
134 fn map_authorization(&self, a: orchard::bundle::Authorized) -> orchard::bundle::Authorized {
135 a
136 }
137}
138
139#[derive(Debug)]
140struct PrecomputedAuth {}
141
142impl zp_tx::Authorization for PrecomputedAuth {
143 type TransparentAuth = TransparentAuth;
144 type SaplingAuth = sapling_crypto::bundle::Authorized;
145 type OrchardAuth = orchard::bundle::Authorized;
146
147 #[cfg(zcash_unstable = "zfuture")]
148 type TzeAuth = zp_tx::components::tze::Authorized;
149}
150
151impl TryFrom<&transparent::Output> for zcash_transparent::bundle::TxOut {
155 type Error = io::Error;
156
157 #[allow(clippy::unwrap_in_result)]
158 fn try_from(output: &transparent::Output) -> Result<Self, Self::Error> {
159 let serialized_output_bytes = output
160 .zcash_serialize_to_vec()
161 .expect("zcash_primitives and Zebra transparent output formats must be compatible");
162
163 zcash_transparent::bundle::TxOut::read(&mut serialized_output_bytes.as_slice())
164 }
165}
166
167impl TryFrom<transparent::Output> for zcash_transparent::bundle::TxOut {
169 type Error = io::Error;
170
171 #[allow(clippy::needless_borrow)]
173 fn try_from(output: transparent::Output) -> Result<Self, Self::Error> {
174 (&output).try_into()
175 }
176}
177
178impl TryFrom<Amount<NonNegative>> for zcash_protocol::value::Zatoshis {
180 type Error = BalanceError;
181
182 fn try_from(amount: Amount<NonNegative>) -> Result<Self, Self::Error> {
183 zcash_protocol::value::Zatoshis::from_nonnegative_i64(amount.into())
184 }
185}
186
187impl TryFrom<Amount> for ZatBalance {
188 type Error = BalanceError;
189
190 fn try_from(amount: Amount) -> Result<Self, Self::Error> {
191 ZatBalance::from_i64(amount.into())
192 }
193}
194
195impl From<&Script> for zcash_transparent::address::Script {
197 fn from(script: &Script) -> Self {
198 zcash_transparent::address::Script(script::Code(script.as_raw_bytes().to_vec()))
199 }
200}
201
202impl From<Script> for zcash_transparent::address::Script {
204 #[allow(clippy::needless_borrow)]
206 fn from(script: Script) -> Self {
207 (&script).into()
208 }
209}
210
211#[derive(Debug)]
213pub(crate) struct PrecomputedTxData {
214 sighash_data: PrecomputedSighashData<PrecomputedAuth>,
219 all_previous_outputs: Arc<Vec<transparent::Output>>,
220}
221
222impl PrecomputedTxData {
223 pub(crate) fn new(
229 tx: &Transaction,
230 nu: NetworkUpgrade,
231 all_previous_outputs: Arc<Vec<transparent::Output>>,
232 ) -> Result<PrecomputedTxData, Error> {
233 let branch_id = nu
234 .branch_id()
235 .and_then(|cbid| zcash_protocol::consensus::BranchId::try_from(cbid).ok())
236 .ok_or(Error::InvalidConsensusBranchId)?;
237
238 let tx_branch_id = tx.inner().deref().consensus_branch_id();
241 if tx.version() >= 5 && tx_branch_id != branch_id {
242 return Err(Error::InvalidConsensusBranchId);
243 }
244
245 Self::from_transaction_with_branch_id(tx, branch_id, all_previous_outputs)
246 }
247
248 fn from_transaction_with_branch_id(
253 tx: &crate::transaction::Transaction,
254 branch_id: zcash_protocol::consensus::BranchId,
255 all_previous_outputs: Arc<Vec<transparent::Output>>,
256 ) -> Result<PrecomputedTxData, Error> {
257 let inner = tx.inner();
258
259 let data = inner.clone().into_data();
267 let data_with_branch_id = crate::transaction::compat::transaction_data_from_parts(
268 data.version(),
269 branch_id,
270 data.lock_time(),
271 data.expiry_height(),
272 data.transparent_bundle().cloned(),
273 data.sprout_bundle().cloned(),
274 data.sapling_bundle().cloned(),
275 data.orchard_bundle().cloned(),
276 data.ironwood_bundle().cloned(),
277 );
278
279 let tx_data: zp_tx::TransactionData<PrecomputedAuth> = data_with_branch_id
280 .map_authorization(
281 MapTransparent {
282 auth: TransparentAuth {
283 all_prev_outputs: all_previous_outputs.clone(),
284 },
285 },
286 IdentityMap,
287 IdentityMap,
288 #[cfg(zcash_unstable = "zfuture")]
289 (),
290 );
291
292 Ok(PrecomputedTxData {
293 sighash_data: PrecomputedSighashData::new(tx_data),
294 all_previous_outputs,
295 })
296 }
297
298 pub fn orchard_bundle(
300 &self,
301 ) -> Option<orchard::bundle::Bundle<orchard::bundle::Authorized, ZatBalance>> {
302 self.sighash_data.tx().orchard_bundle().cloned()
303 }
304
305 pub fn ironwood_bundle(
310 &self,
311 ) -> Option<orchard::bundle::Bundle<orchard::bundle::Authorized, ZatBalance>> {
312 self.sighash_data.tx().ironwood_bundle().cloned()
313 }
314
315 pub fn sapling_bundle(
317 &self,
318 ) -> Option<sapling_crypto::Bundle<sapling_crypto::bundle::Authorized, ZatBalance>> {
319 self.sighash_data.tx().sapling_bundle().cloned()
320 }
321}
322
323#[derive(Debug)]
333enum SighashError {
334 InputIndexOutOfBounds {
337 input_index: usize,
338 input_count: usize,
339 },
340 NoTransparentBundle,
345 BundleInputCountMismatch {
352 input_index: usize,
353 bundle_vin_len: usize,
354 all_prev_outputs_len: usize,
355 },
356 InvalidPreviousOutputAmount,
360}
361
362impl std::fmt::Display for SighashError {
363 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
364 match self {
365 Self::InputIndexOutOfBounds {
366 input_index,
367 input_count,
368 } => write!(
369 f,
370 "input_index {input_index} is out of bounds (transaction has \
371 {input_count} transparent inputs)"
372 ),
373 Self::NoTransparentBundle => f.write_str(
374 "transparent sighash requested for a transaction with no \
375 transparent bundle (vin and vout both empty)",
376 ),
377 Self::BundleInputCountMismatch {
378 input_index,
379 bundle_vin_len,
380 all_prev_outputs_len,
381 } => write!(
382 f,
383 "input_index {input_index} valid for all_previous_outputs (len \
384 {all_prev_outputs_len}) but out of bounds for the parsed \
385 transparent bundle (vin len {bundle_vin_len}); this indicates \
386 a serialize/deserialize round-trip inconsistency"
387 ),
388 Self::InvalidPreviousOutputAmount => f.write_str(
389 "previous output amount could not be converted to Zatoshis; \
390 the amount should have been validated before sighash \
391 computation",
392 ),
393 }
394 }
395}
396
397impl std::error::Error for SighashError {}
398
399pub(crate) fn sighash(
419 precomputed_tx_data: &PrecomputedTxData,
420 hash_type: HashType,
421 input_index_script_code: Option<(usize, Vec<u8>)>,
422) -> SigHash {
423 sighash_inner(
424 precomputed_tx_data,
425 hash_type.try_into().expect("hash type should be canonical"),
426 input_index_script_code,
427 )
428 .expect(
429 "sighash precondition violated: callers must pass an in-bounds \
430 input_index when computing a transparent sighash, and the transaction \
431 must contain the transparent input being signed",
432 )
433}
434
435pub(crate) fn sighash_v4_raw(
445 precomputed_tx_data: &PrecomputedTxData,
446 raw_hash_type: u8,
447 input_index_script_code: Option<(usize, Vec<u8>)>,
448) -> SigHash {
449 sighash_inner(
450 precomputed_tx_data,
451 zcash_transparent::sighash::SighashType::from_raw(raw_hash_type),
452 input_index_script_code,
453 )
454 .expect(
455 "sighash precondition violated: callers must pass an in-bounds \
456 input_index when computing a transparent sighash, and the transaction \
457 must contain the transparent input being signed",
458 )
459}
460
461fn sighash_inner(
468 precomputed_tx_data: &PrecomputedTxData,
469 sighash_type: zcash_transparent::sighash::SighashType,
470 input_index_script_code: Option<(usize, Vec<u8>)>,
471) -> Result<SigHash, SighashError> {
472 let lock_script: zcash_transparent::address::Script;
473 let unlock_script: zcash_transparent::address::Script;
474 let signable_input = match input_index_script_code {
475 Some((input_index, script_code)) => {
476 let all_prev_outputs_len = precomputed_tx_data.all_previous_outputs.len();
483 let output = precomputed_tx_data
484 .all_previous_outputs
485 .get(input_index)
486 .ok_or(SighashError::InputIndexOutOfBounds {
487 input_index,
488 input_count: all_prev_outputs_len,
489 })?;
490 let bundle = precomputed_tx_data
497 .sighash_data
498 .tx()
499 .transparent_bundle()
500 .ok_or(SighashError::NoTransparentBundle)?;
501 lock_script = output.lock_script.clone().into();
502 unlock_script = zcash_transparent::address::Script(script::Code(script_code));
503 let value = output
504 .value
505 .try_into()
506 .map_err(|_| SighashError::InvalidPreviousOutputAmount)?;
507 let from_parts = zcash_transparent::sighash::SignableInput::from_parts(
508 bundle,
509 sighash_type,
510 input_index,
511 &unlock_script,
512 &lock_script,
513 value,
514 )
515 .map_err(|_| SighashError::BundleInputCountMismatch {
516 input_index,
517 bundle_vin_len: bundle.vin.len(),
518 all_prev_outputs_len,
519 })?;
520 zp_tx::sighash::SignableInput::Transparent(from_parts)
521 }
522 None => zp_tx::sighash::SignableInput::Shielded,
523 };
524
525 Ok(SigHash(
526 *precomputed_tx_data
527 .sighash_data
528 .signature_hash(&signable_input)
529 .as_ref(),
530 ))
531}