diff --git a/src/blockdata/transaction.rs b/src/blockdata/transaction.rs index 7beac7f5..f11c4f8c 100644 --- a/src/blockdata/transaction.rs +++ b/src/blockdata/transaction.rs @@ -586,7 +586,7 @@ pub enum SigHashType { impl SigHashType { /// Break the sighash flag into the "real" sighash flag and the ANYONECANPAY boolean - fn split_anyonecanpay_flag(&self) -> (SigHashType, bool) { + pub(crate) fn split_anyonecanpay_flag(&self) -> (SigHashType, bool) { match *self { SigHashType::All => (SigHashType::All, false), SigHashType::None => (SigHashType::None, false), diff --git a/src/util/bip143.rs b/src/util/bip143.rs index 742a53f2..23a3fd97 100644 --- a/src/util/bip143.rs +++ b/src/util/bip143.rs @@ -19,10 +19,10 @@ //! signatures, which are placed in the scriptSig. //! -use hashes::Hash; +use hashes::{Hash, sha256d}; use hash_types::SigHash; use blockdata::script::Script; -use blockdata::transaction::{Transaction, TxIn}; +use blockdata::transaction::{Transaction, TxIn, SigHashType}; use consensus::encode::Encodable; /// Parts of a sighash which are common across inputs or signatures, and which are @@ -99,6 +99,120 @@ impl SighashComponents { } } +/// A replacement for SigHashComponents which supports all sighash modes +pub struct SigHashCache<'a> { + /// Access to transaction required for various introspection + tx: &'a Transaction, + /// Hash of all the previous outputs, computed as required + hash_prevouts: Option, + /// Hash of all the input sequence nos, computed as required + hash_sequence: Option, + /// Hash of all the outputs in this transaction, computed as required + hash_outputs: Option, +} + +impl<'a> SigHashCache<'a> { + /// Compute the sighash components from an unsigned transaction and auxiliary + /// in a lazy manner when required. + /// For the generated sighashes to be valid, no fields in the transaction may change except for + /// script_sig and witnesses. + pub fn new(tx: &Transaction) -> SigHashCache { + SigHashCache { + tx: tx, + hash_prevouts: None, + hash_sequence: None, + hash_outputs: None, + } + } + + /// Calculate hash for prevouts + pub fn hash_prevouts(&mut self) -> sha256d::Hash { + let hash_prevout = &mut self.hash_prevouts; + let input = &self.tx.input; + *hash_prevout.get_or_insert_with(|| { + let mut enc = sha256d::Hash::engine(); + for txin in input { + txin.previous_output.consensus_encode(&mut enc).unwrap(); + } + sha256d::Hash::from_engine(enc) + }) + } + + /// Calculate hash for input sequence values + pub fn hash_sequence(&mut self) -> sha256d::Hash { + let hash_sequence = &mut self.hash_sequence; + let input = &self.tx.input; + *hash_sequence.get_or_insert_with(|| { + let mut enc = sha256d::Hash::engine(); + for txin in input { + txin.sequence.consensus_encode(&mut enc).unwrap(); + } + sha256d::Hash::from_engine(enc) + }) + } + + /// Calculate hash for outputs + pub fn hash_outputs(&mut self) -> sha256d::Hash { + let hash_output = &mut self.hash_outputs; + let output = &self.tx.output; + *hash_output.get_or_insert_with(|| { + let mut enc = sha256d::Hash::engine(); + for txout in output { + txout.consensus_encode(&mut enc).unwrap(); + } + sha256d::Hash::from_engine(enc) + }) + } + + /// Compute the BIP143 sighash for any flag type. See SighashComponents::sighash_all simpler + /// API for the most common case + pub fn signature_hash(&mut self, input_index: usize, script_code: &Script, value: u64, sighash_type: SigHashType) -> SigHash { + + let zero_hash = sha256d::Hash::default(); + + let (sighash, anyone_can_pay) = sighash_type.split_anyonecanpay_flag(); + + let mut enc = SigHash::engine(); + self.tx.version.consensus_encode(&mut enc).unwrap(); + + if !anyone_can_pay { + self.hash_prevouts().consensus_encode(&mut enc).unwrap(); + } else { + zero_hash.consensus_encode(&mut enc).unwrap(); + } + + if !anyone_can_pay && sighash != SigHashType::Single && sighash != SigHashType::None { + self.hash_sequence().consensus_encode(&mut enc).unwrap(); + } else { + zero_hash.consensus_encode(&mut enc).unwrap(); + } + + let txin = &self.tx.input[input_index]; + + txin + .previous_output + .consensus_encode(&mut enc) + .unwrap(); + script_code.consensus_encode(&mut enc).unwrap(); + value.consensus_encode(&mut enc).unwrap(); + txin.sequence.consensus_encode(&mut enc).unwrap(); + + if sighash != SigHashType::Single && sighash != SigHashType::None { + self.hash_outputs().consensus_encode(&mut enc).unwrap(); + } else if sighash == SigHashType::Single && input_index < self.tx.output.len() { + let mut single_enc = SigHash::engine(); + self.tx.output[input_index].consensus_encode(&mut single_enc).unwrap(); + SigHash::from_engine(single_enc).consensus_encode(&mut enc).unwrap(); + } else { + zero_hash.consensus_encode(&mut enc).unwrap(); + } + + self.tx.lock_time.consensus_encode(&mut enc).unwrap(); + sighash_type.as_u32().consensus_encode(&mut enc).unwrap(); + SigHash::from_engine(enc) + } +} + #[cfg(test)] mod tests { use hash_types::SigHash; @@ -120,6 +234,17 @@ mod tests { witness_script } + fn run_test_sighash_bip143(tx: &str, script: &str, input_index: usize, value: u64, hash_type: u32, expected_result: &str) { + let tx: Transaction = deserialize(&Vec::::from_hex(tx).unwrap()[..]).unwrap(); + let script = Script::from(Vec::::from_hex(script).unwrap()); + let raw_expected = SigHash::from_hex(expected_result).unwrap(); + let expected_result = SigHash::from_slice(&raw_expected[..]).unwrap(); + let mut cache = SigHashCache::new(&tx); + let sighash_type = SigHashType::from_u32(hash_type); + let actual_result = cache.signature_hash(input_index, &script, value, sighash_type); + assert_eq!(actual_result, expected_result); + } + #[test] fn bip143_p2wpkh() { let tx = deserialize::( @@ -237,4 +362,15 @@ mod tests { hex_hash!(SigHash, "185c0be5263dce5b4bb50a047973c1b6272bfbd0103a89444597dc40b248ee7c") ); } + #[test] + fn bip143_sighash_flags() { + // All examples generated via Bitcoin Core RPC using signrawtransactionwithwallet + // with additional debug printing + run_test_sighash_bip143("0200000001cf309ee0839b8aaa3fbc84f8bd32e9c6357e99b49bf6a3af90308c68e762f1d70100000000feffffff0288528c61000000001600146e8d9e07c543a309dcdeba8b50a14a991a658c5be0aebb0000000000160014698d8419804a5d5994704d47947889ff7620c004db000000", "76a91462744660c6b5133ddeaacbc57d2dc2d7b14d0b0688ac", 0, 1648888940, 0x01, "0a1bc2758dbb5b3a56646f8cafbf63f410cc62b77a482f8b87552683300a7711"); + run_test_sighash_bip143("0200000001cf309ee0839b8aaa3fbc84f8bd32e9c6357e99b49bf6a3af90308c68e762f1d70100000000feffffff0288528c61000000001600146e8d9e07c543a309dcdeba8b50a14a991a658c5be0aebb0000000000160014698d8419804a5d5994704d47947889ff7620c004db000000", "76a91462744660c6b5133ddeaacbc57d2dc2d7b14d0b0688ac", 0, 1648888940, 0x02, "3e275ac8b084f79f756dcd535bffb615cc94a685eefa244d9031eaf22e4cec12"); + run_test_sighash_bip143("0200000001cf309ee0839b8aaa3fbc84f8bd32e9c6357e99b49bf6a3af90308c68e762f1d70100000000feffffff0288528c61000000001600146e8d9e07c543a309dcdeba8b50a14a991a658c5be0aebb0000000000160014698d8419804a5d5994704d47947889ff7620c004db000000", "76a91462744660c6b5133ddeaacbc57d2dc2d7b14d0b0688ac", 0, 1648888940, 0x03, "191a08165ffacc3ea55753b225f323c35fd00d9cc0268081a4a501921fc6ec14"); + run_test_sighash_bip143("0200000001cf309ee0839b8aaa3fbc84f8bd32e9c6357e99b49bf6a3af90308c68e762f1d70100000000feffffff0288528c61000000001600146e8d9e07c543a309dcdeba8b50a14a991a658c5be0aebb0000000000160014698d8419804a5d5994704d47947889ff7620c004db000000", "76a91462744660c6b5133ddeaacbc57d2dc2d7b14d0b0688ac", 0, 1648888940, 0x81, "4b6b612530f94470bbbdef18f57f2990d56b239f41b8728b9a49dc8121de4559"); + run_test_sighash_bip143("0200000001cf309ee0839b8aaa3fbc84f8bd32e9c6357e99b49bf6a3af90308c68e762f1d70100000000feffffff0288528c61000000001600146e8d9e07c543a309dcdeba8b50a14a991a658c5be0aebb0000000000160014698d8419804a5d5994704d47947889ff7620c004db000000", "76a91462744660c6b5133ddeaacbc57d2dc2d7b14d0b0688ac", 0, 1648888940, 0x82, "a7e916d3acd4bb97a21e6793828279aeab02162adf8099ea4f309af81f3d5adb"); + run_test_sighash_bip143("0200000001cf309ee0839b8aaa3fbc84f8bd32e9c6357e99b49bf6a3af90308c68e762f1d70100000000feffffff0288528c61000000001600146e8d9e07c543a309dcdeba8b50a14a991a658c5be0aebb0000000000160014698d8419804a5d5994704d47947889ff7620c004db000000", "76a91462744660c6b5133ddeaacbc57d2dc2d7b14d0b0688ac", 0, 1648888940, 0x83, "d9276e2a48648ddb53a4aaa58314fc2b8067c13013e1913ffb67e0988ce82c78"); + } }