bitcoin/crypto/
sighash.rs

1// SPDX-License-Identifier: CC0-1.0
2
3//! Signature hash implementation (used in transaction signing).
4//!
5//! Efficient implementation of the algorithm to compute the message to be signed according to
6//! [Bip341](https://github.com/bitcoin/bips/blob/150ab6f5c3aca9da05fccc5b435e9667853407f4/bip-0341.mediawiki),
7//! [Bip143](https://github.com/bitcoin/bips/blob/99701f68a88ce33b2d0838eb84e115cef505b4c2/bip-0143.mediawiki)
8//! and legacy (before Bip143).
9//!
10//! Computing signature hashes is required to sign a transaction and this module is designed to
11//! handle its complexity efficiently. Computing these hashes is as simple as creating
12//! [`SighashCache`] and calling its methods.
13
14use core::{fmt, str};
15
16use hashes::{hash_newtype, sha256, sha256d, sha256t_hash_newtype, Hash};
17use internals::write_err;
18use io::Write;
19
20use crate::blockdata::witness::Witness;
21use crate::consensus::{encode, Encodable};
22use crate::prelude::*;
23use crate::taproot::{LeafVersion, TapLeafHash, TAPROOT_ANNEX_PREFIX};
24use crate::{transaction, Amount, Script, ScriptBuf, Sequence, Transaction, TxIn, TxOut};
25
26/// Used for signature hash for invalid use of SIGHASH_SINGLE.
27#[rustfmt::skip]
28pub(crate) const UINT256_ONE: [u8; 32] = [
29    1, 0, 0, 0, 0, 0, 0, 0,
30    0, 0, 0, 0, 0, 0, 0, 0,
31    0, 0, 0, 0, 0, 0, 0, 0,
32    0, 0, 0, 0, 0, 0, 0, 0
33];
34
35macro_rules! impl_message_from_hash {
36    ($ty:ident) => {
37        impl From<$ty> for secp256k1::Message {
38            fn from(hash: $ty) -> secp256k1::Message {
39                secp256k1::Message::from_digest(hash.to_byte_array())
40            }
41        }
42    };
43}
44
45hash_newtype! {
46    /// Hash of a transaction according to the legacy signature algorithm.
47    #[hash_newtype(forward)]
48    pub struct LegacySighash(sha256d::Hash);
49
50    /// Hash of a transaction according to the segwit version 0 signature algorithm.
51    #[hash_newtype(forward)]
52    pub struct SegwitV0Sighash(sha256d::Hash);
53}
54
55impl_message_from_hash!(LegacySighash);
56impl_message_from_hash!(SegwitV0Sighash);
57
58sha256t_hash_newtype! {
59    pub struct TapSighashTag = hash_str("TapSighash");
60
61    /// Taproot-tagged hash with tag \"TapSighash\".
62    ///
63    /// This hash type is used for computing taproot signature hash."
64    #[hash_newtype(forward)]
65    pub struct TapSighash(_);
66}
67
68impl_message_from_hash!(TapSighash);
69
70/// Efficiently calculates signature hash message for legacy, segwit and taproot inputs.
71#[derive(Debug)]
72pub struct SighashCache<T: Borrow<Transaction>> {
73    /// Access to transaction required for transaction introspection. Moreover, type
74    /// `T: Borrow<Transaction>` allows us to use borrowed and mutable borrowed types,
75    /// the latter in particular is necessary for [`SighashCache::witness_mut`].
76    tx: T,
77
78    /// Common cache for taproot and segwit inputs, `None` for legacy inputs.
79    common_cache: Option<CommonCache>,
80
81    /// Cache for segwit v0 inputs (the result of another round of sha256 on `common_cache`).
82    segwit_cache: Option<SegwitCache>,
83
84    /// Cache for taproot v1 inputs.
85    taproot_cache: Option<TaprootCache>,
86}
87
88/// Common values cached between segwit and taproot inputs.
89#[derive(Debug)]
90struct CommonCache {
91    prevouts: sha256::Hash,
92    sequences: sha256::Hash,
93
94    /// In theory `outputs` could be an `Option` since `SIGHASH_NONE` and `SIGHASH_SINGLE` do not
95    /// need it, but since `SIGHASH_ALL` is by far the most used variant we don't bother.
96    outputs: sha256::Hash,
97}
98
99/// Values cached for segwit inputs, equivalent to [`CommonCache`] plus another round of `sha256`.
100#[derive(Debug)]
101struct SegwitCache {
102    prevouts: sha256d::Hash,
103    sequences: sha256d::Hash,
104    outputs: sha256d::Hash,
105}
106
107/// Values cached for taproot inputs.
108#[derive(Debug)]
109struct TaprootCache {
110    amounts: sha256::Hash,
111    script_pubkeys: sha256::Hash,
112}
113
114/// Contains outputs of previous transactions. In the case [`TapSighashType`] variant is
115/// `SIGHASH_ANYONECANPAY`, [`Prevouts::One`] may be used.
116#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
117pub enum Prevouts<'u, T>
118where
119    T: 'u + Borrow<TxOut>,
120{
121    /// `One` variant allows provision of the single prevout needed. It's useful, for example, when
122    /// modifier `SIGHASH_ANYONECANPAY` is provided, only prevout of the current input is needed.
123    /// The first `usize` argument is the input index this [`TxOut`] is referring to.
124    One(usize, T),
125    /// When `SIGHASH_ANYONECANPAY` is not provided, or when the caller is giving all prevouts so
126    /// the same variable can be used for multiple inputs.
127    All(&'u [T]),
128}
129
130const KEY_VERSION_0: u8 = 0u8;
131
132/// Information related to the script path spending.
133///
134/// This can be hashed into a [`TapLeafHash`].
135#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
136pub struct ScriptPath<'s> {
137    script: &'s Script,
138    leaf_version: LeafVersion,
139}
140
141/// Hashtype of an input's signature, encoded in the last byte of the signature.
142/// Fixed values so they can be cast as integer types for encoding.
143#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
144pub enum TapSighashType {
145    /// 0x0: Used when not explicitly specified, defaults to [`TapSighashType::All`]
146    Default = 0x00,
147    /// 0x1: Sign all outputs.
148    All = 0x01,
149    /// 0x2: Sign no outputs --- anyone can choose the destination.
150    None = 0x02,
151    /// 0x3: Sign the output whose index matches this input's index. If none exists,
152    /// sign the hash `0000000000000000000000000000000000000000000000000000000000000001`.
153    /// (This rule is probably an unintentional C++ism, but it's consensus so we have
154    /// to follow it.)
155    Single = 0x03,
156    /// 0x81: Sign all outputs but only this input.
157    AllPlusAnyoneCanPay = 0x81,
158    /// 0x82: Sign no outputs and only this input.
159    NonePlusAnyoneCanPay = 0x82,
160    /// 0x83: Sign one output and only this input (see `Single` for what "one output" means).
161    SinglePlusAnyoneCanPay = 0x83,
162}
163#[cfg(feature = "serde")]
164crate::serde_utils::serde_string_impl!(TapSighashType, "a TapSighashType data");
165
166impl fmt::Display for TapSighashType {
167    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168        use TapSighashType::*;
169
170        let s = match self {
171            Default => "SIGHASH_DEFAULT",
172            All => "SIGHASH_ALL",
173            None => "SIGHASH_NONE",
174            Single => "SIGHASH_SINGLE",
175            AllPlusAnyoneCanPay => "SIGHASH_ALL|SIGHASH_ANYONECANPAY",
176            NonePlusAnyoneCanPay => "SIGHASH_NONE|SIGHASH_ANYONECANPAY",
177            SinglePlusAnyoneCanPay => "SIGHASH_SINGLE|SIGHASH_ANYONECANPAY",
178        };
179        f.write_str(s)
180    }
181}
182
183impl str::FromStr for TapSighashType {
184    type Err = SighashTypeParseError;
185
186    fn from_str(s: &str) -> Result<Self, Self::Err> {
187        use TapSighashType::*;
188
189        match s {
190            "SIGHASH_DEFAULT" => Ok(Default),
191            "SIGHASH_ALL" => Ok(All),
192            "SIGHASH_NONE" => Ok(None),
193            "SIGHASH_SINGLE" => Ok(Single),
194            "SIGHASH_ALL|SIGHASH_ANYONECANPAY" => Ok(AllPlusAnyoneCanPay),
195            "SIGHASH_NONE|SIGHASH_ANYONECANPAY" => Ok(NonePlusAnyoneCanPay),
196            "SIGHASH_SINGLE|SIGHASH_ANYONECANPAY" => Ok(SinglePlusAnyoneCanPay),
197            _ => Err(SighashTypeParseError { unrecognized: s.to_owned() }),
198        }
199    }
200}
201
202impl<'u, T> Prevouts<'u, T>
203where
204    T: Borrow<TxOut>,
205{
206    fn check_all(&self, tx: &Transaction) -> Result<(), PrevoutsSizeError> {
207        if let Prevouts::All(prevouts) = self {
208            if prevouts.len() != tx.input.len() {
209                return Err(PrevoutsSizeError);
210            }
211        }
212        Ok(())
213    }
214
215    fn get_all(&self) -> Result<&[T], PrevoutsKindError> {
216        match self {
217            Prevouts::All(prevouts) => Ok(*prevouts),
218            _ => Err(PrevoutsKindError),
219        }
220    }
221
222    fn get(&self, input_index: usize) -> Result<&TxOut, PrevoutsIndexError> {
223        match self {
224            Prevouts::One(index, prevout) =>
225                if input_index == *index {
226                    Ok(prevout.borrow())
227                } else {
228                    Err(PrevoutsIndexError::InvalidOneIndex)
229                },
230            Prevouts::All(prevouts) => prevouts
231                .get(input_index)
232                .map(|x| x.borrow())
233                .ok_or(PrevoutsIndexError::InvalidAllIndex),
234        }
235    }
236}
237
238/// The number of supplied prevouts differs from the number of inputs in the transaction.
239#[derive(Debug, Clone, PartialEq, Eq)]
240#[non_exhaustive]
241pub struct PrevoutsSizeError;
242
243impl fmt::Display for PrevoutsSizeError {
244    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
245        write!(f, "number of supplied prevouts differs from the number of inputs in transaction")
246    }
247}
248
249#[cfg(feature = "std")]
250impl std::error::Error for PrevoutsSizeError {
251    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { None }
252}
253
254/// A single prevout was been provided but all prevouts are needed without `ANYONECANPAY`.
255#[derive(Debug, Clone, PartialEq, Eq)]
256#[non_exhaustive]
257pub struct PrevoutsKindError;
258
259impl fmt::Display for PrevoutsKindError {
260    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
261        write!(f, "single prevout provided but all prevouts are needed without `ANYONECANPAY`")
262    }
263}
264
265#[cfg(feature = "std")]
266impl std::error::Error for PrevoutsKindError {
267    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { None }
268}
269
270/// [`Prevouts`] index related errors.
271#[derive(Debug, Clone, PartialEq, Eq)]
272#[non_exhaustive]
273pub enum PrevoutsIndexError {
274    /// Invalid index when accessing a [`Prevouts::One`] kind.
275    InvalidOneIndex,
276    /// Invalid index when accessing a [`Prevouts::All`] kind.
277    InvalidAllIndex,
278}
279
280internals::impl_from_infallible!(PrevoutsIndexError);
281
282impl fmt::Display for PrevoutsIndexError {
283    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
284        use PrevoutsIndexError::*;
285
286        match *self {
287            InvalidOneIndex => write!(f, "invalid index when accessing a Prevouts::One kind"),
288            InvalidAllIndex => write!(f, "invalid index when accessing a Prevouts::All kind"),
289        }
290    }
291}
292
293#[cfg(feature = "std")]
294impl std::error::Error for PrevoutsIndexError {
295    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
296        use PrevoutsIndexError::*;
297
298        match *self {
299            InvalidOneIndex | InvalidAllIndex => None,
300        }
301    }
302}
303
304impl<'s> ScriptPath<'s> {
305    /// Creates a new `ScriptPath` structure.
306    pub fn new(script: &'s Script, leaf_version: LeafVersion) -> Self {
307        ScriptPath { script, leaf_version }
308    }
309    /// Creates a new `ScriptPath` structure using default leaf version value.
310    pub fn with_defaults(script: &'s Script) -> Self { Self::new(script, LeafVersion::TapScript) }
311    /// Computes the leaf hash for this `ScriptPath`.
312    pub fn leaf_hash(&self) -> TapLeafHash {
313        let mut enc = TapLeafHash::engine();
314
315        self.leaf_version
316            .to_consensus()
317            .consensus_encode(&mut enc)
318            .expect("writing to hash enging should never fail");
319        self.script.consensus_encode(&mut enc).expect("writing to hash enging should never fail");
320
321        TapLeafHash::from_engine(enc)
322    }
323}
324
325impl<'s> From<ScriptPath<'s>> for TapLeafHash {
326    fn from(script_path: ScriptPath<'s>) -> TapLeafHash { script_path.leaf_hash() }
327}
328
329/// Hashtype of an input's signature, encoded in the last byte of the signature.
330///
331/// Fixed values so they can be cast as integer types for encoding (see also
332/// [`TapSighashType`]).
333#[derive(PartialEq, Eq, Debug, Copy, Clone, Hash)]
334pub enum EcdsaSighashType {
335    /// 0x1: Sign all outputs.
336    All = 0x01,
337    /// 0x2: Sign no outputs --- anyone can choose the destination.
338    None = 0x02,
339    /// 0x3: Sign the output whose index matches this input's index. If none exists,
340    /// sign the hash `0000000000000000000000000000000000000000000000000000000000000001`.
341    /// (This rule is probably an unintentional C++ism, but it's consensus so we have
342    /// to follow it.)
343    Single = 0x03,
344    /// 0x81: Sign all outputs but only this input.
345    AllPlusAnyoneCanPay = 0x81,
346    /// 0x82: Sign no outputs and only this input.
347    NonePlusAnyoneCanPay = 0x82,
348    /// 0x83: Sign one output and only this input (see `Single` for what "one output" means).
349    SinglePlusAnyoneCanPay = 0x83,
350}
351#[cfg(feature = "serde")]
352crate::serde_utils::serde_string_impl!(EcdsaSighashType, "a EcdsaSighashType data");
353
354impl fmt::Display for EcdsaSighashType {
355    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
356        use EcdsaSighashType::*;
357
358        let s = match self {
359            All => "SIGHASH_ALL",
360            None => "SIGHASH_NONE",
361            Single => "SIGHASH_SINGLE",
362            AllPlusAnyoneCanPay => "SIGHASH_ALL|SIGHASH_ANYONECANPAY",
363            NonePlusAnyoneCanPay => "SIGHASH_NONE|SIGHASH_ANYONECANPAY",
364            SinglePlusAnyoneCanPay => "SIGHASH_SINGLE|SIGHASH_ANYONECANPAY",
365        };
366        f.write_str(s)
367    }
368}
369
370impl str::FromStr for EcdsaSighashType {
371    type Err = SighashTypeParseError;
372
373    fn from_str(s: &str) -> Result<Self, Self::Err> {
374        use EcdsaSighashType::*;
375
376        match s {
377            "SIGHASH_ALL" => Ok(All),
378            "SIGHASH_NONE" => Ok(None),
379            "SIGHASH_SINGLE" => Ok(Single),
380            "SIGHASH_ALL|SIGHASH_ANYONECANPAY" => Ok(AllPlusAnyoneCanPay),
381            "SIGHASH_NONE|SIGHASH_ANYONECANPAY" => Ok(NonePlusAnyoneCanPay),
382            "SIGHASH_SINGLE|SIGHASH_ANYONECANPAY" => Ok(SinglePlusAnyoneCanPay),
383            _ => Err(SighashTypeParseError { unrecognized: s.to_owned() }),
384        }
385    }
386}
387
388impl EcdsaSighashType {
389    /// Splits the sighash flag into the "real" sighash flag and the ANYONECANPAY boolean.
390    pub(crate) fn split_anyonecanpay_flag(self) -> (EcdsaSighashType, bool) {
391        use EcdsaSighashType::*;
392
393        match self {
394            All => (All, false),
395            None => (None, false),
396            Single => (Single, false),
397            AllPlusAnyoneCanPay => (All, true),
398            NonePlusAnyoneCanPay => (None, true),
399            SinglePlusAnyoneCanPay => (Single, true),
400        }
401    }
402
403    /// Checks if the sighash type is [`Self::Single`] or [`Self::SinglePlusAnyoneCanPay`].
404    ///
405    /// This matches Bitcoin Core's behavior where SIGHASH_SINGLE bug check is based on the base
406    /// type (after masking with 0x1f), regardless of the ANYONECANPAY flag.
407    ///
408    /// See: <https://github.com/bitcoin/bitcoin/blob/e486597/src/script/interpreter.cpp#L1618-L1619>
409    pub fn is_single(&self) -> bool { matches!(self, Self::Single | Self::SinglePlusAnyoneCanPay) }
410
411    /// Creates a [`EcdsaSighashType`] from a raw `u32`.
412    ///
413    /// **Note**: this replicates consensus behaviour, for current standardness rules correctness
414    /// you probably want [`Self::from_standard`].
415    ///
416    /// This might cause unexpected behavior because it does not roundtrip. That is,
417    /// `EcdsaSighashType::from_consensus(n) as u32 != n` for non-standard values of `n`. While
418    /// verifying signatures, the user should retain the `n` and use it compute the signature hash
419    /// message.
420    pub fn from_consensus(n: u32) -> EcdsaSighashType {
421        use EcdsaSighashType::*;
422
423        // In Bitcoin Core, the SignatureHash function will mask the (int32) value with
424        // 0x1f to (apparently) deactivate ACP when checking for SINGLE and NONE bits.
425        // We however want to be matching also against on ACP-masked ALL, SINGLE, and NONE.
426        // So here we re-activate ACP.
427        let mask = 0x1f | 0x80;
428        match n & mask {
429            // "real" sighashes
430            0x01 => All,
431            0x02 => None,
432            0x03 => Single,
433            0x81 => AllPlusAnyoneCanPay,
434            0x82 => NonePlusAnyoneCanPay,
435            0x83 => SinglePlusAnyoneCanPay,
436            // catchalls
437            x if x & 0x80 == 0x80 => AllPlusAnyoneCanPay,
438            _ => All,
439        }
440    }
441
442    /// Creates a [`EcdsaSighashType`] from a raw `u32`.
443    ///
444    /// # Errors
445    ///
446    /// If `n` is a non-standard sighash value.
447    pub fn from_standard(n: u32) -> Result<EcdsaSighashType, NonStandardSighashTypeError> {
448        use EcdsaSighashType::*;
449
450        match n {
451            // Standard sighashes, see https://github.com/bitcoin/bitcoin/blob/b805dbb0b9c90dadef0424e5b3bf86ac308e103e/src/script/interpreter.cpp#L189-L198
452            0x01 => Ok(All),
453            0x02 => Ok(None),
454            0x03 => Ok(Single),
455            0x81 => Ok(AllPlusAnyoneCanPay),
456            0x82 => Ok(NonePlusAnyoneCanPay),
457            0x83 => Ok(SinglePlusAnyoneCanPay),
458            non_standard => Err(NonStandardSighashTypeError(non_standard)),
459        }
460    }
461
462    /// Converts [`EcdsaSighashType`] to a `u32` sighash flag.
463    ///
464    /// The returned value is guaranteed to be a valid according to standardness rules.
465    pub fn to_u32(self) -> u32 { self as u32 }
466}
467
468impl From<EcdsaSighashType> for TapSighashType {
469    fn from(s: EcdsaSighashType) -> Self {
470        use TapSighashType::*;
471
472        match s {
473            EcdsaSighashType::All => All,
474            EcdsaSighashType::None => None,
475            EcdsaSighashType::Single => Single,
476            EcdsaSighashType::AllPlusAnyoneCanPay => AllPlusAnyoneCanPay,
477            EcdsaSighashType::NonePlusAnyoneCanPay => NonePlusAnyoneCanPay,
478            EcdsaSighashType::SinglePlusAnyoneCanPay => SinglePlusAnyoneCanPay,
479        }
480    }
481}
482
483impl TapSighashType {
484    /// Breaks the sighash flag into the "real" sighash flag and the `SIGHASH_ANYONECANPAY` boolean.
485    pub(crate) fn split_anyonecanpay_flag(self) -> (TapSighashType, bool) {
486        use TapSighashType::*;
487
488        match self {
489            Default => (Default, false),
490            All => (All, false),
491            None => (None, false),
492            Single => (Single, false),
493            AllPlusAnyoneCanPay => (All, true),
494            NonePlusAnyoneCanPay => (None, true),
495            SinglePlusAnyoneCanPay => (Single, true),
496        }
497    }
498
499    /// Constructs a [`TapSighashType`] from a raw `u8`.
500    pub fn from_consensus_u8(sighash_type: u8) -> Result<Self, InvalidSighashTypeError> {
501        use TapSighashType::*;
502
503        Ok(match sighash_type {
504            0x00 => Default,
505            0x01 => All,
506            0x02 => None,
507            0x03 => Single,
508            0x81 => AllPlusAnyoneCanPay,
509            0x82 => NonePlusAnyoneCanPay,
510            0x83 => SinglePlusAnyoneCanPay,
511            x => return Err(InvalidSighashTypeError(x.into())),
512        })
513    }
514}
515
516/// Integer is not a consensus valid sighash type.
517#[derive(Debug, Clone, PartialEq, Eq)]
518pub struct InvalidSighashTypeError(pub u32);
519
520impl fmt::Display for InvalidSighashTypeError {
521    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
522        write!(f, "invalid sighash type {}", self.0)
523    }
524}
525
526#[cfg(feature = "std")]
527impl std::error::Error for InvalidSighashTypeError {
528    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { None }
529}
530
531/// This type is consensus valid but an input including it would prevent the transaction from
532/// being relayed on today's Bitcoin network.
533#[derive(Debug, Clone, PartialEq, Eq)]
534pub struct NonStandardSighashTypeError(pub u32);
535
536impl fmt::Display for NonStandardSighashTypeError {
537    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
538        write!(f, "non-standard sighash type {}", self.0)
539    }
540}
541
542#[cfg(feature = "std")]
543impl std::error::Error for NonStandardSighashTypeError {
544    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { None }
545}
546
547/// Error returned for failure during parsing one of the sighash types.
548///
549/// This is currently returned for unrecognized sighash strings.
550#[derive(Debug, Clone, PartialEq, Eq)]
551#[non_exhaustive]
552pub struct SighashTypeParseError {
553    /// The unrecognized string we attempted to parse.
554    pub unrecognized: String,
555}
556
557impl fmt::Display for SighashTypeParseError {
558    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
559        write!(f, "unrecognized SIGHASH string '{}'", self.unrecognized)
560    }
561}
562
563#[cfg(feature = "std")]
564impl std::error::Error for SighashTypeParseError {
565    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { None }
566}
567
568impl<R: Borrow<Transaction>> SighashCache<R> {
569    /// Constructs a new `SighashCache` from an unsigned transaction.
570    ///
571    /// The sighash components are computed in a lazy manner when required. For the generated
572    /// sighashes to be valid, no fields in the transaction may change except for script_sig and
573    /// witness.
574    pub fn new(tx: R) -> Self {
575        SighashCache { tx, common_cache: None, taproot_cache: None, segwit_cache: None }
576    }
577
578    /// Returns the reference to the cached transaction.
579    pub fn transaction(&self) -> &Transaction { self.tx.borrow() }
580
581    /// Destroys the cache and recovers the stored transaction.
582    pub fn into_transaction(self) -> R { self.tx }
583
584    /// Encodes the BIP341 signing data for any flag type into a given object implementing the
585    /// [`io::Write`] trait.
586    pub fn taproot_encode_signing_data_to<W: Write + ?Sized, T: Borrow<TxOut>>(
587        &mut self,
588        writer: &mut W,
589        input_index: usize,
590        prevouts: &Prevouts<T>,
591        annex: Option<Annex>,
592        leaf_hash_code_separator: Option<(TapLeafHash, u32)>,
593        sighash_type: TapSighashType,
594    ) -> Result<(), SigningDataError<TaprootError>> {
595        prevouts.check_all(self.tx.borrow()).map_err(SigningDataError::sighash)?;
596
597        let (sighash, anyone_can_pay) = sighash_type.split_anyonecanpay_flag();
598
599        // epoch
600        0u8.consensus_encode(writer)?;
601
602        // * Control:
603        // hash_type (1).
604        (sighash_type as u8).consensus_encode(writer)?;
605
606        // * Transaction Data:
607        // nVersion (4): the nVersion of the transaction.
608        self.tx.borrow().version.consensus_encode(writer)?;
609
610        // nLockTime (4): the nLockTime of the transaction.
611        self.tx.borrow().lock_time.consensus_encode(writer)?;
612
613        // If the hash_type & 0x80 does not equal SIGHASH_ANYONECANPAY:
614        //     sha_prevouts (32): the SHA256 of the serialization of all input outpoints.
615        //     sha_amounts (32): the SHA256 of the serialization of all spent output amounts.
616        //     sha_scriptpubkeys (32): the SHA256 of the serialization of all spent output scriptPubKeys.
617        //     sha_sequences (32): the SHA256 of the serialization of all input nSequence.
618        if !anyone_can_pay {
619            self.common_cache().prevouts.consensus_encode(writer)?;
620            self.taproot_cache(prevouts.get_all().map_err(SigningDataError::sighash)?)
621                .amounts
622                .consensus_encode(writer)?;
623            self.taproot_cache(prevouts.get_all().map_err(SigningDataError::sighash)?)
624                .script_pubkeys
625                .consensus_encode(writer)?;
626            self.common_cache().sequences.consensus_encode(writer)?;
627        }
628
629        // If hash_type & 3 does not equal SIGHASH_NONE or SIGHASH_SINGLE:
630        //     sha_outputs (32): the SHA256 of the serialization of all outputs in CTxOut format.
631        if sighash != TapSighashType::None && sighash != TapSighashType::Single {
632            self.common_cache().outputs.consensus_encode(writer)?;
633        }
634
635        // * Data about this input:
636        // spend_type (1): equal to (ext_flag * 2) + annex_present, where annex_present is 0
637        // if no annex is present, or 1 otherwise
638        let mut spend_type = 0u8;
639        if annex.is_some() {
640            spend_type |= 1u8;
641        }
642        if leaf_hash_code_separator.is_some() {
643            spend_type |= 2u8;
644        }
645        spend_type.consensus_encode(writer)?;
646
647        // If hash_type & 0x80 equals SIGHASH_ANYONECANPAY:
648        //      outpoint (36): the COutPoint of this input (32-byte hash + 4-byte little-endian).
649        //      amount (8): value of the previous output spent by this input.
650        //      scriptPubKey (35): scriptPubKey of the previous output spent by this input, serialized as script inside CTxOut. Its size is always 35 bytes.
651        //      nSequence (4): nSequence of this input.
652        if anyone_can_pay {
653            let txin = &self.tx.borrow().tx_in(input_index).map_err(SigningDataError::sighash)?;
654            let previous_output = prevouts.get(input_index).map_err(SigningDataError::sighash)?;
655            txin.previous_output.consensus_encode(writer)?;
656            previous_output.value.consensus_encode(writer)?;
657            previous_output.script_pubkey.consensus_encode(writer)?;
658            txin.sequence.consensus_encode(writer)?;
659        } else {
660            (input_index as u32).consensus_encode(writer)?;
661        }
662
663        // If an annex is present (the lowest bit of spend_type is set):
664        //      sha_annex (32): the SHA256 of (compact_size(size of annex) || annex), where annex
665        //      includes the mandatory 0x50 prefix.
666        if let Some(annex) = annex {
667            let mut enc = sha256::Hash::engine();
668            annex.consensus_encode(&mut enc)?;
669            let hash = sha256::Hash::from_engine(enc);
670            hash.consensus_encode(writer)?;
671        }
672
673        // * Data about this output:
674        // If hash_type & 3 equals SIGHASH_SINGLE:
675        //      sha_single_output (32): the SHA256 of the corresponding output in CTxOut format.
676        if sighash == TapSighashType::Single {
677            let mut enc = sha256::Hash::engine();
678            self.tx
679                .borrow()
680                .output
681                .get(input_index)
682                .ok_or(TaprootError::SingleMissingOutput(SingleMissingOutputError {
683                    input_index,
684                    outputs_length: self.tx.borrow().output.len(),
685                }))
686                .map_err(SigningDataError::Sighash)?
687                .consensus_encode(&mut enc)?;
688            let hash = sha256::Hash::from_engine(enc);
689            hash.consensus_encode(writer)?;
690        }
691
692        //     if (scriptpath):
693        //         ss += TaggedHash("TapLeaf", bytes([leaf_ver]) + ser_string(script))
694        //         ss += bytes([0])
695        //         ss += struct.pack("<i", codeseparator_pos)
696        if let Some((hash, code_separator_pos)) = leaf_hash_code_separator {
697            hash.as_byte_array().consensus_encode(writer)?;
698            KEY_VERSION_0.consensus_encode(writer)?;
699            code_separator_pos.consensus_encode(writer)?;
700        }
701
702        Ok(())
703    }
704
705    /// Computes the BIP341 sighash for any flag type.
706    pub fn taproot_signature_hash<T: Borrow<TxOut>>(
707        &mut self,
708        input_index: usize,
709        prevouts: &Prevouts<T>,
710        annex: Option<Annex>,
711        leaf_hash_code_separator: Option<(TapLeafHash, u32)>,
712        sighash_type: TapSighashType,
713    ) -> Result<TapSighash, TaprootError> {
714        let mut enc = TapSighash::engine();
715        self.taproot_encode_signing_data_to(
716            &mut enc,
717            input_index,
718            prevouts,
719            annex,
720            leaf_hash_code_separator,
721            sighash_type,
722        )
723        .map_err(SigningDataError::unwrap_sighash)?;
724        Ok(TapSighash::from_engine(enc))
725    }
726
727    /// Computes the BIP341 sighash for a key spend.
728    pub fn taproot_key_spend_signature_hash<T: Borrow<TxOut>>(
729        &mut self,
730        input_index: usize,
731        prevouts: &Prevouts<T>,
732        sighash_type: TapSighashType,
733    ) -> Result<TapSighash, TaprootError> {
734        let mut enc = TapSighash::engine();
735        self.taproot_encode_signing_data_to(
736            &mut enc,
737            input_index,
738            prevouts,
739            None,
740            None,
741            sighash_type,
742        )
743        .map_err(SigningDataError::unwrap_sighash)?;
744        Ok(TapSighash::from_engine(enc))
745    }
746
747    /// Computes the BIP341 sighash for a script spend.
748    ///
749    /// Assumes the default `OP_CODESEPARATOR` position of `0xFFFFFFFF`. Custom values can be
750    /// provided through the more fine-grained API of [`SighashCache::taproot_encode_signing_data_to`].
751    pub fn taproot_script_spend_signature_hash<S: Into<TapLeafHash>, T: Borrow<TxOut>>(
752        &mut self,
753        input_index: usize,
754        prevouts: &Prevouts<T>,
755        leaf_hash: S,
756        sighash_type: TapSighashType,
757    ) -> Result<TapSighash, TaprootError> {
758        let mut enc = TapSighash::engine();
759        self.taproot_encode_signing_data_to(
760            &mut enc,
761            input_index,
762            prevouts,
763            None,
764            Some((leaf_hash.into(), 0xFFFFFFFF)),
765            sighash_type,
766        )
767        .map_err(SigningDataError::unwrap_sighash)?;
768        Ok(TapSighash::from_engine(enc))
769    }
770
771    /// Encodes the BIP143 signing data for any flag type into a given object implementing the
772    /// [`std::io::Write`] trait.
773    ///
774    /// `script_code` is dependent on the type of the spend transaction. For p2wpkh use
775    /// [`Script::p2wpkh_script_code`], for p2wsh just pass in the witness script. (Also see
776    /// [`Self::p2wpkh_signature_hash`] and [`SighashCache::p2wsh_signature_hash`].)
777    pub fn segwit_v0_encode_signing_data_to<W: Write + ?Sized>(
778        &mut self,
779        writer: &mut W,
780        input_index: usize,
781        script_code: &Script,
782        value: Amount,
783        sighash_type: EcdsaSighashType,
784    ) -> Result<(), SigningDataError<transaction::InputsIndexError>> {
785        let zero_hash = sha256d::Hash::all_zeros();
786
787        let (sighash, anyone_can_pay) = sighash_type.split_anyonecanpay_flag();
788
789        self.tx.borrow().version.consensus_encode(writer)?;
790
791        if !anyone_can_pay {
792            self.segwit_cache().prevouts.consensus_encode(writer)?;
793        } else {
794            zero_hash.consensus_encode(writer)?;
795        }
796
797        if !anyone_can_pay
798            && sighash != EcdsaSighashType::Single
799            && sighash != EcdsaSighashType::None
800        {
801            self.segwit_cache().sequences.consensus_encode(writer)?;
802        } else {
803            zero_hash.consensus_encode(writer)?;
804        }
805
806        {
807            let txin = &self.tx.borrow().tx_in(input_index).map_err(SigningDataError::sighash)?;
808            txin.previous_output.consensus_encode(writer)?;
809            script_code.consensus_encode(writer)?;
810            value.consensus_encode(writer)?;
811            txin.sequence.consensus_encode(writer)?;
812        }
813
814        if sighash != EcdsaSighashType::Single && sighash != EcdsaSighashType::None {
815            self.segwit_cache().outputs.consensus_encode(writer)?;
816        } else if sighash == EcdsaSighashType::Single && input_index < self.tx.borrow().output.len()
817        {
818            let mut single_enc = LegacySighash::engine();
819            self.tx.borrow().output[input_index].consensus_encode(&mut single_enc)?;
820            let hash = LegacySighash::from_engine(single_enc);
821            writer.write_all(&hash[..])?;
822        } else {
823            writer.write_all(&zero_hash[..])?;
824        }
825
826        self.tx.borrow().lock_time.consensus_encode(writer)?;
827        sighash_type.to_u32().consensus_encode(writer)?;
828        Ok(())
829    }
830
831    /// Computes the BIP143 sighash to spend a p2wpkh transaction for any flag type.
832    ///
833    /// `script_pubkey` is the `scriptPubkey` (native segwit) of the spend transaction
834    /// ([`TxOut::script_pubkey`]) or the `redeemScript` (wrapped segwit).
835    pub fn p2wpkh_signature_hash(
836        &mut self,
837        input_index: usize,
838        script_pubkey: &Script,
839        value: Amount,
840        sighash_type: EcdsaSighashType,
841    ) -> Result<SegwitV0Sighash, P2wpkhError> {
842        let script_code = script_pubkey.p2wpkh_script_code().ok_or(P2wpkhError::NotP2wpkhScript)?;
843
844        let mut enc = SegwitV0Sighash::engine();
845        self.segwit_v0_encode_signing_data_to(
846            &mut enc,
847            input_index,
848            &script_code,
849            value,
850            sighash_type,
851        )
852        .map_err(SigningDataError::unwrap_sighash)?;
853        Ok(SegwitV0Sighash::from_engine(enc))
854    }
855
856    /// Computes the BIP143 sighash to spend a p2wsh transaction for any flag type.
857    pub fn p2wsh_signature_hash(
858        &mut self,
859        input_index: usize,
860        witness_script: &Script,
861        value: Amount,
862        sighash_type: EcdsaSighashType,
863    ) -> Result<SegwitV0Sighash, transaction::InputsIndexError> {
864        let mut enc = SegwitV0Sighash::engine();
865        self.segwit_v0_encode_signing_data_to(
866            &mut enc,
867            input_index,
868            witness_script,
869            value,
870            sighash_type,
871        )
872        .map_err(SigningDataError::unwrap_sighash)?;
873        Ok(SegwitV0Sighash::from_engine(enc))
874    }
875
876    /// Encodes the legacy signing data from which a signature hash for a given input index with a
877    /// given sighash flag can be computed.
878    ///
879    /// To actually produce a scriptSig, this hash needs to be run through an ECDSA signer, the
880    /// [`EcdsaSighashType`] appended to the resulting sig, and a script written around this, but
881    /// this is the general (and hard) part.
882    ///
883    /// The `sighash_type` supports an arbitrary `u32` value, instead of just [`EcdsaSighashType`],
884    /// because internally 4 bytes are being hashed, even though only the lowest byte is appended to
885    /// signature in a transaction.
886    ///
887    /// # Warning
888    ///
889    /// - Does NOT attempt to support OP_CODESEPARATOR. In general this would require evaluating
890    ///   `script_pubkey` to determine which separators get evaluated and which don't, which we don't
891    ///   have the information to determine.
892    /// - Does NOT handle the sighash single bug (see "Return type" section)
893    ///
894    /// # Returns
895    ///
896    /// This function can't handle the SIGHASH_SINGLE bug internally, so it returns [`EncodeSigningDataResult`]
897    /// that must be handled by the caller (see [`EncodeSigningDataResult::is_sighash_single_bug`]).
898    pub fn legacy_encode_signing_data_to<W: Write + ?Sized, U: Into<u32>>(
899        &self,
900        writer: &mut W,
901        input_index: usize,
902        script_pubkey: &Script,
903        sighash_type: U,
904    ) -> EncodeSigningDataResult<SigningDataError<transaction::InputsIndexError>> {
905        // Validate input_index.
906        if let Err(e) = self.tx.borrow().tx_in(input_index) {
907            return EncodeSigningDataResult::WriteResult(Err(SigningDataError::Sighash(e)));
908        }
909        let sighash_type: u32 = sighash_type.into();
910
911        if is_invalid_use_of_sighash_single(
912            sighash_type,
913            input_index,
914            self.tx.borrow().output.len(),
915        ) {
916            // We cannot correctly handle the SIGHASH_SINGLE bug here because usage of this function
917            // will result in the data written to the writer being hashed, however the correct
918            // handling of the SIGHASH_SINGLE bug is to return the 'one array' - either implement
919            // this behaviour manually or use `signature_hash()`.
920            return EncodeSigningDataResult::SighashSingleBug;
921        }
922
923        fn encode_signing_data_to_inner<W: Write + ?Sized>(
924            self_: &Transaction,
925            writer: &mut W,
926            input_index: usize,
927            script_pubkey: &Script,
928            sighash_type: u32,
929        ) -> Result<(), io::Error> {
930            let (sighash, anyone_can_pay) =
931                EcdsaSighashType::from_consensus(sighash_type).split_anyonecanpay_flag();
932
933            // Build tx to sign
934            let mut tx = Transaction {
935                version: self_.version,
936                lock_time: self_.lock_time,
937                input: vec![],
938                output: vec![],
939            };
940            // Add all inputs necessary..
941            if anyone_can_pay {
942                tx.input = vec![TxIn {
943                    previous_output: self_.input[input_index].previous_output,
944                    script_sig: script_pubkey.to_owned(),
945                    sequence: self_.input[input_index].sequence,
946                    witness: Witness::default(),
947                }];
948            } else {
949                tx.input = Vec::with_capacity(self_.input.len());
950                for (n, input) in self_.input.iter().enumerate() {
951                    tx.input.push(TxIn {
952                        previous_output: input.previous_output,
953                        script_sig: if n == input_index {
954                            script_pubkey.to_owned()
955                        } else {
956                            ScriptBuf::new()
957                        },
958                        sequence: if n != input_index
959                            && (sighash == EcdsaSighashType::Single
960                                || sighash == EcdsaSighashType::None)
961                        {
962                            Sequence::ZERO
963                        } else {
964                            input.sequence
965                        },
966                        witness: Witness::default(),
967                    });
968                }
969            }
970            // ..then all outputs
971            tx.output = match sighash {
972                EcdsaSighashType::All => self_.output.clone(),
973                EcdsaSighashType::Single => {
974                    let output_iter = self_
975                        .output
976                        .iter()
977                        .take(input_index + 1) // sign all outputs up to and including this one, but erase
978                        .enumerate() // all of them except for this one
979                        .map(|(n, out)| if n == input_index { out.clone() } else { TxOut::NULL });
980                    output_iter.collect()
981                }
982                EcdsaSighashType::None => vec![],
983                _ => unreachable!(),
984            };
985            // hash the result
986            tx.consensus_encode(writer)?;
987            sighash_type.to_le_bytes().consensus_encode(writer)?;
988            Ok(())
989        }
990
991        EncodeSigningDataResult::WriteResult(
992            encode_signing_data_to_inner(
993                self.tx.borrow(),
994                writer,
995                input_index,
996                script_pubkey,
997                sighash_type,
998            )
999            .map_err(Into::into),
1000        )
1001    }
1002
1003    /// Computes a legacy signature hash for a given input index with a given sighash flag.
1004    ///
1005    /// To actually produce a scriptSig, this hash needs to be run through an ECDSA signer, the
1006    /// [`EcdsaSighashType`] appended to the resulting sig, and a script written around this, but
1007    /// this is the general (and hard) part.
1008    ///
1009    /// The `sighash_type` supports an arbitrary `u32` value, instead of just [`EcdsaSighashType`],
1010    /// because internally 4 bytes are being hashed, even though only the lowest byte is appended to
1011    /// signature in a transaction.
1012    ///
1013    /// This function correctly handles the sighash single bug by returning the 'one array'. The
1014    /// sighash single bug becomes exploitable when one tries to sign a transaction with
1015    /// `SIGHASH_SINGLE` and there is not a corresponding output with the same index as the input.
1016    ///
1017    /// # Warning
1018    ///
1019    /// Does NOT attempt to support OP_CODESEPARATOR. In general this would require evaluating
1020    /// `script_pubkey` to determine which separators get evaluated and which don't, which we don't
1021    /// have the information to determine.
1022    pub fn legacy_signature_hash(
1023        &self,
1024        input_index: usize,
1025        script_pubkey: &Script,
1026        sighash_type: u32,
1027    ) -> Result<LegacySighash, transaction::InputsIndexError> {
1028        let mut engine = LegacySighash::engine();
1029        match self
1030            .legacy_encode_signing_data_to(&mut engine, input_index, script_pubkey, sighash_type)
1031            .is_sighash_single_bug()
1032        {
1033            Ok(true) => Ok(LegacySighash::from_byte_array(UINT256_ONE)),
1034            Ok(false) => Ok(LegacySighash::from_engine(engine)),
1035            Err(e) => Err(e.unwrap_sighash()),
1036        }
1037    }
1038
1039    #[inline]
1040    fn common_cache(&mut self) -> &CommonCache {
1041        Self::common_cache_minimal_borrow(&mut self.common_cache, self.tx.borrow())
1042    }
1043
1044    fn common_cache_minimal_borrow<'a>(
1045        common_cache: &'a mut Option<CommonCache>,
1046        tx: &Transaction,
1047    ) -> &'a CommonCache {
1048        common_cache.get_or_insert_with(|| {
1049            let mut enc_prevouts = sha256::Hash::engine();
1050            let mut enc_sequences = sha256::Hash::engine();
1051            for txin in tx.input.iter() {
1052                txin.previous_output.consensus_encode(&mut enc_prevouts).unwrap();
1053                txin.sequence.consensus_encode(&mut enc_sequences).unwrap();
1054            }
1055            CommonCache {
1056                prevouts: sha256::Hash::from_engine(enc_prevouts),
1057                sequences: sha256::Hash::from_engine(enc_sequences),
1058                outputs: {
1059                    let mut enc = sha256::Hash::engine();
1060                    for txout in tx.output.iter() {
1061                        txout.consensus_encode(&mut enc).unwrap();
1062                    }
1063                    sha256::Hash::from_engine(enc)
1064                },
1065            }
1066        })
1067    }
1068
1069    fn segwit_cache(&mut self) -> &SegwitCache {
1070        let common_cache = &mut self.common_cache;
1071        let tx = self.tx.borrow();
1072        self.segwit_cache.get_or_insert_with(|| {
1073            let common_cache = Self::common_cache_minimal_borrow(common_cache, tx);
1074            SegwitCache {
1075                prevouts: common_cache.prevouts.hash_again(),
1076                sequences: common_cache.sequences.hash_again(),
1077                outputs: common_cache.outputs.hash_again(),
1078            }
1079        })
1080    }
1081
1082    fn taproot_cache<T: Borrow<TxOut>>(&mut self, prevouts: &[T]) -> &TaprootCache {
1083        self.taproot_cache.get_or_insert_with(|| {
1084            let mut enc_amounts = sha256::Hash::engine();
1085            let mut enc_script_pubkeys = sha256::Hash::engine();
1086            for prevout in prevouts {
1087                prevout.borrow().value.consensus_encode(&mut enc_amounts).unwrap();
1088                prevout.borrow().script_pubkey.consensus_encode(&mut enc_script_pubkeys).unwrap();
1089            }
1090            TaprootCache {
1091                amounts: sha256::Hash::from_engine(enc_amounts),
1092                script_pubkeys: sha256::Hash::from_engine(enc_script_pubkeys),
1093            }
1094        })
1095    }
1096}
1097
1098impl<R: BorrowMut<Transaction>> SighashCache<R> {
1099    /// Allows modification of witnesses.
1100    ///
1101    /// As a lint against accidental changes to the transaction that would invalidate the cache and
1102    /// signatures, `SighashCache` borrows the Transaction so that modifying it is not possible
1103    /// without hacks with `UnsafeCell` (which is hopefully a strong indication that something is
1104    /// wrong). However modifying witnesses never invalidates the cache and is actually useful - one
1105    /// usually wants to put the signature generated for an input into the witness of that input.
1106    ///
1107    /// This method allows doing exactly that if the transaction is owned by the `SighashCache` or
1108    /// borrowed mutably.
1109    ///
1110    /// # Examples
1111    ///
1112    /// ```compile_fail
1113    /// let mut sighasher = SighashCache::new(&mut tx_to_sign);
1114    /// let sighash = sighasher.p2wpkh_signature_hash(input_index, &utxo.script_pubkey, amount, sighash_type)?;
1115    ///
1116    /// let signature = {
1117    ///     // Sign the sighash using secp256k1
1118    /// };
1119    ///
1120    /// *sighasher.witness_mut(input_index).unwrap() = Witness::p2wpkh(&signature, &pk);
1121    /// ```
1122    ///
1123    /// For full signing code see the [`segwit v0`] and [`taproot`] signing examples.
1124    ///
1125    /// [`segwit v0`]: <https://github.com/rust-bitcoin/rust-bitcoin/blob/master/bitcoin/examples/sign-tx-segwit-v0.rs>
1126    /// [`taproot`]: <https://github.com/rust-bitcoin/rust-bitcoin/blob/master/bitcoin/examples/sign-tx-taproot.rs>
1127    pub fn witness_mut(&mut self, input_index: usize) -> Option<&mut Witness> {
1128        self.tx.borrow_mut().input.get_mut(input_index).map(|i| &mut i.witness)
1129    }
1130}
1131
1132/// The `Annex` struct is a slice wrapper enforcing first byte is `0x50`.
1133#[derive(Clone, PartialEq, Eq, Hash, Debug)]
1134pub struct Annex<'a>(&'a [u8]);
1135
1136impl<'a> Annex<'a> {
1137    /// Creates a new `Annex` struct checking the first byte is `0x50`.
1138    pub fn new(annex_bytes: &'a [u8]) -> Result<Self, AnnexError> {
1139        use AnnexError::*;
1140
1141        match annex_bytes.first() {
1142            Some(&TAPROOT_ANNEX_PREFIX) => Ok(Annex(annex_bytes)),
1143            Some(other) => Err(IncorrectPrefix(*other)),
1144            None => Err(Empty),
1145        }
1146    }
1147
1148    /// Returns the Annex bytes data (including first byte `0x50`).
1149    pub fn as_bytes(&self) -> &[u8] { self.0 }
1150}
1151
1152impl<'a> Encodable for Annex<'a> {
1153    fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
1154        encode::consensus_encode_with_size(self.0, w)
1155    }
1156}
1157
1158/// Error computing a taproot sighash.
1159#[derive(Debug, Clone, PartialEq, Eq)]
1160#[non_exhaustive]
1161pub enum TaprootError {
1162    /// Index out of bounds when accessing transaction input vector.
1163    InputsIndex(transaction::InputsIndexError),
1164    /// Using `SIGHASH_SINGLE` requires an output at the same index is the input.
1165    SingleMissingOutput(SingleMissingOutputError),
1166    /// Prevouts size error.
1167    PrevoutsSize(PrevoutsSizeError),
1168    /// Prevouts index error.
1169    PrevoutsIndex(PrevoutsIndexError),
1170    /// Prevouts kind error.
1171    PrevoutsKind(PrevoutsKindError),
1172    /// Invalid Sighash type.
1173    InvalidSighashType(u32),
1174}
1175
1176internals::impl_from_infallible!(TaprootError);
1177
1178impl fmt::Display for TaprootError {
1179    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1180        use TaprootError::*;
1181
1182        match *self {
1183            InputsIndex(ref e) => write_err!(f, "inputs index"; e),
1184            SingleMissingOutput(ref e) => write_err!(f, "sighash single"; e),
1185            PrevoutsSize(ref e) => write_err!(f, "prevouts size"; e),
1186            PrevoutsIndex(ref e) => write_err!(f, "prevouts index"; e),
1187            PrevoutsKind(ref e) => write_err!(f, "prevouts kind"; e),
1188            InvalidSighashType(hash_ty) => write!(f, "invalid taproot sighash type : {} ", hash_ty),
1189        }
1190    }
1191}
1192
1193#[cfg(feature = "std")]
1194impl std::error::Error for TaprootError {
1195    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1196        use TaprootError::*;
1197
1198        match *self {
1199            InputsIndex(ref e) => Some(e),
1200            SingleMissingOutput(ref e) => Some(e),
1201            PrevoutsSize(ref e) => Some(e),
1202            PrevoutsIndex(ref e) => Some(e),
1203            PrevoutsKind(ref e) => Some(e),
1204            InvalidSighashType(_) => None,
1205        }
1206    }
1207}
1208
1209impl From<transaction::InputsIndexError> for TaprootError {
1210    fn from(e: transaction::InputsIndexError) -> Self { Self::InputsIndex(e) }
1211}
1212
1213impl From<PrevoutsSizeError> for TaprootError {
1214    fn from(e: PrevoutsSizeError) -> Self { Self::PrevoutsSize(e) }
1215}
1216
1217impl From<PrevoutsKindError> for TaprootError {
1218    fn from(e: PrevoutsKindError) -> Self { Self::PrevoutsKind(e) }
1219}
1220
1221impl From<PrevoutsIndexError> for TaprootError {
1222    fn from(e: PrevoutsIndexError) -> Self { Self::PrevoutsIndex(e) }
1223}
1224
1225/// Error computing a P2WPKH sighash.
1226#[derive(Debug, Clone, PartialEq, Eq)]
1227#[non_exhaustive]
1228pub enum P2wpkhError {
1229    /// Error computing the sighash.
1230    Sighash(transaction::InputsIndexError),
1231    /// Script is not a witness program for a p2wpkh output.
1232    NotP2wpkhScript,
1233}
1234
1235internals::impl_from_infallible!(P2wpkhError);
1236
1237impl From<transaction::InputsIndexError> for P2wpkhError {
1238    fn from(value: transaction::InputsIndexError) -> Self { P2wpkhError::Sighash(value) }
1239}
1240
1241impl fmt::Display for P2wpkhError {
1242    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1243        use P2wpkhError::*;
1244
1245        match *self {
1246            Sighash(ref e) => write_err!(f, "error encoding segwit v0 signing data"; e),
1247            NotP2wpkhScript => write!(f, "script is not a script pubkey for a p2wpkh output"),
1248        }
1249    }
1250}
1251
1252#[cfg(feature = "std")]
1253impl std::error::Error for P2wpkhError {
1254    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1255        use P2wpkhError::*;
1256
1257        match *self {
1258            Sighash(ref e) => Some(e),
1259            NotP2wpkhScript => None,
1260        }
1261    }
1262}
1263
1264/// Using `SIGHASH_SINGLE` requires an output at the same index as the input.
1265#[derive(Debug, Clone, PartialEq, Eq)]
1266#[non_exhaustive]
1267pub struct SingleMissingOutputError {
1268    /// Input index.
1269    pub input_index: usize,
1270    /// Length of the output vector.
1271    pub outputs_length: usize,
1272}
1273
1274impl fmt::Display for SingleMissingOutputError {
1275    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1276        write!(
1277            f,
1278            "sighash single requires an output at the same index as the input \
1279             (input index: {}, outputs length: {})",
1280            self.input_index, self.outputs_length
1281        )
1282    }
1283}
1284
1285#[cfg(feature = "std")]
1286impl std::error::Error for SingleMissingOutputError {
1287    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { None }
1288}
1289
1290/// Annex must be at least one byte long and the first bytes must be `0x50`.
1291#[derive(Debug, Clone, PartialEq, Eq)]
1292#[non_exhaustive]
1293pub enum AnnexError {
1294    /// The annex is empty.
1295    Empty,
1296    /// Incorrect prefix byte in the annex.
1297    IncorrectPrefix(u8),
1298}
1299
1300internals::impl_from_infallible!(AnnexError);
1301
1302impl fmt::Display for AnnexError {
1303    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1304        use AnnexError::*;
1305
1306        match *self {
1307            Empty => write!(f, "the annex is empty"),
1308            IncorrectPrefix(byte) =>
1309                write!(f, "incorrect prefix byte in the annex {:02x}, expecting 0x50", byte),
1310        }
1311    }
1312}
1313
1314#[cfg(feature = "std")]
1315impl std::error::Error for AnnexError {
1316    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1317        use AnnexError::*;
1318
1319        match *self {
1320            Empty | IncorrectPrefix(_) => None,
1321        }
1322    }
1323}
1324
1325fn is_invalid_use_of_sighash_single(sighash: u32, input_index: usize, outputs_len: usize) -> bool {
1326    let ty = EcdsaSighashType::from_consensus(sighash);
1327    ty.is_single() && input_index >= outputs_len
1328}
1329
1330/// Result of [`SighashCache::legacy_encode_signing_data_to`].
1331///
1332/// This type forces the caller to handle SIGHASH_SINGLE bug case.
1333///
1334/// This corner case can't be expressed using standard `Result`,
1335/// in a way that is both convenient and not-prone to accidental
1336/// mistakes (like calling `.expect("writer never fails")`).
1337#[must_use]
1338pub enum EncodeSigningDataResult<E> {
1339    /// Input data is an instance of `SIGHASH_SINGLE` bug
1340    SighashSingleBug,
1341    /// Operation performed normally.
1342    WriteResult(Result<(), E>),
1343}
1344
1345impl<E> EncodeSigningDataResult<E> {
1346    /// Checks for SIGHASH_SINGLE bug returning error if the writer failed.
1347    ///
1348    /// This method is provided for easy and correct handling of the result because
1349    /// SIGHASH_SINGLE bug is a special case that must not be ignored nor cause panicking.
1350    /// Since the data is usually written directly into a hasher which never fails,
1351    /// the recommended pattern to handle this is:
1352    ///
1353    /// ```rust
1354    /// # use bitcoin::consensus::deserialize;
1355    /// # use bitcoin::hashes::{Hash, hex::FromHex};
1356    /// # use bitcoin::sighash::{LegacySighash, SighashCache};
1357    /// # use bitcoin::Transaction;
1358    /// # let mut writer = LegacySighash::engine();
1359    /// # let input_index = 0;
1360    /// # let script_pubkey = bitcoin::ScriptBuf::new();
1361    /// # let sighash_u32 = 0u32;
1362    /// # const SOME_TX: &'static str = "0100000001a15d57094aa7a21a28cb20b59aab8fc7d1149a3bdbcddba9c622e4f5f6a99ece010000006c493046022100f93bb0e7d8db7bd46e40132d1f8242026e045f03a0efe71bbb8e3f475e970d790221009337cd7f1f929f00cc6ff01f03729b069a7c21b59b1736ddfee5db5946c5da8c0121033b9b137ee87d5a812d6f506efdd37f0affa7ffc310711c06c7f3e097c9447c52ffffffff0100e1f505000000001976a9140389035a9225b3839e2bbf32d826a1e222031fd888ac00000000";
1363    /// # let raw_tx = Vec::from_hex(SOME_TX).unwrap();
1364    /// # let tx: Transaction = deserialize(&raw_tx).unwrap();
1365    /// let cache = SighashCache::new(&tx);
1366    /// if cache.legacy_encode_signing_data_to(&mut writer, input_index, &script_pubkey, sighash_u32)
1367    ///         .is_sighash_single_bug()
1368    ///         .expect("writer can't fail") {
1369    ///     // use a hash value of "1", instead of computing the actual hash due to SIGHASH_SINGLE bug
1370    /// }
1371    /// ```
1372    pub fn is_sighash_single_bug(self) -> Result<bool, E> {
1373        match self {
1374            EncodeSigningDataResult::SighashSingleBug => Ok(true),
1375            EncodeSigningDataResult::WriteResult(Ok(())) => Ok(false),
1376            EncodeSigningDataResult::WriteResult(Err(e)) => Err(e),
1377        }
1378    }
1379
1380    /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
1381    /// contained [`Err`] value, leaving an [`Ok`] value untouched.
1382    ///
1383    /// Like [`Result::map_err`].
1384    pub fn map_err<E2, F>(self, f: F) -> EncodeSigningDataResult<E2>
1385    where
1386        F: FnOnce(E) -> E2,
1387    {
1388        match self {
1389            EncodeSigningDataResult::SighashSingleBug => EncodeSigningDataResult::SighashSingleBug,
1390            EncodeSigningDataResult::WriteResult(Err(e)) =>
1391                EncodeSigningDataResult::WriteResult(Err(f(e))),
1392            EncodeSigningDataResult::WriteResult(Ok(o)) =>
1393                EncodeSigningDataResult::WriteResult(Ok(o)),
1394        }
1395    }
1396}
1397
1398/// Error returned when writing signing data fails.
1399#[derive(Debug)]
1400pub enum SigningDataError<E> {
1401    /// Can happen only when using `*_encode_signing_*` methods with custom writers, engines
1402    /// like those used in `*_signature_hash` methods do not error.
1403    Io(io::Error),
1404    /// An argument to the called sighash function was invalid.
1405    Sighash(E),
1406}
1407
1408internals::impl_from_infallible!(SigningDataError<E>);
1409
1410impl<E> SigningDataError<E> {
1411    /// Returns the sighash variant, panicking if it's IO.
1412    ///
1413    /// This is used when encoding to hash engine when we know that IO doesn't fail.
1414    fn unwrap_sighash(self) -> E {
1415        match self {
1416            Self::Sighash(error) => error,
1417            Self::Io(error) => panic!("hash engine error {}", error),
1418        }
1419    }
1420
1421    fn sighash<E2: Into<E>>(error: E2) -> Self { Self::Sighash(error.into()) }
1422}
1423
1424// We cannot simultaneously impl `From<E>`. it was determined that this alternative requires less
1425// manual `map_err` calls.
1426impl<E> From<io::Error> for SigningDataError<E> {
1427    fn from(value: io::Error) -> Self { Self::Io(value) }
1428}
1429
1430impl<E: fmt::Display> fmt::Display for SigningDataError<E> {
1431    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1432        match self {
1433            Self::Io(error) => write_err!(f, "failed to write sighash data"; error),
1434            Self::Sighash(error) => write_err!(f, "failed to compute sighash data"; error),
1435        }
1436    }
1437}
1438
1439#[cfg(feature = "std")]
1440impl<E: std::error::Error + 'static> std::error::Error for SigningDataError<E> {
1441    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1442        match self {
1443            SigningDataError::Io(error) => Some(error),
1444            SigningDataError::Sighash(error) => Some(error),
1445        }
1446    }
1447}
1448
1449#[cfg(test)]
1450mod tests {
1451    use std::str::FromStr;
1452
1453    use hashes::HashEngine;
1454    use hex::{test_hex_unwrap as hex, FromHex};
1455
1456    use super::*;
1457    use crate::blockdata::locktime::absolute;
1458    use crate::consensus::deserialize;
1459
1460    extern crate serde_json;
1461
1462    #[test]
1463    fn sighash_single_bug() {
1464        // We need a tx with more inputs than outputs.
1465        let tx = Transaction {
1466            version: transaction::Version::ONE,
1467            lock_time: absolute::LockTime::ZERO,
1468            input: vec![TxIn::default(), TxIn::default()],
1469            output: vec![TxOut::NULL],
1470        };
1471        let script = ScriptBuf::new();
1472        let cache = SighashCache::new(&tx);
1473
1474        let sighash_single = 3;
1475        let got = cache.legacy_signature_hash(1, &script, sighash_single).expect("sighash");
1476        let want = LegacySighash::from_byte_array(UINT256_ONE);
1477        assert_eq!(got, want);
1478
1479        // https://github.com/rust-bitcoin/rust-bitcoin/issues/4112
1480        let sighash_single = 131;
1481        let got = cache.legacy_signature_hash(1, &script, sighash_single).expect("sighash");
1482        let want = LegacySighash::from_byte_array(UINT256_ONE);
1483        assert_eq!(got, want);
1484    }
1485
1486    #[test]
1487    #[cfg(feature = "serde")]
1488    fn legacy_sighash() {
1489        use serde_json::Value;
1490
1491        use crate::sighash::SighashCache;
1492
1493        fn run_test_sighash(
1494            tx: &str,
1495            script: &str,
1496            input_index: usize,
1497            hash_type: i64,
1498            expected_result: &str,
1499        ) {
1500            let tx: Transaction = deserialize(&Vec::from_hex(tx).unwrap()[..]).unwrap();
1501            let script = ScriptBuf::from(Vec::from_hex(script).unwrap());
1502            let mut raw_expected = Vec::from_hex(expected_result).unwrap();
1503            raw_expected.reverse();
1504            let want = LegacySighash::from_slice(&raw_expected[..]).unwrap();
1505
1506            let cache = SighashCache::new(&tx);
1507            let got = cache.legacy_signature_hash(input_index, &script, hash_type as u32).unwrap();
1508
1509            assert_eq!(got, want);
1510        }
1511
1512        // These test vectors were stolen from libbtc, which is Copyright 2014 Jonas Schnelli MIT
1513        // They were transformed by replacing {...} with run_test_sighash(...), then the ones containing
1514        // OP_CODESEPARATOR in their pubkeys were removed
1515        let data = include_str!("../../tests/data/legacy_sighash.json");
1516
1517        let testdata = serde_json::from_str::<Value>(data).unwrap().as_array().unwrap().clone();
1518        for t in testdata.iter().skip(1) {
1519            let tx = t.get(0).unwrap().as_str().unwrap();
1520            let script = t.get(1).unwrap().as_str().unwrap_or("");
1521            let input_index = t.get(2).unwrap().as_u64().unwrap();
1522            let hash_type = t.get(3).unwrap().as_i64().unwrap();
1523            let expected_sighash = t.get(4).unwrap().as_str().unwrap();
1524            run_test_sighash(tx, script, input_index as usize, hash_type, expected_sighash);
1525        }
1526    }
1527
1528    #[test]
1529    fn test_tap_sighash_hash() {
1530        let bytes = hex!("00011b96877db45ffa23b307e9f0ac87b80ef9a80b4c5f0db3fbe734422453e83cc5576f3d542c5d4898fb2b696c15d43332534a7c1d1255fda38993545882df92c3e353ff6d36fbfadc4d168452afd8467f02fe53d71714fcea5dfe2ea759bd00185c4cb02bc76d42620393ca358a1a713f4997f9fc222911890afb3fe56c6a19b202df7bffdcfad08003821294279043746631b00e2dc5e52a111e213bbfe6ef09a19428d418dab0d50000000000");
1531        let expected = hex!("04e808aad07a40b3767a1442fead79af6ef7e7c9316d82dec409bb31e77699b0");
1532        let mut enc = TapSighash::engine();
1533        enc.input(&bytes);
1534        let hash = TapSighash::from_engine(enc);
1535        assert_eq!(expected, hash.to_byte_array());
1536    }
1537
1538    #[test]
1539    fn test_sighashes_keyspending() {
1540        // following test case has been taken from Bitcoin Core test framework
1541
1542        test_taproot_sighash(
1543            "020000000164eb050a5e3da0c2a65e4786f26d753b7bc69691fabccafb11f7acef36641f1846010000003101b2b404392a22000000000017a9147f2bde86fe78bf68a0544a4f290e12f0b7e0a08c87580200000000000017a91425d11723074ecfb96a0a83c3956bfaf362ae0c908758020000000000001600147e20f938993641de67bb0cdd71682aa34c4d29ad5802000000000000160014c64984dc8761acfa99418bd6bedc79b9287d652d72000000",
1544            "01365724000000000023542156b39dab4f8f3508e0432cfb41fab110170acaa2d4c42539cb90a4dc7c093bc500",
1545            0,
1546            "33ca0ebfb4a945eeee9569fc0f5040221275f88690b7f8592ada88ce3bdf6703",
1547            TapSighashType::Default, None, None, None
1548        );
1549
1550        test_taproot_sighash(
1551            "0200000002fff49be59befe7566050737910f6ccdc5e749c7f8860ddc140386463d88c5ad0f3000000002cf68eb4a3d67f9d4c079249f7e4f27b8854815cb1ed13842d4fbf395f9e217fd605ee24090100000065235d9203f458520000000000160014b6d48333bb13b4c644e57c43a9a26df3a44b785e58020000000000001976a914eea9461a9e1e3f765d3af3e726162e0229fe3eb688ac58020000000000001976a9143a8869c9f2b5ea1d4ff3aeeb6a8fb2fffb1ad5fe88ac0ad7125c",
1552            "02591f220000000000225120f25ad35583ea31998d968871d7de1abd2a52f6fe4178b54ea158274806ff4ece48fb310000000000225120f25ad35583ea31998d968871d7de1abd2a52f6fe4178b54ea158274806ff4ece",
1553            1,
1554            "626ab955d58c9a8a600a0c580549d06dc7da4e802eb2a531f62a588e430967a8",
1555            TapSighashType::All, None, None, None
1556        );
1557
1558        test_taproot_sighash(
1559            "0200000001350005f65aa830ced2079df348e2d8c2bdb4f10e2dde6a161d8a07b40d1ad87dae000000001611d0d603d9dc0e000000000017a914459b6d7d6bbb4d8837b4bf7e9a4556f952da2f5c8758020000000000001976a9141dd70e1299ffc2d5b51f6f87de9dfe9398c33cbb88ac58020000000000001976a9141dd70e1299ffc2d5b51f6f87de9dfe9398c33cbb88aca71c1f4f",
1560            "01c4811000000000002251201bf9297d0a2968ae6693aadd0fa514717afefd218087a239afb7418e2d22e65c",
1561            0,
1562            "dfa9437f9c9a1d1f9af271f79f2f5482f287cdb0d2e03fa92c8a9b216cc6061c",
1563            TapSighashType::AllPlusAnyoneCanPay, None, None, None
1564        );
1565
1566        test_taproot_sighash(
1567            "020000000185bed1a6da2bffbd60ec681a1bfb71c5111d6395b99b3f8b2bf90167111bcb18f5010000007c83ace802ded24a00000000001600142c4698f9f7a773866879755aa78c516fb332af8e5802000000000000160014d38639dfbac4259323b98a472405db0c461b31fa61073747",
1568            "0144c84d0000000000225120e3f2107989c88e67296ab2faca930efa2e3a5bd3ff0904835a11c9e807458621",
1569            0,
1570            "3129de36a5d05fff97ffca31eb75fcccbbbc27b3147a7a36a9e4b45d8b625067",
1571            TapSighashType::None, None, None, None
1572        );
1573
1574        test_taproot_sighash(
1575            "eb93dbb901028c8515589dac980b6e7f8e4088b77ed866ca0d6d210a7218b6fd0f6b22dd6d7300000000eb4740a9047efc0e0000000000160014913da2128d8fcf292b3691db0e187414aa1783825802000000000000160014913da2128d8fcf292b3691db0e187414aa178382580200000000000017a9143dd27f01c6f7ef9bb9159937b17f17065ed01a0c875802000000000000160014d7630e19df70ada9905ede1722b800c0005f246641000000",
1576            "013fed110000000000225120eb536ae8c33580290630fc495046e998086a64f8f33b93b07967d9029b265c55",
1577            0,
1578            "2441e8b0e063a2083ee790f14f2045022f07258ddde5ee01de543c9e789d80ae",
1579            TapSighashType::NonePlusAnyoneCanPay, None, None, None
1580        );
1581
1582        test_taproot_sighash(
1583            "02000000017836b409a5fed32211407e44b971591f2032053f14701fb5b3a30c0ff382f2cc9c0100000061ac55f60288fb5600000000001976a9144ea02f6f182b082fb6ce47e36bbde390b6a41b5088ac58020000000000001976a9144ea02f6f182b082fb6ce47e36bbde390b6a41b5088ace4000000",
1584            "01efa558000000000022512007071ea3dc7e331b0687d0193d1e6d6ed10e645ef36f10ef8831d5e522ac9e80",
1585            0,
1586            "30239345177cadd0e3ea413d49803580abb6cb27971b481b7788a78d35117a88",
1587            TapSighashType::Single, None, None, None
1588        );
1589
1590        test_taproot_sighash(
1591            "0100000001aa6deae89d5e0aaca58714fc76ef6f3c8284224888089232d4e663843ed3ab3eae010000008b6657a60450cb4c0000000000160014a3d42b5413ef0c0701c4702f3cd7d4df222c147058020000000000001976a91430b4ed8723a4ee8992aa2c8814cfe5c3ad0ab9d988ac5802000000000000160014365b1166a6ed0a5e8e9dff17a6d00bbb43454bc758020000000000001976a914bc98c51a84fe7fad5dc380eb8b39586eff47241688ac4f313247",
1592            "0107af4e00000000002251202c36d243dfc06cb56a248e62df27ecba7417307511a81ae61aa41c597a929c69",
1593            0,
1594            "bf9c83f26c6dd16449e4921f813f551c4218e86f2ec906ca8611175b41b566df",
1595            TapSighashType::SinglePlusAnyoneCanPay, None, None, None
1596        );
1597    }
1598
1599    #[test]
1600    fn test_sighashes_with_annex() {
1601        test_taproot_sighash(
1602            "0200000001df8123752e8f37d132c4e9f1ff7e4f9b986ade9211267e9ebd5fd22a5e718dec6d01000000ce4023b903cb7b23000000000017a914a18b36ea7a094db2f4940fc09edf154e86de7bd787580200000000000017a914afd0d512a2c5c2b40e25669e9cc460303c325b8b87580200000000000017a914a18b36ea7a094db2f4940fc09edf154e86de7bd787f6020000",
1603            "01ea49260000000000225120ab5e9800806bf18cb246edcf5fe63441208fe955a4b5a35bbff65f5db622a010",
1604            0,
1605            "3b003000add359a364a156e73e02846782a59d0d95ca8c4638aaad99f2ef915c",
1606            TapSighashType::SinglePlusAnyoneCanPay,
1607            Some("507b979802e62d397acb29f56743a791894b99372872fc5af06a4f6e8d242d0615cda53062bb20e6ec79756fe39183f0c128adfe85559a8fa042b042c018aa8010143799e44f0893c40e1e"),
1608            None,
1609            None,
1610        );
1611    }
1612
1613    #[test]
1614    fn test_sighashes_with_script_path() {
1615        test_taproot_sighash(
1616            "020000000189fc651483f9296b906455dd939813bf086b1bbe7c77635e157c8e14ae29062195010000004445b5c7044561320000000000160014331414dbdada7fb578f700f38fb69995fc9b5ab958020000000000001976a914268db0a8104cc6d8afd91233cc8b3d1ace8ac3ef88ac580200000000000017a914ec00dcb368d6a693e11986d265f659d2f59e8be2875802000000000000160014c715799a49a0bae3956df9c17cb4440a673ac0df6f010000",
1617            "011bec34000000000022512028055142ea437db73382e991861446040b61dd2185c4891d7daf6893d79f7182",
1618            0,
1619            "d66de5274a60400c7b08c86ba6b7f198f40660079edf53aca89d2a9501317f2e",
1620            TapSighashType::All,
1621            None,
1622            Some("20cc4e1107aea1d170c5ff5b6817e1303010049724fb3caa7941792ea9d29b3e2bacab"),
1623            None,
1624        );
1625    }
1626
1627    #[test]
1628    fn test_sighashes_with_script_path_raw_hash() {
1629        test_taproot_sighash(
1630            "020000000189fc651483f9296b906455dd939813bf086b1bbe7c77635e157c8e14ae29062195010000004445b5c7044561320000000000160014331414dbdada7fb578f700f38fb69995fc9b5ab958020000000000001976a914268db0a8104cc6d8afd91233cc8b3d1ace8ac3ef88ac580200000000000017a914ec00dcb368d6a693e11986d265f659d2f59e8be2875802000000000000160014c715799a49a0bae3956df9c17cb4440a673ac0df6f010000",
1631            "011bec34000000000022512028055142ea437db73382e991861446040b61dd2185c4891d7daf6893d79f7182",
1632            0,
1633            "d66de5274a60400c7b08c86ba6b7f198f40660079edf53aca89d2a9501317f2e",
1634            TapSighashType::All,
1635            None,
1636            None,
1637            Some("15a2530514e399f8b5cf0b3d3112cf5b289eaa3e308ba2071b58392fdc6da68a"),
1638        );
1639    }
1640
1641    #[test]
1642    fn test_sighashes_with_annex_and_script() {
1643        test_taproot_sighash(
1644            "020000000132fb72cb8fba496755f027a9743e2d698c831fdb8304e4d1a346ac92cbf51acba50100000026bdc7df044aad34000000000017a9144fa2554ed6174586854fa3bc01de58dcf33567d0875802000000000000160014950367e1e62cdf240b35b883fc2f5e39f0eb9ab95802000000000000160014950367e1e62cdf240b35b883fc2f5e39f0eb9ab958020000000000001600141b31217d48ccc8760dcc0710fade5866d628e733a02d5122",
1645            "011458360000000000225120a7baec3fb9f84614e3899fcc010c638f80f13539344120e1f4d8b68a9a011a13",
1646            0,
1647            "a0042aa434f9a75904b64043f2a283f8b4c143c7f4f7f49a6cbe5b9f745f4c15",
1648            TapSighashType::All,
1649            Some("50a6272b470e1460e3332ade7bb14b81671c564fb6245761bd5bd531394b28860e0b3808ab229fb51791fb6ae6fa82d915b2efb8f6df83ae1f5ab3db13e30928875e2a22b749d89358de481f19286cd4caa792ce27f9559082d227a731c5486882cc707f83da361c51b7aadd9a0cf68fe7480c410fa137b454482d9a1ebf0f96d760b4d61426fc109c6e8e99a508372c45caa7b000a41f8251305da3f206c1849985ba03f3d9592832b4053afbd23ab25d0465df0bc25a36c223aacf8e04ec736a418c72dc319e4da3e972e349713ca600965e7c665f2090d5a70e241ac164115a1f5639f28b1773327715ca307ace64a2de7f0e3df70a2ffee3857689f909c0dad46d8a20fa373a4cc6eed6d4c9806bf146f0d76baae1"),
1650            Some("7520ab9160dd8299dc1367659be3e8f66781fe440d52940c7f8d314a89b9f2698d406ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6ead6eadac"),
1651            None,
1652        );
1653    }
1654
1655    #[test]
1656    #[rustfmt::skip] // Allow long function call `taproot_signature_hash`.
1657    fn test_sighash_errors() {
1658        use crate::transaction::{IndexOutOfBoundsError, InputsIndexError};
1659
1660        let dumb_tx = Transaction {
1661            version: transaction::Version::TWO,
1662            lock_time: absolute::LockTime::ZERO,
1663            input: vec![TxIn::default()],
1664            output: vec![],
1665        };
1666        let mut c = SighashCache::new(&dumb_tx);
1667
1668        // 1.29 fixes
1669        let empty_vec = vec![];
1670        let empty_prevouts : Prevouts<TxOut> = Prevouts::All(&empty_vec);
1671        assert_eq!(
1672            c.taproot_signature_hash(0, &empty_prevouts, None, None, TapSighashType::All),
1673            Err(TaprootError::PrevoutsSize(PrevoutsSizeError))
1674        );
1675        let two = vec![TxOut::NULL, TxOut::NULL];
1676        let too_many_prevouts = Prevouts::All(&two);
1677        assert_eq!(
1678            c.taproot_signature_hash(0, &too_many_prevouts, None, None, TapSighashType::All),
1679            Err(TaprootError::PrevoutsSize(PrevoutsSizeError))
1680        );
1681        let tx_out = TxOut::NULL;
1682        let prevout = Prevouts::One(1, &tx_out);
1683        assert_eq!(
1684            c.taproot_signature_hash(0, &prevout, None, None, TapSighashType::All),
1685            Err(TaprootError::PrevoutsKind(PrevoutsKindError))
1686        );
1687        assert_eq!(
1688            c.taproot_signature_hash(0, &prevout, None, None, TapSighashType::AllPlusAnyoneCanPay),
1689            Err(TaprootError::PrevoutsIndex(PrevoutsIndexError::InvalidOneIndex))
1690        );
1691        assert_eq!(
1692            c.taproot_signature_hash(10, &prevout, None, None, TapSighashType::AllPlusAnyoneCanPay),
1693            Err(InputsIndexError(IndexOutOfBoundsError {
1694                index: 10,
1695                length: 1
1696            }).into())
1697        );
1698        let prevout = Prevouts::One(0, &tx_out);
1699        assert_eq!(
1700            c.taproot_signature_hash(0, &prevout, None, None, TapSighashType::SinglePlusAnyoneCanPay),
1701            Err(TaprootError::SingleMissingOutput(SingleMissingOutputError {
1702                input_index: 0,
1703                outputs_length: 0
1704            }))
1705        );
1706        assert_eq!(
1707            c.legacy_signature_hash(10, Script::new(), 0u32),
1708            Err(InputsIndexError(IndexOutOfBoundsError {
1709                index: 10,
1710                length: 1
1711            }))
1712        );
1713    }
1714
1715    #[test]
1716    fn test_annex_errors() {
1717        assert_eq!(Annex::new(&[]), Err(AnnexError::Empty));
1718        assert_eq!(Annex::new(&[0x51]), Err(AnnexError::IncorrectPrefix(0x51)));
1719        assert_eq!(Annex::new(&[0x51, 0x50]), Err(AnnexError::IncorrectPrefix(0x51)));
1720    }
1721
1722    #[allow(clippy::too_many_arguments)]
1723    fn test_taproot_sighash(
1724        tx_hex: &str,
1725        prevout_hex: &str,
1726        input_index: usize,
1727        expected_hash: &str,
1728        sighash_type: TapSighashType,
1729        annex_hex: Option<&str>,
1730        script_hex: Option<&str>,
1731        script_leaf_hash: Option<&str>,
1732    ) {
1733        let tx_bytes = Vec::from_hex(tx_hex).unwrap();
1734        let tx: Transaction = deserialize(&tx_bytes).unwrap();
1735        let prevout_bytes = Vec::from_hex(prevout_hex).unwrap();
1736        let prevouts: Vec<TxOut> = deserialize(&prevout_bytes).unwrap();
1737        let annex_inner;
1738        let annex = match annex_hex {
1739            Some(annex_hex) => {
1740                annex_inner = Vec::from_hex(annex_hex).unwrap();
1741                Some(Annex::new(&annex_inner).unwrap())
1742            }
1743            None => None,
1744        };
1745
1746        let leaf_hash = match (script_hex, script_leaf_hash) {
1747            (Some(script_hex), _) => {
1748                let script_inner = ScriptBuf::from_hex(script_hex).unwrap();
1749                Some(ScriptPath::with_defaults(&script_inner).leaf_hash())
1750            }
1751            (_, Some(script_leaf_hash)) => Some(script_leaf_hash.parse::<TapLeafHash>().unwrap()),
1752            _ => None,
1753        };
1754        // All our tests use the default `0xFFFFFFFF` codeseparator value
1755        let leaf_hash = leaf_hash.map(|lh| (lh, 0xFFFFFFFF));
1756
1757        let prevouts = if sighash_type.split_anyonecanpay_flag().1 && tx_bytes[0] % 2 == 0 {
1758            // for anyonecanpay the `Prevouts::All` variant is good anyway, but sometimes we want to
1759            // test other codepaths
1760            Prevouts::One(input_index, prevouts[input_index].clone())
1761        } else {
1762            Prevouts::All(&prevouts)
1763        };
1764
1765        let mut sighash_cache = SighashCache::new(&tx);
1766
1767        let hash = sighash_cache
1768            .taproot_signature_hash(input_index, &prevouts, annex, leaf_hash, sighash_type)
1769            .unwrap();
1770        let expected = Vec::from_hex(expected_hash).unwrap();
1771        assert_eq!(expected, hash.to_byte_array());
1772    }
1773
1774    #[cfg(feature = "serde")]
1775    #[test]
1776    fn bip_341_sighash_tests() {
1777        use hex::DisplayHex;
1778
1779        fn sighash_deser_numeric<'de, D>(deserializer: D) -> Result<TapSighashType, D::Error>
1780        where
1781            D: actual_serde::Deserializer<'de>,
1782        {
1783            use actual_serde::de::{Deserialize, Error, Unexpected};
1784
1785            let raw = u8::deserialize(deserializer)?;
1786            TapSighashType::from_consensus_u8(raw).map_err(|_| {
1787                D::Error::invalid_value(
1788                    Unexpected::Unsigned(raw.into()),
1789                    &"number in range 0-3 or 0x81-0x83",
1790                )
1791            })
1792        }
1793
1794        use secp256k1::{SecretKey, XOnlyPublicKey};
1795
1796        use crate::consensus::serde as con_serde;
1797        use crate::taproot::{TapNodeHash, TapTweakHash};
1798
1799        #[derive(serde::Deserialize)]
1800        #[serde(crate = "actual_serde")]
1801        struct UtxoSpent {
1802            #[serde(rename = "scriptPubKey")]
1803            script_pubkey: ScriptBuf,
1804            #[serde(rename = "amountSats")]
1805            value: Amount,
1806        }
1807
1808        #[derive(serde::Deserialize)]
1809        #[serde(rename_all = "camelCase")]
1810        #[serde(crate = "actual_serde")]
1811        struct KpsGiven {
1812            #[serde(with = "con_serde::With::<con_serde::Hex>")]
1813            raw_unsigned_tx: Transaction,
1814            utxos_spent: Vec<UtxoSpent>,
1815        }
1816
1817        #[derive(serde::Deserialize)]
1818        #[serde(rename_all = "camelCase")]
1819        #[serde(crate = "actual_serde")]
1820        struct KpsIntermediary {
1821            hash_prevouts: sha256::Hash,
1822            hash_outputs: sha256::Hash,
1823            hash_sequences: sha256::Hash,
1824            hash_amounts: sha256::Hash,
1825            hash_script_pubkeys: sha256::Hash,
1826        }
1827
1828        #[derive(serde::Deserialize)]
1829        #[serde(rename_all = "camelCase")]
1830        #[serde(crate = "actual_serde")]
1831        struct KpsInputSpendingGiven {
1832            txin_index: usize,
1833            internal_privkey: SecretKey,
1834            merkle_root: Option<TapNodeHash>,
1835            #[serde(deserialize_with = "sighash_deser_numeric")]
1836            hash_type: TapSighashType,
1837        }
1838
1839        #[derive(serde::Deserialize)]
1840        #[serde(rename_all = "camelCase")]
1841        #[serde(crate = "actual_serde")]
1842        struct KpsInputSpendingIntermediary {
1843            internal_pubkey: XOnlyPublicKey,
1844            tweak: TapTweakHash,
1845            tweaked_privkey: SecretKey,
1846            sig_msg: String,
1847            //precomputed_used: Vec<String>, // unused
1848            sig_hash: TapSighash,
1849        }
1850
1851        #[derive(serde::Deserialize)]
1852        #[serde(rename_all = "camelCase")]
1853        #[serde(crate = "actual_serde")]
1854        struct KpsInputSpendingExpected {
1855            witness: Vec<String>,
1856        }
1857
1858        #[derive(serde::Deserialize)]
1859        #[serde(rename_all = "camelCase")]
1860        #[serde(crate = "actual_serde")]
1861        struct KpsInputSpending {
1862            given: KpsInputSpendingGiven,
1863            intermediary: KpsInputSpendingIntermediary,
1864            expected: KpsInputSpendingExpected,
1865            // auxiliary: KpsAuxiliary, //unused
1866        }
1867
1868        #[derive(serde::Deserialize)]
1869        #[serde(rename_all = "camelCase")]
1870        #[serde(crate = "actual_serde")]
1871        struct KeyPathSpending {
1872            given: KpsGiven,
1873            intermediary: KpsIntermediary,
1874            input_spending: Vec<KpsInputSpending>,
1875        }
1876
1877        #[derive(serde::Deserialize)]
1878        #[serde(rename_all = "camelCase")]
1879        #[serde(crate = "actual_serde")]
1880        struct TestData {
1881            version: u64,
1882            key_path_spending: Vec<KeyPathSpending>,
1883            //script_pubkey: Vec<ScriptPubKey>, // unused
1884        }
1885
1886        let json_str = include_str!("../../tests/data/bip341_tests.json");
1887        let mut data =
1888            serde_json::from_str::<TestData>(json_str).expect("JSON was not well-formatted");
1889
1890        assert_eq!(data.version, 1u64);
1891        let secp = &secp256k1::Secp256k1::new();
1892        let key_path = data.key_path_spending.remove(0);
1893
1894        let raw_unsigned_tx = key_path.given.raw_unsigned_tx;
1895        let utxos = key_path
1896            .given
1897            .utxos_spent
1898            .into_iter()
1899            .map(|txo| TxOut { value: txo.value, script_pubkey: txo.script_pubkey })
1900            .collect::<Vec<_>>();
1901
1902        // Test intermediary
1903        let mut cache = SighashCache::new(&raw_unsigned_tx);
1904
1905        let expected = key_path.intermediary;
1906        // Compute all caches
1907        assert_eq!(expected.hash_amounts, cache.taproot_cache(&utxos).amounts);
1908        assert_eq!(expected.hash_outputs, cache.common_cache().outputs);
1909        assert_eq!(expected.hash_prevouts, cache.common_cache().prevouts);
1910        assert_eq!(expected.hash_script_pubkeys, cache.taproot_cache(&utxos).script_pubkeys);
1911        assert_eq!(expected.hash_sequences, cache.common_cache().sequences);
1912
1913        for mut inp in key_path.input_spending {
1914            let tx_ind = inp.given.txin_index;
1915            let internal_priv_key = inp.given.internal_privkey;
1916            let merkle_root = inp.given.merkle_root;
1917            let hash_ty = inp.given.hash_type;
1918
1919            let expected = inp.intermediary;
1920            let sig_str = inp.expected.witness.remove(0);
1921            let (expected_key_spend_sig, expected_hash_ty) = if sig_str.len() == 128 {
1922                (
1923                    secp256k1::schnorr::Signature::from_str(&sig_str).unwrap(),
1924                    TapSighashType::Default,
1925                )
1926            } else {
1927                let hash_ty = u8::from_str_radix(&sig_str[128..130], 16).unwrap();
1928                let hash_ty = TapSighashType::from_consensus_u8(hash_ty).unwrap();
1929                (secp256k1::schnorr::Signature::from_str(&sig_str[..128]).unwrap(), hash_ty)
1930            };
1931
1932            // tests
1933            let keypair = secp256k1::Keypair::from_secret_key(secp, &internal_priv_key);
1934            let (internal_key, _parity) = XOnlyPublicKey::from_keypair(&keypair);
1935            let tweak = TapTweakHash::from_key_and_tweak(internal_key, merkle_root);
1936            let tweaked_keypair = keypair.add_xonly_tweak(secp, &tweak.to_scalar()).unwrap();
1937            let mut sig_msg = Vec::new();
1938            cache
1939                .taproot_encode_signing_data_to(
1940                    &mut sig_msg,
1941                    tx_ind,
1942                    &Prevouts::All(&utxos),
1943                    None,
1944                    None,
1945                    hash_ty,
1946                )
1947                .unwrap();
1948            let sighash = cache
1949                .taproot_signature_hash(tx_ind, &Prevouts::All(&utxos), None, None, hash_ty)
1950                .unwrap();
1951
1952            let msg = secp256k1::Message::from(sighash);
1953            let key_spend_sig = secp.sign_schnorr_with_aux_rand(&msg, &tweaked_keypair, &[0u8; 32]);
1954
1955            assert_eq!(expected.internal_pubkey, internal_key);
1956            assert_eq!(expected.tweak, tweak);
1957            assert_eq!(expected.sig_msg, sig_msg.to_lower_hex_string());
1958            assert_eq!(expected.sig_hash, sighash);
1959            assert_eq!(expected_hash_ty, hash_ty);
1960            assert_eq!(expected_key_spend_sig, key_spend_sig);
1961
1962            let tweaked_priv_key = SecretKey::from_keypair(&tweaked_keypair);
1963            assert_eq!(expected.tweaked_privkey, tweaked_priv_key);
1964        }
1965    }
1966
1967    #[test]
1968    fn sighashtype_fromstr_display() {
1969        let sighashtypes = vec![
1970            ("SIGHASH_DEFAULT", TapSighashType::Default),
1971            ("SIGHASH_ALL", TapSighashType::All),
1972            ("SIGHASH_NONE", TapSighashType::None),
1973            ("SIGHASH_SINGLE", TapSighashType::Single),
1974            ("SIGHASH_ALL|SIGHASH_ANYONECANPAY", TapSighashType::AllPlusAnyoneCanPay),
1975            ("SIGHASH_NONE|SIGHASH_ANYONECANPAY", TapSighashType::NonePlusAnyoneCanPay),
1976            ("SIGHASH_SINGLE|SIGHASH_ANYONECANPAY", TapSighashType::SinglePlusAnyoneCanPay),
1977        ];
1978        for (s, sht) in sighashtypes {
1979            assert_eq!(sht.to_string(), s);
1980            assert_eq!(TapSighashType::from_str(s).unwrap(), sht);
1981        }
1982        let sht_mistakes = vec![
1983            "SIGHASH_ALL | SIGHASH_ANYONECANPAY",
1984            "SIGHASH_NONE |SIGHASH_ANYONECANPAY",
1985            "SIGHASH_SINGLE| SIGHASH_ANYONECANPAY",
1986            "SIGHASH_ALL SIGHASH_ANYONECANPAY",
1987            "SIGHASH_NONE |",
1988            "SIGHASH_SIGNLE",
1989            "DEFAULT",
1990            "ALL",
1991            "sighash_none",
1992            "Sighash_none",
1993            "SigHash_None",
1994            "SigHash_NONE",
1995        ];
1996        for s in sht_mistakes {
1997            assert_eq!(
1998                TapSighashType::from_str(s).unwrap_err().to_string(),
1999                format!("unrecognized SIGHASH string '{}'", s)
2000            );
2001        }
2002    }
2003
2004    #[test]
2005    fn bip143_p2wpkh() {
2006        let tx = deserialize::<Transaction>(
2007            &hex!(
2008                "0100000002fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433541db4e4ad969f000000\
2009                0000eeffffffef51e1b804cc89d182d279655c3aa89e815b1b309fe287d9b2b55d57b90ec68a01000000\
2010                00ffffffff02202cb206000000001976a9148280b37df378db99f66f85c95a783a76ac7a6d5988ac9093\
2011                510d000000001976a9143bde42dbee7e4dbe6a21b2d50ce2f0167faa815988ac11000000"
2012            ),
2013        ).unwrap();
2014
2015        let spk = ScriptBuf::from_hex("00141d0f172a0ecb48aee1be1f2687d2963ae33f71a1").unwrap();
2016        let value = Amount::from_sat(600_000_000);
2017
2018        let mut cache = SighashCache::new(&tx);
2019        assert_eq!(
2020            cache.p2wpkh_signature_hash(1, &spk, value, EcdsaSighashType::All).unwrap(),
2021            "c37af31116d1b27caf68aae9e3ac82f1477929014d5b917657d0eb49478cb670"
2022                .parse::<SegwitV0Sighash>()
2023                .unwrap(),
2024        );
2025
2026        let cache = cache.segwit_cache();
2027        // Parse hex into Vec because BIP143 test vector displays forwards but our sha256d::Hash displays backwards.
2028        assert_eq!(
2029            cache.prevouts.as_byte_array(),
2030            &Vec::from_hex("96b827c8483d4e9b96712b6713a7b68d6e8003a781feba36c31143470b4efd37")
2031                .unwrap()[..],
2032        );
2033        assert_eq!(
2034            cache.sequences.as_byte_array(),
2035            &Vec::from_hex("52b0a642eea2fb7ae638c36f6252b6750293dbe574a806984b8e4d8548339a3b")
2036                .unwrap()[..],
2037        );
2038        assert_eq!(
2039            cache.outputs.as_byte_array(),
2040            &Vec::from_hex("863ef3e1a92afbfdb97f31ad0fc7683ee943e9abcf2501590ff8f6551f47e5e5")
2041                .unwrap()[..],
2042        );
2043    }
2044
2045    #[test]
2046    fn bip143_p2wpkh_nested_in_p2sh() {
2047        let tx = deserialize::<Transaction>(
2048            &hex!(
2049                "0100000001db6b1b20aa0fd7b23880be2ecbd4a98130974cf4748fb66092ac4d3ceb1a5477010000\
2050                0000feffffff02b8b4eb0b000000001976a914a457b684d7f0d539a46a45bbc043f35b59d0d96388ac00\
2051                08af2f000000001976a914fd270b1ee6abcaea97fea7ad0402e8bd8ad6d77c88ac92040000"
2052            ),
2053        ).unwrap();
2054
2055        let redeem_script =
2056            ScriptBuf::from_hex("001479091972186c449eb1ded22b78e40d009bdf0089").unwrap();
2057        let value = Amount::from_sat(1_000_000_000);
2058
2059        let mut cache = SighashCache::new(&tx);
2060        assert_eq!(
2061            cache.p2wpkh_signature_hash(0, &redeem_script, value, EcdsaSighashType::All).unwrap(),
2062            "64f3b0f4dd2bb3aa1ce8566d220cc74dda9df97d8490cc81d89d735c92e59fb6"
2063                .parse::<SegwitV0Sighash>()
2064                .unwrap(),
2065        );
2066
2067        let cache = cache.segwit_cache();
2068        // Parse hex into Vec because BIP143 test vector displays forwards but our sha256d::Hash displays backwards.
2069        assert_eq!(
2070            cache.prevouts.as_byte_array(),
2071            &Vec::from_hex("b0287b4a252ac05af83d2dcef00ba313af78a3e9c329afa216eb3aa2a7b4613a")
2072                .unwrap()[..],
2073        );
2074        assert_eq!(
2075            cache.sequences.as_byte_array(),
2076            &Vec::from_hex("18606b350cd8bf565266bc352f0caddcf01e8fa789dd8a15386327cf8cabe198")
2077                .unwrap()[..],
2078        );
2079        assert_eq!(
2080            cache.outputs.as_byte_array(),
2081            &Vec::from_hex("de984f44532e2173ca0d64314fcefe6d30da6f8cf27bafa706da61df8a226c83")
2082                .unwrap()[..],
2083        );
2084    }
2085
2086    // Note, if you are looking at the test vectors in BIP-143 and wondering why there is a `cf`
2087    // prepended to all the script_code hex it is the length byte, it gets added when we consensus
2088    // encode a script.
2089    fn bip143_p2wsh_nested_in_p2sh_data() -> (Transaction, ScriptBuf, Amount) {
2090        let tx = deserialize::<Transaction>(&hex!(
2091            "010000000136641869ca081e70f394c6948e8af409e18b619df2ed74aa106c1ca29787b96e0100000000\
2092             ffffffff0200e9a435000000001976a914389ffce9cd9ae88dcc0631e88a821ffdbe9bfe2688acc0832f\
2093             05000000001976a9147480a33f950689af511e6e84c138dbbd3c3ee41588ac00000000"
2094        ))
2095        .unwrap();
2096
2097        let witness_script = ScriptBuf::from_hex(
2098            "56210307b8ae49ac90a048e9b53357a2354b3334e9c8bee813ecb98e99a7e07e8c3ba32103b28f0c28\
2099             bfab54554ae8c658ac5c3e0ce6e79ad336331f78c428dd43eea8449b21034b8113d703413d57761b8b\
2100             9781957b8c0ac1dfe69f492580ca4195f50376ba4a21033400f6afecb833092a9a21cfdf1ed1376e58\
2101             c5d1f47de74683123987e967a8f42103a6d48b1131e94ba04d9737d61acdaa1322008af9602b3b1486\
2102             2c07a1789aac162102d8b661b0b3302ee2f162b09e07a55ad5dfbe673a9f01d9f0c19617681024306b\
2103             56ae",
2104        )
2105        .unwrap();
2106
2107        let value = Amount::from_sat(987_654_321);
2108        (tx, witness_script, value)
2109    }
2110
2111    #[test]
2112    fn bip143_p2wsh_nested_in_p2sh_sighash_type_all() {
2113        let (tx, witness_script, value) = bip143_p2wsh_nested_in_p2sh_data();
2114        let mut cache = SighashCache::new(&tx);
2115        assert_eq!(
2116            cache.p2wsh_signature_hash(0, &witness_script, value, EcdsaSighashType::All).unwrap(),
2117            "185c0be5263dce5b4bb50a047973c1b6272bfbd0103a89444597dc40b248ee7c"
2118                .parse::<SegwitV0Sighash>()
2119                .unwrap(),
2120        );
2121
2122        // We only test the cache intermediate values for `EcdsaSighashType::All` because they are
2123        // not the same as the BIP test vectors for all the rest of the sighash types. These fields
2124        // are private so it does not effect sighash cache usage, we do test against the produced
2125        // sighash for all sighash types.
2126
2127        let cache = cache.segwit_cache();
2128        // Parse hex into Vec because BIP143 test vector displays forwards but our sha256d::Hash displays backwards.
2129        assert_eq!(
2130            cache.prevouts.as_byte_array(),
2131            &Vec::from_hex("74afdc312af5183c4198a40ca3c1a275b485496dd3929bca388c4b5e31f7aaa0")
2132                .unwrap()[..],
2133        );
2134        assert_eq!(
2135            cache.sequences.as_byte_array(),
2136            &Vec::from_hex("3bb13029ce7b1f559ef5e747fcac439f1455a2ec7c5f09b72290795e70665044")
2137                .unwrap()[..],
2138        );
2139        assert_eq!(
2140            cache.outputs.as_byte_array(),
2141            &Vec::from_hex("bc4d309071414bed932f98832b27b4d76dad7e6c1346f487a8fdbb8eb90307cc")
2142                .unwrap()[..],
2143        );
2144    }
2145
2146    macro_rules! check_bip143_p2wsh_nested_in_p2sh {
2147        ($($test_name:ident, $sighash_type:ident, $sighash:literal);* $(;)?) => {
2148            $(
2149                #[test]
2150                fn $test_name() {
2151                    use EcdsaSighashType::*;
2152
2153                    let (tx, witness_script, value) = bip143_p2wsh_nested_in_p2sh_data();
2154                    let mut cache = SighashCache::new(&tx);
2155                    assert_eq!(
2156                        cache
2157                            .p2wsh_signature_hash(0, &witness_script, value, $sighash_type)
2158                            .unwrap(),
2159                        $sighash
2160                            .parse::<SegwitV0Sighash>()
2161                            .unwrap(),
2162                    );
2163                }
2164            )*
2165        }
2166    }
2167    check_bip143_p2wsh_nested_in_p2sh! {
2168        // EcdsaSighashType::All tested above.
2169        bip143_p2wsh_nested_in_p2sh_sighash_none, None, "e9733bc60ea13c95c6527066bb975a2ff29a925e80aa14c213f686cbae5d2f36";
2170        bip143_p2wsh_nested_in_p2sh_sighash_single, Single, "1e1f1c303dc025bd664acb72e583e933fae4cff9148bf78c157d1e8f78530aea";
2171        bip143_p2wsh_nested_in_p2sh_sighash_all_plus_anyonecanpay, AllPlusAnyoneCanPay, "2a67f03e63a6a422125878b40b82da593be8d4efaafe88ee528af6e5a9955c6e";
2172        bip143_p2wsh_nested_in_p2sh_sighash_none_plus_anyonecanpay, NonePlusAnyoneCanPay, "781ba15f3779d5542ce8ecb5c18716733a5ee42a6f51488ec96154934e2c890a";
2173        bip143_p2wsh_nested_in_p2sh_sighash_single_plus_anyonecanpay, SinglePlusAnyoneCanPay, "511e8e52ed574121fc1b654970395502128263f62662e076dc6baf05c2e6a99b";
2174    }
2175}