diff --git a/bitcoin/Cargo.toml b/bitcoin/Cargo.toml index 64ee773d..20f3c96b 100644 --- a/bitcoin/Cargo.toml +++ b/bitcoin/Cargo.toml @@ -37,7 +37,7 @@ rustdoc-args = ["--cfg", "docsrs"] bitcoin-internals = { path = "../internals" } bech32 = { version = "0.9.0", default-features = false } bitcoin_hashes = { version = "0.11.0", default-features = false } -secp256k1 = { version = "0.25.0", default-features = false, features = ["bitcoin_hashes"] } +secp256k1 = { git = "https://github.com/rust-bitcoin/rust-secp256k1", tag = "2023-02-01--fix-hashes", default-features = false, features = ["bitcoin_hashes"] } hex_lit = "0.1.1" base64 = { version = "0.13.0", optional = true } @@ -50,7 +50,7 @@ actual-serde = { package = "serde", version = "1.0.103", default-features = fals serde_json = "1.0.0" serde_test = "1.0.19" serde_derive = "1.0.103" -secp256k1 = { version = "0.25.0", features = ["recovery"] } +secp256k1 = { git = "https://github.com/rust-bitcoin/rust-secp256k1", tag = "2023-02-01--fix-hashes", features = ["recovery"] } bincode = "1.3.1" [target.'cfg(mutate)'.dev-dependencies] diff --git a/bitcoin/examples/taproot-psbt.rs b/bitcoin/examples/taproot-psbt.rs index 55d6dd34..4b77ac05 100644 --- a/bitcoin/examples/taproot-psbt.rs +++ b/bitcoin/examples/taproot-psbt.rs @@ -82,11 +82,10 @@ use bitcoin::bip32::{ChildNumber, DerivationPath, ExtendedPrivKey, ExtendedPubKe use bitcoin::consensus::encode; use bitcoin::constants::COIN_VALUE; use bitcoin::crypto::taproot; -use bitcoin::hashes::Hash; use bitcoin::key::{TapTweak, XOnlyPublicKey}; use bitcoin::opcodes::all::{OP_CHECKSIG, OP_CLTV, OP_DROP}; use bitcoin::psbt::{self, Input, Output, Psbt, PsbtSighashType}; -use bitcoin::secp256k1::{Message, Secp256k1}; +use bitcoin::secp256k1::Secp256k1; use bitcoin::sighash::{self, TapSighashType, SighashCache}; use bitcoin::taproot::{ LeafVersion, TapLeafHash, TapSighash, TaprootBuilder, TaprootSpendInfo, @@ -745,7 +744,7 @@ fn sign_psbt_taproot( Some(_) => keypair, // no tweak for script spend }; - let sig = secp.sign_schnorr(&Message::from_slice(&hash.into_inner()[..]).unwrap(), &keypair); + let sig = secp.sign_schnorr(&hash.into(), &keypair); let final_signature = taproot::Signature { sig, hash_ty }; diff --git a/bitcoin/src/address.rs b/bitcoin/src/address.rs index 9c9a32a0..c8f56430 100644 --- a/bitcoin/src/address.rs +++ b/bitcoin/src/address.rs @@ -435,13 +435,12 @@ impl Payload { /// Constructs a [Payload] from an output script (`scriptPubkey`). pub fn from_script(script: &Script) -> Result { Ok(if script.is_p2pkh() { - let mut hash_inner = [0u8; 20]; - hash_inner.copy_from_slice(&script.as_bytes()[3..23]); - Payload::PubkeyHash(PubkeyHash::from_inner(hash_inner)) + let bytes = script.as_bytes()[3..23].try_into().expect("statically 20B long"); + Payload::PubkeyHash(PubkeyHash::from_byte_array(bytes)) + } else if script.is_p2sh() { - let mut hash_inner = [0u8; 20]; - hash_inner.copy_from_slice(&script.as_bytes()[2..22]); - Payload::ScriptHash(ScriptHash::from_inner(hash_inner)) + let bytes = script.as_bytes()[2..22].try_into().expect("statically 20B long"); + Payload::ScriptHash(ScriptHash::from_byte_array(bytes)) } else if script.is_witness_program() { let opcode = script.first_opcode().expect("witness_version guarantees len() > 4"); @@ -959,9 +958,9 @@ impl Address { let payload = self.payload.inner_prog_as_bytes(); let xonly_pubkey = XOnlyPublicKey::from(pubkey.inner); - (*pubkey_hash.as_inner() == *payload) + (*pubkey_hash.as_byte_array() == *payload) || (xonly_pubkey.serialize() == *payload) - || (*segwit_redeem_hash(&pubkey_hash).as_inner() == *payload) + || (*segwit_redeem_hash(&pubkey_hash).as_byte_array() == *payload) } /// Returns true if the supplied xonly public key can be used to derive the address. diff --git a/bitcoin/src/bip152.rs b/bitcoin/src/bip152.rs index af99fad5..6e1c163a 100644 --- a/bitcoin/src/bip152.rs +++ b/bitcoin/src/bip152.rs @@ -221,8 +221,8 @@ impl HeaderAndShortIds { } else { short_ids.push(ShortId::with_siphash_keys( &match version { - 1 => tx.txid().as_hash(), - 2 => tx.wtxid().as_hash(), + 1 => tx.txid().to_raw_hash(), + 2 => tx.wtxid().to_raw_hash(), _ => unreachable!(), }, siphash_keys, diff --git a/bitcoin/src/bip158.rs b/bitcoin/src/bip158.rs index 0be1f29a..277d81ea 100644 --- a/bitcoin/src/bip158.rs +++ b/bitcoin/src/bip158.rs @@ -170,7 +170,7 @@ pub struct BlockFilterWriter<'a, W> { impl<'a, W: io::Write> BlockFilterWriter<'a, W> { /// Creates a new [`BlockFilterWriter`] from `block`. pub fn new(writer: &'a mut W, block: &'a Block) -> BlockFilterWriter<'a, W> { - let block_hash_as_int = block.block_hash().into_inner(); + let block_hash_as_int = block.block_hash().to_byte_array(); let k0 = u64::from_le_bytes(block_hash_as_int[0..8].try_into().expect("8 byte slice")); let k1 = u64::from_le_bytes(block_hash_as_int[8..16].try_into().expect("8 byte slice")); let writer = GcsFilterWriter::new(writer, k0, k1, M, P); @@ -225,7 +225,7 @@ pub struct BlockFilterReader { impl BlockFilterReader { /// Creates a new [`BlockFilterReader`] from `block_hash`. pub fn new(block_hash: &BlockHash) -> BlockFilterReader { - let block_hash_as_int = block_hash.into_inner(); + let block_hash_as_int = block_hash.to_byte_array(); let k0 = u64::from_le_bytes(block_hash_as_int[0..8].try_into().expect("8 byte slice")); let k1 = u64::from_le_bytes(block_hash_as_int[8..16].try_into().expect("8 byte slice")); BlockFilterReader { reader: GcsFilterReader::new(k0, k1, M, P) } diff --git a/bitcoin/src/blockdata/block.rs b/bitcoin/src/blockdata/block.rs index 3e525cc9..45ab355c 100644 --- a/bitcoin/src/blockdata/block.rs +++ b/bitcoin/src/blockdata/block.rs @@ -257,7 +257,7 @@ impl Block { /// Computes the transaction merkle root. pub fn compute_merkle_root(&self) -> Option { - let hashes = self.txdata.iter().map(|obj| obj.txid().as_hash()); + let hashes = self.txdata.iter().map(|obj| obj.txid().to_raw_hash()); merkle_tree::calculate_root(hashes).map(|h| h.into()) } @@ -274,9 +274,9 @@ impl Block { let hashes = self.txdata.iter().enumerate().map(|(i, t)| { if i == 0 { // Replace the first hash with zeroes. - Wtxid::all_zeros().as_hash() + Wtxid::all_zeros().to_raw_hash() } else { - t.wtxid().as_hash() + t.wtxid().to_raw_hash() } }); merkle_tree::calculate_root(hashes).map(|h| h.into()) diff --git a/bitcoin/src/blockdata/constants.rs b/bitcoin/src/blockdata/constants.rs index 3ae56bb5..53fe47ca 100644 --- a/bitcoin/src/blockdata/constants.rs +++ b/bitcoin/src/blockdata/constants.rs @@ -260,7 +260,7 @@ mod test { // The genesis block hash is a double-sha256 and it is displayed backwards. let genesis_hash = genesis_block(network).block_hash(); // We abuse the sha256 hash here so we get a LowerHex impl that does not print the hex backwards. - let hash = sha256::Hash::from_slice(&genesis_hash.into_inner()).unwrap(); + let hash = sha256::Hash::from_slice(genesis_hash.as_byte_array()).unwrap(); let want = format!("{:02x}", hash); let chain_hash = ChainHash::using_genesis_block(network); diff --git a/bitcoin/src/consensus/encode.rs b/bitcoin/src/consensus/encode.rs index 11086f40..89beca6d 100644 --- a/bitcoin/src/consensus/encode.rs +++ b/bitcoin/src/consensus/encode.rs @@ -762,37 +762,37 @@ tuple_encode!(T0, T1, T2, T3, T4, T5, T6, T7); impl Encodable for sha256d::Hash { fn consensus_encode(&self, w: &mut W) -> Result { - self.into_inner().consensus_encode(w) + self.as_byte_array().consensus_encode(w) } } impl Decodable for sha256d::Hash { fn consensus_decode(r: &mut R) -> Result { - Ok(Self::from_inner(<::Inner>::consensus_decode(r)?)) + Ok(Self::from_byte_array(<::Bytes>::consensus_decode(r)?)) } } impl Encodable for sha256::Hash { fn consensus_encode(&self, w: &mut W) -> Result { - self.into_inner().consensus_encode(w) + self.as_byte_array().consensus_encode(w) } } impl Decodable for sha256::Hash { fn consensus_decode(r: &mut R) -> Result { - Ok(Self::from_inner(<::Inner>::consensus_decode(r)?)) + Ok(Self::from_byte_array(<::Bytes>::consensus_decode(r)?)) } } impl Encodable for TapLeafHash { fn consensus_encode(&self, w: &mut W) -> Result { - self.into_inner().consensus_encode(w) + self.as_byte_array().consensus_encode(w) } } impl Decodable for TapLeafHash { fn consensus_decode(r: &mut R) -> Result { - Ok(Self::from_inner(<::Inner>::consensus_decode(r)?)) + Ok(Self::from_byte_array(<::Bytes>::consensus_decode(r)?)) } } diff --git a/bitcoin/src/crypto/key.rs b/bitcoin/src/crypto/key.rs index 83af9989..e50d8750 100644 --- a/bitcoin/src/crypto/key.rs +++ b/bitcoin/src/crypto/key.rs @@ -129,8 +129,8 @@ impl PublicKey { /// Returns bitcoin 160-bit hash of the public key for witness program pub fn wpubkey_hash(&self) -> Option { if self.compressed { - Some(WPubkeyHash::from_inner( - hash160::Hash::hash(&self.inner.serialize()).into_inner() + Some(WPubkeyHash::from_byte_array( + hash160::Hash::hash(&self.inner.serialize()).to_byte_array() )) } else { // We can't create witness pubkey hashes for an uncompressed diff --git a/bitcoin/src/crypto/sighash.rs b/bitcoin/src/crypto/sighash.rs index cbdb6c85..5390bc82 100644 --- a/bitcoin/src/crypto/sighash.rs +++ b/bitcoin/src/crypto/sighash.rs @@ -42,7 +42,7 @@ pub(crate) const MIDSTATE_TAPSIGHASH: [u8; 32] = [ macro_rules! impl_thirty_two_byte_hash { ($ty:ident) => { impl secp256k1::ThirtyTwoByteHash for $ty { - fn into_32(self) -> [u8; 32] { self.into_inner() } + fn into_32(self) -> [u8; 32] { self.to_byte_array() } } } } @@ -679,7 +679,7 @@ impl> SighashCache { // ss += bytes([0]) // ss += struct.pack("> SighashCache { .legacy_encode_signing_data_to(&mut enc, input_index, script_pubkey, sighash_type) .is_sighash_single_bug()? { - Ok(LegacySighash::from_inner(UINT256_ONE)) + Ok(LegacySighash::from_byte_array(UINT256_ONE)) } else { Ok(LegacySighash::from_engine(enc)) } @@ -1202,7 +1202,7 @@ mod tests { let mut enc = TapSighash::engine(); enc.input(&bytes); let hash = TapSighash::from_engine(enc); - assert_eq!(expected, hash.into_inner()); + assert_eq!(expected, hash.to_byte_array()); } #[test] @@ -1436,7 +1436,7 @@ mod tests { .taproot_signature_hash(input_index, &prevouts, annex, leaf_hash, sighash_type) .unwrap(); let expected = Vec::from_hex(expected_hash).unwrap(); - assert_eq!(expected, hash.into_inner()); + assert_eq!(expected, hash.to_byte_array()); } #[cfg(feature = "serde")] @@ -1696,15 +1696,15 @@ mod tests { let cache = cache.segwit_cache(); // Parse hex into Vec because BIP143 test vector displays forwards but our sha256d::Hash displays backwards. assert_eq!( - cache.prevouts.into_inner(), + cache.prevouts.as_byte_array(), &Vec::from_hex("96b827c8483d4e9b96712b6713a7b68d6e8003a781feba36c31143470b4efd37").unwrap()[..], ); assert_eq!( - cache.sequences.into_inner(), + cache.sequences.as_byte_array(), &Vec::from_hex("52b0a642eea2fb7ae638c36f6252b6750293dbe574a806984b8e4d8548339a3b").unwrap()[..], ); assert_eq!( - cache.outputs.into_inner(), + cache.outputs.as_byte_array(), &Vec::from_hex("863ef3e1a92afbfdb97f31ad0fc7683ee943e9abcf2501590ff8f6551f47e5e5").unwrap()[..], ); } @@ -1732,15 +1732,15 @@ mod tests { let cache = cache.segwit_cache(); // Parse hex into Vec because BIP143 test vector displays forwards but our sha256d::Hash displays backwards. assert_eq!( - cache.prevouts.into_inner(), + cache.prevouts.as_byte_array(), &Vec::from_hex("b0287b4a252ac05af83d2dcef00ba313af78a3e9c329afa216eb3aa2a7b4613a").unwrap()[..], ); assert_eq!( - cache.sequences.into_inner(), + cache.sequences.as_byte_array(), &Vec::from_hex("18606b350cd8bf565266bc352f0caddcf01e8fa789dd8a15386327cf8cabe198").unwrap()[..], ); assert_eq!( - cache.outputs.into_inner(), + cache.outputs.as_byte_array(), &Vec::from_hex("de984f44532e2173ca0d64314fcefe6d30da6f8cf27bafa706da61df8a226c83").unwrap()[..], ); } @@ -1773,15 +1773,15 @@ mod tests { let cache = cache.segwit_cache(); // Parse hex into Vec because BIP143 test vector displays forwards but our sha256d::Hash displays backwards. assert_eq!( - cache.prevouts.into_inner(), + cache.prevouts.as_byte_array(), &Vec::from_hex("74afdc312af5183c4198a40ca3c1a275b485496dd3929bca388c4b5e31f7aaa0").unwrap()[..], ); assert_eq!( - cache.sequences.into_inner(), + cache.sequences.as_byte_array(), &Vec::from_hex("3bb13029ce7b1f559ef5e747fcac439f1455a2ec7c5f09b72290795e70665044").unwrap()[..], ); assert_eq!( - cache.outputs.into_inner(), + cache.outputs.as_byte_array(), &Vec::from_hex("bc4d309071414bed932f98832b27b4d76dad7e6c1346f487a8fdbb8eb90307cc").unwrap()[..], ); } diff --git a/bitcoin/src/hash_types.rs b/bitcoin/src/hash_types.rs index be978a69..29bc29de 100644 --- a/bitcoin/src/hash_types.rs +++ b/bitcoin/src/hash_types.rs @@ -21,7 +21,7 @@ macro_rules! impl_hashencode { impl $crate::consensus::Decodable for $hashtype { fn consensus_decode(r: &mut R) -> Result { use $crate::hashes::Hash; - Ok(Self::from_inner(<<$hashtype as $crate::hashes::Hash>::Inner>::consensus_decode(r)?)) + Ok(Self::from_byte_array(<<$hashtype as $crate::hashes::Hash>::Bytes>::consensus_decode(r)?)) } } }; @@ -34,14 +34,14 @@ macro_rules! impl_asref_push_bytes { impl AsRef<$crate::blockdata::script::PushBytes> for $hashtype { fn as_ref(&self) -> &$crate::blockdata::script::PushBytes { use $crate::hashes::Hash; - self.as_inner().as_ref() + self.as_byte_array().into() } } impl From<$hashtype> for $crate::blockdata::script::PushBytesBuf { fn from(hash: $hashtype) -> Self { use $crate::hashes::Hash; - hash.as_inner().into() + hash.as_byte_array().into() } } )* diff --git a/bitcoin/src/merkle_tree/block.rs b/bitcoin/src/merkle_tree/block.rs index e3eeeefb..a094da97 100644 --- a/bitcoin/src/merkle_tree/block.rs +++ b/bitcoin/src/merkle_tree/block.rs @@ -305,7 +305,7 @@ impl PartialMerkleTree { if hash_used != self.hashes.len() as u32 { return Err(NotAllHashesConsumed); } - Ok(TxMerkleNode::from_inner(hash_merkle_root.into_inner())) + Ok(TxMerkleNode::from_byte_array(hash_merkle_root.to_byte_array())) } /// Helper function to efficiently calculate the number of nodes at given height @@ -319,7 +319,7 @@ impl PartialMerkleTree { fn calc_hash(&self, height: u32, pos: u32, txids: &[Txid]) -> TxMerkleNode { if height == 0 { // Hash at height 0 is the txid itself - TxMerkleNode::from_inner(txids[pos as usize].into_inner()) + TxMerkleNode::from_byte_array(txids[pos as usize].to_byte_array()) } else { // Calculate left hash let left = self.calc_hash(height - 1, pos * 2, txids); @@ -384,7 +384,7 @@ impl PartialMerkleTree { *hash_used += 1; if height == 0 && parent_of_match { // in case of height 0, we have a matched txid - matches.push(Txid::from_inner(hash.into_inner())); + matches.push(Txid::from_byte_array(hash.to_byte_array())); indexes.push(pos); } Ok(hash) @@ -573,7 +573,7 @@ mod tests { .collect::>(); // Calculate the merkle root and height - let hashes = tx_ids.iter().map(|t| t.as_hash()); + let hashes = tx_ids.iter().map(|t| t.to_raw_hash()); let merkle_root_1: TxMerkleNode = merkle_tree::calculate_root(hashes).expect("hashes is not empty").into(); let mut height = 1; @@ -741,7 +741,7 @@ mod tests { let n = rng.gen_range(0..self.hashes.len()); let bit = rng.gen::(); let hashes = &mut self.hashes; - let mut hash = hashes[n].into_inner(); + let mut hash = hashes[n].to_byte_array(); hash[(bit >> 3) as usize] ^= 1 << (bit & 7); hashes[n] = TxMerkleNode::from_slice(&hash).unwrap(); } diff --git a/bitcoin/src/merkle_tree/mod.rs b/bitcoin/src/merkle_tree/mod.rs index b7b515f2..678feb1e 100644 --- a/bitcoin/src/merkle_tree/mod.rs +++ b/bitcoin/src/merkle_tree/mod.rs @@ -122,7 +122,7 @@ mod tests { let block: Block = deserialize(&segwit_block[..]).expect("Failed to deserialize block"); assert!(block.check_merkle_root()); // Sanity check. - let hashes_iter = block.txdata.iter().map(|obj| obj.txid().as_hash()); + let hashes_iter = block.txdata.iter().map(|obj| obj.txid().to_raw_hash()); let mut hashes_array: [sha256d::Hash; 15] = [Hash::all_zeros(); 15]; for (i, hash) in hashes_iter.clone().enumerate() { diff --git a/bitcoin/src/network/message.rs b/bitcoin/src/network/message.rs index 311a0b37..8e20de6a 100644 --- a/bitcoin/src/network/message.rs +++ b/bitcoin/src/network/message.rs @@ -582,7 +582,7 @@ mod test { flags: BloomFlags::All, }), NetworkMessage::FilterAdd(FilterAdd { data: script.as_bytes().to_vec() }), - NetworkMessage::FilterAdd(FilterAdd { data: hash([29u8; 32]).into_inner().to_vec() }), + NetworkMessage::FilterAdd(FilterAdd { data: hash([29u8; 32]).as_byte_array().to_vec() }), NetworkMessage::FilterClear, NetworkMessage::GetCFilters(GetCFilters { filter_type: 2, diff --git a/bitcoin/src/pow.rs b/bitcoin/src/pow.rs index 471f247e..bdfc2e80 100644 --- a/bitcoin/src/pow.rs +++ b/bitcoin/src/pow.rs @@ -196,7 +196,7 @@ impl Target { #[cfg_attr(all(test, mutate), mutate)] pub fn is_met_by(&self, hash: BlockHash) -> bool { use crate::hashes::Hash; - let hash = U256::from_le_bytes(hash.into_inner()); + let hash = U256::from_le_bytes(hash.to_byte_array()); hash <= self.0 } @@ -1492,7 +1492,7 @@ mod tests { use crate::hashes::Hash; let hash = BlockHash::from_str("ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c").expect("failed to parse block hash"); - let target = Target(U256::from_le_bytes(hash.into_inner())); + let target = Target(U256::from_le_bytes(hash.to_byte_array())); assert!(target.is_met_by(hash)); } diff --git a/bitcoin/src/psbt/macros.rs b/bitcoin/src/psbt/macros.rs index cdb4e86b..77da1679 100644 --- a/bitcoin/src/psbt/macros.rs +++ b/bitcoin/src/psbt/macros.rs @@ -169,7 +169,7 @@ macro_rules! impl_psbt_hash_serialize { ($hash_type:ty) => { impl $crate::psbt::serialize::Serialize for $hash_type { fn serialize(&self) -> $crate::prelude::Vec { - self.into_inner().to_vec() + self.as_byte_array().to_vec() } } }; diff --git a/bitcoin/src/psbt/serialize.rs b/bitcoin/src/psbt/serialize.rs index 493e2c70..0c1b568c 100644 --- a/bitcoin/src/psbt/serialize.rs +++ b/bitcoin/src/psbt/serialize.rs @@ -309,9 +309,9 @@ impl Deserialize for taproot::Signature { impl Serialize for (XOnlyPublicKey, TapLeafHash) { fn serialize(&self) -> Vec { let ser_pk = self.0.serialize(); - let mut buf = Vec::with_capacity(ser_pk.len() + self.1.as_inner().len()); + let mut buf = Vec::with_capacity(ser_pk.len() + self.1.as_byte_array().len()); buf.extend(&ser_pk); - buf.extend(self.1.as_inner()); + buf.extend(self.1.as_byte_array()); buf } } diff --git a/bitcoin/src/taproot.rs b/bitcoin/src/taproot.rs index 5ca97c79..619db781 100644 --- a/bitcoin/src/taproot.rs +++ b/bitcoin/src/taproot.rs @@ -79,7 +79,7 @@ impl TapTweakHash { /// Converts a `TapTweakHash` into a `Scalar` ready for use with key tweaking API. pub fn to_scalar(self) -> Scalar { // This is statistically extremely unlikely to panic. - Scalar::from_be_bytes(self.into_inner()).expect("hash value greater than curve order") + Scalar::from_be_bytes(self.to_byte_array()).expect("hash value greater than curve order") } } @@ -122,7 +122,7 @@ impl TapNodeHash { } impl From for TapNodeHash { - fn from(leaf: TapLeafHash) -> TapNodeHash { TapNodeHash::from_inner(leaf.into_inner()) } + fn from(leaf: TapLeafHash) -> TapNodeHash { TapNodeHash::from_byte_array(leaf.to_byte_array()) } } /// Maximum depth of a taproot tree script spend path. @@ -690,7 +690,7 @@ impl TaprootMerkleBranch { /// Serializes `self` as bytes. pub fn serialize(&self) -> Vec { - self.0.iter().flat_map(|e| e.as_inner()).copied().collect::>() + self.0.iter().flat_map(|e| e.as_byte_array()).copied().collect::>() } /// Appends elements to proof. @@ -1152,10 +1152,10 @@ mod test { use crate::crypto::sighash::MIDSTATE_TAPSIGHASH; // check midstate against hard-coded values - assert_eq!(MIDSTATE_TAPLEAF, tag_engine("TapLeaf").midstate().into_inner()); - assert_eq!(MIDSTATE_TAPBRANCH, tag_engine("TapBranch").midstate().into_inner()); - assert_eq!(MIDSTATE_TAPTWEAK, tag_engine("TapTweak").midstate().into_inner()); - assert_eq!(MIDSTATE_TAPSIGHASH, tag_engine("TapSighash").midstate().into_inner()); + assert_eq!(MIDSTATE_TAPLEAF, tag_engine("TapLeaf").midstate().to_byte_array()); + assert_eq!(MIDSTATE_TAPBRANCH, tag_engine("TapBranch").midstate().to_byte_array()); + assert_eq!(MIDSTATE_TAPTWEAK, tag_engine("TapTweak").midstate().to_byte_array()); + assert_eq!(MIDSTATE_TAPSIGHASH, tag_engine("TapSighash").midstate().to_byte_array()); // test that engine creation roundtrips assert_eq!(tag_engine("TapLeaf").midstate(), TapLeafTag::engine().midstate()); @@ -1167,12 +1167,12 @@ mod test { fn empty_hash(tag_name: &str) -> [u8; 32] { let mut e = tag_engine(tag_name); e.input(&[]); - TapNodeHash::from_engine(e).into_inner() + TapNodeHash::from_engine(e).to_byte_array() } - assert_eq!(empty_hash("TapLeaf"), TapLeafHash::hash(&[]).into_inner()); - assert_eq!(empty_hash("TapBranch"), TapNodeHash::hash(&[]).into_inner()); - assert_eq!(empty_hash("TapTweak"), TapTweakHash::hash(&[]).into_inner()); - assert_eq!(empty_hash("TapSighash"), TapSighash::hash(&[]).into_inner()); + assert_eq!(empty_hash("TapLeaf"), TapLeafHash::hash(&[]).to_byte_array()); + assert_eq!(empty_hash("TapBranch"), TapNodeHash::hash(&[]).to_byte_array()); + assert_eq!(empty_hash("TapTweak"), TapTweakHash::hash(&[]).to_byte_array()); + assert_eq!(empty_hash("TapSighash"), TapSighash::hash(&[]).to_byte_array()); } #[test] diff --git a/hashes/extended_tests/schemars/src/main.rs b/hashes/extended_tests/schemars/src/main.rs index 23c36a9c..7ceee050 100644 --- a/hashes/extended_tests/schemars/src/main.rs +++ b/hashes/extended_tests/schemars/src/main.rs @@ -125,7 +125,7 @@ mod tests { impl sha256t::Tag for TestHashTag { fn engine() -> sha256::HashEngine { // The TapRoot TapLeaf midstate. - let midstate = sha256::Midstate::from_inner(TEST_MIDSTATE); + let midstate = sha256::Midstate::from_byte_array(TEST_MIDSTATE); sha256::HashEngine::from_midstate(midstate, 64) } } diff --git a/hashes/src/hash160.rs b/hashes/src/hash160.rs index 8c6a114a..51462441 100644 --- a/hashes/src/hash160.rs +++ b/hashes/src/hash160.rs @@ -97,7 +97,7 @@ mod tests { } let manual_hash = Hash::from_engine(engine); assert_eq!(hash, manual_hash); - assert_eq!(hash.into_inner()[..].as_ref(), test.output.as_slice()); + assert_eq!(hash.to_byte_array()[..].as_ref(), test.output.as_slice()); } } diff --git a/hashes/src/hmac.rs b/hashes/src/hmac.rs index 3cd10728..22afd7d1 100644 --- a/hashes/src/hmac.rs +++ b/hashes/src/hmac.rs @@ -192,7 +192,7 @@ impl borrow::Borrow<[u8]> for Hmac { impl Hash for Hmac { type Engine = HmacEngine; - type Inner = T::Inner; + type Bytes = T::Bytes; fn from_engine(mut e: HmacEngine) -> Hmac { let ihash = T::from_engine(e.iengine); @@ -207,16 +207,16 @@ impl Hash for Hmac { T::from_slice(sl).map(Hmac) } - fn into_inner(self) -> Self::Inner { - self.0.into_inner() + fn to_byte_array(self) -> Self::Bytes { + self.0.to_byte_array() } - fn as_inner(&self) -> &Self::Inner { - self.0.as_inner() + fn as_byte_array(&self) -> &Self::Bytes { + self.0.as_byte_array() } - fn from_inner(inner: T::Inner) -> Self { - Hmac(T::from_inner(inner)) + fn from_byte_array(bytes: T::Bytes) -> Self { + Hmac(T::from_byte_array(bytes)) } fn all_zeros() -> Self { @@ -237,8 +237,8 @@ impl Serialize for Hmac { #[cfg_attr(docsrs, doc(cfg(feature = "serde")))] impl<'de, T: Hash + Deserialize<'de>> Deserialize<'de> for Hmac { fn deserialize>(d: D) -> Result, D::Error> { - let inner = Deserialize::deserialize(d)?; - Ok(Hmac(inner)) + let bytes = Deserialize::deserialize(d)?; + Ok(Hmac(bytes)) } } @@ -365,7 +365,7 @@ mod tests { engine.input(&test.input); let hash = Hmac::::from_engine(engine); assert_eq!(&hash[..], &test.output[..]); - assert_eq!(hash.into_inner()[..].as_ref(), test.output.as_slice()); + assert_eq!(hash.as_byte_array(), test.output.as_slice()); } } diff --git a/hashes/src/internal_macros.rs b/hashes/src/internal_macros.rs index 8c5a2f0a..be993d23 100644 --- a/hashes/src/internal_macros.rs +++ b/hashes/src/internal_macros.rs @@ -97,7 +97,7 @@ macro_rules! hash_trait_impls { } else { FromHex::from_byte_iter(HexIterator::new(s)?)? }; - Ok(Self::from_inner(inner)) + Ok(Self::from_byte_array(inner)) } } @@ -122,7 +122,7 @@ macro_rules! hash_trait_impls { impl<$($gen: $gent),*> crate::Hash for Hash<$($gen),*> { type Engine = HashEngine; - type Inner = [u8; $bits / 8]; + type Bytes = [u8; $bits / 8]; const LEN: usize = $bits / 8; const DISPLAY_BACKWARD: bool = $reverse; @@ -145,16 +145,16 @@ macro_rules! hash_trait_impls { } } - fn into_inner(self) -> Self::Inner { + fn to_byte_array(self) -> Self::Bytes { self.0 } - fn as_inner(&self) -> &Self::Inner { + fn as_byte_array(&self) -> &Self::Bytes { &self.0 } - fn from_inner(inner: Self::Inner) -> Self { - Self::internal_new(inner) + fn from_byte_array(bytes: Self::Bytes) -> Self { + Self::internal_new(bytes) } fn all_zeros() -> Self { diff --git a/hashes/src/lib.rs b/hashes/src/lib.rs index 3b6d062a..5c218087 100644 --- a/hashes/src/lib.rs +++ b/hashes/src/lib.rs @@ -171,7 +171,7 @@ pub trait Hash: Copy + Clone + PartialEq + Eq + PartialOrd + Ord + type Engine: HashEngine; /// The byte array that represents the hash internally. - type Inner: hex::FromHex; + type Bytes: hex::FromHex + Copy; /// Constructs a new engine. fn engine() -> Self::Engine { @@ -199,14 +199,14 @@ pub trait Hash: Copy + Clone + PartialEq + Eq + PartialOrd + Ord + /// true for `Sha256dHash`, so here we are. const DISPLAY_BACKWARD: bool = false; - /// Unwraps the hash and returns the underlying byte array. - fn into_inner(self) -> Self::Inner; + /// Returns the underlying byte array. + fn to_byte_array(self) -> Self::Bytes; - /// Unwraps the hash and returns a reference to the underlying byte array. - fn as_inner(&self) -> &Self::Inner; + /// Returns a reference to the underlying byte array. + fn as_byte_array(&self) -> &Self::Bytes; /// Constructs a hash from the underlying byte array. - fn from_inner(inner: Self::Inner) -> Self; + fn from_byte_array(bytes: Self::Bytes) -> Self; /// Returns an all zero hash. /// @@ -231,11 +231,11 @@ mod tests { #[test] fn convert_newtypes() { let h1 = TestNewtype::hash(&[]); - let h2: TestNewtype2 = h1.as_hash().into(); + let h2: TestNewtype2 = h1.to_raw_hash().into(); assert_eq!(&h1[..], &h2[..]); let h = sha256d::Hash::hash(&[]); let h2: TestNewtype = h.to_string().parse().unwrap(); - assert_eq!(h2.as_hash(), h); + assert_eq!(h2.to_raw_hash(), h); } } diff --git a/hashes/src/ripemd160.rs b/hashes/src/ripemd160.rs index e27f87af..591706b8 100644 --- a/hashes/src/ripemd160.rs +++ b/hashes/src/ripemd160.rs @@ -480,7 +480,7 @@ mod tests { } let manual_hash = ripemd160::Hash::from_engine(engine); assert_eq!(hash, manual_hash); - assert_eq!(hash.into_inner()[..].as_ref(), test.output.as_slice()); + assert_eq!(hash.as_byte_array(), test.output.as_slice()); } } diff --git a/hashes/src/sha1.rs b/hashes/src/sha1.rs index 144cd3ac..7fae399e 100644 --- a/hashes/src/sha1.rs +++ b/hashes/src/sha1.rs @@ -206,7 +206,7 @@ mod tests { } let manual_hash = sha1::Hash::from_engine(engine); assert_eq!(hash, manual_hash); - assert_eq!(hash.into_inner()[..].as_ref(), test.output.as_slice()); + assert_eq!(hash.as_byte_array(), test.output.as_slice()); } } diff --git a/hashes/src/sha256.rs b/hashes/src/sha256.rs index 357cec8f..5155615b 100644 --- a/hashes/src/sha256.rs +++ b/hashes/src/sha256.rs @@ -46,12 +46,12 @@ fn from_engine(mut e: HashEngine) -> Hash { e.input(&(8 * data_len).to_be_bytes()); debug_assert_eq!(e.length % BLOCK_SIZE, 0); - Hash(e.midstate().into_inner()) + Hash(e.midstate().to_byte_array()) } #[cfg(fuzzing)] fn from_engine(e: HashEngine) -> Hash { - let mut hash = e.midstate().into_inner(); + let mut hash = e.midstate().to_byte_array(); if hash == [0; 32] { // Assume sha256 is secure and never generate 0-hashes (which represent invalid // secp256k1 secret keys, causing downstream application breakage). @@ -111,7 +111,7 @@ impl crate::HashEngine for HashEngine { impl Hash { /// Iterate the sha256 algorithm to turn a sha256 hash into a sha256d hash pub fn hash_again(&self) -> sha256d::Hash { - crate::Hash::from_inner(::hash(&self.0).0) + crate::Hash::from_byte_array(::hash(&self.0).0) } } @@ -149,7 +149,7 @@ impl Midstate { const DISPLAY_BACKWARD: bool = true; /// Construct a new [`Midstate`] from the inner value. - pub fn from_inner(inner: [u8; 32]) -> Self { + pub fn from_byte_array(inner: [u8; 32]) -> Self { Midstate(inner) } @@ -165,7 +165,7 @@ impl Midstate { } /// Unwraps the [`Midstate`] and returns the underlying byte array. - pub fn into_inner(self) -> [u8; 32] { + pub fn to_byte_array(self) -> [u8; 32] { self.0 } } @@ -176,7 +176,7 @@ impl hex::FromHex for Midstate { I: Iterator> + ExactSizeIterator + DoubleEndedIterator, { // DISPLAY_BACKWARD is true - Ok(Midstate::from_inner(hex::FromHex::from_byte_iter(iter.rev())?)) + Ok(Midstate::from_byte_array(hex::FromHex::from_byte_iter(iter.rev())?)) } } @@ -381,7 +381,7 @@ mod tests { } let manual_hash = sha256::Hash::from_engine(engine); assert_eq!(hash, manual_hash); - assert_eq!(hash.into_inner()[..].as_ref(), test.output.as_slice()); + assert_eq!(hash.to_byte_array()[..].as_ref(), test.output.as_slice()); } } @@ -402,7 +402,7 @@ mod tests { assert_eq!( engine.midstate(), // RPC output - sha256::Midstate::from_inner([ + sha256::Midstate::from_byte_array([ 0x0b, 0xcf, 0xe0, 0xe5, 0x4e, 0x6c, 0xc7, 0xd3, 0x4f, 0x4f, 0x7c, 0x1d, 0xf0, 0xb0, 0xf5, 0x03, 0xf2, 0xf7, 0x12, 0x91, 0x2a, 0x06, 0x05, 0xb4, @@ -455,7 +455,7 @@ mod tests { 0xd5, 0x69, 0x09, 0x59, ]; let midstate_engine = - sha256::HashEngine::from_midstate(sha256::Midstate::from_inner(MIDSTATE), 64); + sha256::HashEngine::from_midstate(sha256::Midstate::from_byte_array(MIDSTATE), 64); let hash = sha256::Hash::from_engine(midstate_engine); assert_eq!(hash, sha256::Hash(HASH_EXPECTED)); } diff --git a/hashes/src/sha256d.rs b/hashes/src/sha256d.rs index bbf9f77a..ec227a9f 100644 --- a/hashes/src/sha256d.rs +++ b/hashes/src/sha256d.rs @@ -89,7 +89,7 @@ mod tests { let sha2d_hash = sha2_hash.hash_again(); assert_eq!(hash, sha2d_hash); - assert_eq!(hash.into_inner()[..].as_ref(), test.output.as_slice()); + assert_eq!(hash.to_byte_array()[..].as_ref(), test.output.as_slice()); } } diff --git a/hashes/src/sha256t.rs b/hashes/src/sha256t.rs index 6f47448c..c7f4d3bf 100644 --- a/hashes/src/sha256t.rs +++ b/hashes/src/sha256t.rs @@ -88,7 +88,7 @@ crate::internal_macros::hash_trait_impls!(256, true, T: Tag); fn from_engine(e: sha256::HashEngine) -> Hash { use crate::Hash as _; - Hash::from_inner(sha256::Hash::from_engine(e).into_inner()) + Hash::from_byte_array(sha256::Hash::from_engine(e).to_byte_array()) } /// Macro used to define a newtype tagged hash. @@ -110,7 +110,7 @@ macro_rules! sha256t_hash_newtype { impl $crate::sha256t::Tag for $tag { fn engine() -> $crate::sha256::HashEngine { - let midstate = $crate::sha256::Midstate::from_inner($midstate); + let midstate = $crate::sha256::Midstate::from_byte_array($midstate); $crate::sha256::HashEngine::from_midstate(midstate, $midstate_len) } } @@ -141,7 +141,7 @@ mod tests { impl sha256t::Tag for TestHashTag { fn engine() -> sha256::HashEngine { // The TapRoot TapLeaf midstate. - let midstate = sha256::Midstate::from_inner(TEST_MIDSTATE); + let midstate = sha256::Midstate::from_byte_array(TEST_MIDSTATE); sha256::HashEngine::from_midstate(midstate, 64) } } diff --git a/hashes/src/sha512.rs b/hashes/src/sha512.rs index e6618f36..9feaa3a5 100644 --- a/hashes/src/sha512.rs +++ b/hashes/src/sha512.rs @@ -379,7 +379,7 @@ mod tests { } let manual_hash = sha512::Hash::from_engine(engine); assert_eq!(hash, manual_hash); - assert_eq!(hash.into_inner()[..].as_ref(), test.output.as_slice()); + assert_eq!(hash.to_byte_array()[..].as_ref(), test.output.as_slice()); } } diff --git a/hashes/src/sha512_256.rs b/hashes/src/sha512_256.rs index 02b9fa94..ad146146 100644 --- a/hashes/src/sha512_256.rs +++ b/hashes/src/sha512_256.rs @@ -165,7 +165,7 @@ mod tests { } let manual_hash = sha512_256::Hash::from_engine(engine); assert_eq!(hash, manual_hash); - assert_eq!(hash.into_inner()[..].as_ref(), test.output.as_slice()); + assert_eq!(hash.to_byte_array()[..].as_ref(), test.output.as_slice()); } } } diff --git a/hashes/src/util.rs b/hashes/src/util.rs index 743e94c7..62441a77 100644 --- a/hashes/src/util.rs +++ b/hashes/src/util.rs @@ -173,18 +173,23 @@ macro_rules! hash_newtype { $crate::borrow_slice_impl!($newtype); impl $newtype { - /// Creates this type from the inner hash type. + /// Creates this wrapper type from the inner hash type. #[allow(unused)] // the user of macro may not need this - pub fn from_hash(inner: $hash) -> $newtype { + pub fn from_raw_hash(inner: $hash) -> $newtype { $newtype(inner) } - /// Converts this type into the inner hash type. + /// Returns the inner hash (sha256, sh256d etc.). #[allow(unused)] // the user of macro may not need this - pub fn as_hash(&self) -> $hash { - // Hashes implement Copy so don't need into_hash. + pub fn to_raw_hash(self) -> $hash { self.0 } + + /// Returns a reference to the inner hash (sha256, sh256d etc.). + #[allow(unused)] // the user of macro may not need this + pub fn as_raw_hash(&self) -> &$hash { + &self.0 + } } impl $crate::_export::_core::convert::From<$hash> for $newtype { @@ -202,7 +207,7 @@ macro_rules! hash_newtype { impl $crate::Hash for $newtype { type Engine = <$hash as $crate::Hash>::Engine; - type Inner = <$hash as $crate::Hash>::Inner; + type Bytes = <$hash as $crate::Hash>::Bytes; const LEN: usize = <$hash as $crate::Hash>::LEN; const DISPLAY_BACKWARD: bool = $crate::hash_newtype_get_direction!($hash, $(#[$($type_attrs)*])*); @@ -221,18 +226,18 @@ macro_rules! hash_newtype { } #[inline] - fn from_inner(inner: Self::Inner) -> Self { - $newtype(<$hash as $crate::Hash>::from_inner(inner)) + fn from_byte_array(bytes: Self::Bytes) -> Self { + $newtype(<$hash as $crate::Hash>::from_byte_array(bytes)) } #[inline] - fn into_inner(self) -> Self::Inner { - self.0.into_inner() + fn to_byte_array(self) -> Self::Bytes { + self.0.to_byte_array() } #[inline] - fn as_inner(&self) -> &Self::Inner { - self.0.as_inner() + fn as_byte_array(&self) -> &Self::Bytes { + self.0.as_byte_array() } #[inline] @@ -248,12 +253,12 @@ macro_rules! hash_newtype { use $crate::hex::{HexIterator, FromHex}; use $crate::Hash; - let inner: <$hash as Hash>::Inner = if ::DISPLAY_BACKWARD { + let inner: <$hash as Hash>::Bytes = if ::DISPLAY_BACKWARD { FromHex::from_byte_iter(HexIterator::new(s)?.rev())? } else { FromHex::from_byte_iter(HexIterator::new(s)?)? }; - Ok($newtype(<$hash>::from_inner(inner))) + Ok($newtype(<$hash>::from_byte_array(inner))) } } @@ -374,14 +379,14 @@ mod test { fn hash_as_ref_array() { let hash = sha256::Hash::hash(&[3, 50]); let r = AsRef::<[u8; 32]>::as_ref(&hash); - assert_eq!(r, hash.as_inner()); + assert_eq!(r, hash.as_byte_array()); } #[test] fn hash_as_ref_slice() { let hash = sha256::Hash::hash(&[3, 50]); let r = AsRef::<[u8]>::as_ref(&hash); - assert_eq!(r, hash.as_inner()); + assert_eq!(r, hash.as_byte_array()); } #[test] @@ -390,7 +395,7 @@ mod test { let hash = sha256::Hash::hash(&[3, 50]); let borrowed: &[u8] = hash.borrow(); - assert_eq!(borrowed, hash.as_inner()); + assert_eq!(borrowed, hash.as_byte_array()); } hash_newtype! { @@ -430,13 +435,13 @@ mod test { fn inner_hash_as_ref_array() { let hash = TestHash::all_zeros(); let r = AsRef::<[u8; 32]>::as_ref(&hash); - assert_eq!(r, hash.as_inner()); + assert_eq!(r, hash.as_byte_array()); } #[test] fn inner_hash_as_ref_slice() { let hash = TestHash::all_zeros(); let r = AsRef::<[u8]>::as_ref(&hash); - assert_eq!(r, hash.as_inner()); + assert_eq!(r, hash.as_byte_array()); } }