Skip to main content

bitcoin_rs_script/
sighash_cache.rs

1use bitcoin::sighash::{
2    EcdsaSighashType, LegacySighash, P2wpkhError, Prevouts, SegwitV0Sighash, TapSighash,
3    TapSighashType, TaprootError,
4};
5use bitcoin::{Amount, Script, TapLeafHash, TxOut};
6use bitcoin_rs_primitives::Tx;
7
8/// Public signature-hash cache wrapper for bitcoin-rs script callers.
9#[derive(Debug)]
10pub struct SigHashCache<'a> {
11    inner: bitcoin::sighash::SighashCache<&'a bitcoin::Transaction>,
12}
13
14impl<'a> SigHashCache<'a> {
15    /// Creates a cache for a transaction.
16    #[must_use]
17    pub fn new(tx: &'a Tx) -> Self {
18        Self {
19            inner: bitcoin::sighash::SighashCache::new(&tx.0),
20        }
21    }
22
23    /// Computes a legacy signature hash.
24    pub fn legacy_signature_hash(
25        &self,
26        input_index: usize,
27        script_pubkey: &Script,
28        sighash_type: u32,
29    ) -> Result<LegacySighash, bitcoin::transaction::InputsIndexError> {
30        self.inner
31            .legacy_signature_hash(input_index, script_pubkey, sighash_type)
32    }
33
34    /// Computes a BIP143 P2WPKH signature hash.
35    pub fn p2wpkh_signature_hash(
36        &mut self,
37        input_index: usize,
38        script_pubkey: &Script,
39        value: Amount,
40        sighash_type: EcdsaSighashType,
41    ) -> Result<SegwitV0Sighash, P2wpkhError> {
42        self.inner
43            .p2wpkh_signature_hash(input_index, script_pubkey, value, sighash_type)
44    }
45
46    /// Computes a BIP143 P2WSH signature hash.
47    pub fn p2wsh_signature_hash(
48        &mut self,
49        input_index: usize,
50        witness_script: &Script,
51        value: Amount,
52        sighash_type: EcdsaSighashType,
53    ) -> Result<SegwitV0Sighash, bitcoin::transaction::InputsIndexError> {
54        self.inner
55            .p2wsh_signature_hash(input_index, witness_script, value, sighash_type)
56    }
57
58    /// Computes a BIP341 taproot key-path signature hash.
59    pub fn taproot_key_spend_signature_hash<T: std::borrow::Borrow<TxOut>>(
60        &mut self,
61        input_index: usize,
62        prevouts: &Prevouts<T>,
63        sighash_type: TapSighashType,
64    ) -> Result<TapSighash, TaprootError> {
65        self.inner
66            .taproot_key_spend_signature_hash(input_index, prevouts, sighash_type)
67    }
68
69    /// Computes a BIP342 tapscript signature hash.
70    pub fn taproot_script_spend_signature_hash<S, T>(
71        &mut self,
72        input_index: usize,
73        prevouts: &Prevouts<T>,
74        leaf_hash: S,
75        sighash_type: TapSighashType,
76    ) -> Result<TapSighash, TaprootError>
77    where
78        S: Into<TapLeafHash>,
79        T: std::borrow::Borrow<TxOut>,
80    {
81        self.inner.taproot_script_spend_signature_hash(
82            input_index,
83            prevouts,
84            leaf_hash,
85            sighash_type,
86        )
87    }
88}