Re-name hash inner/byte methods
Currently we have an associated type on hash types `Inner` with accompanying methods `into_inner`, `from_inner`, `as_inner`. Also, we provide a way to create new wrapped hash types. The use of 'inner' becomes ambiguous with the addition of wrapped types because the inner could be the inner hash type or the `Inner` byte array of the inner wrapped hash type. In an effort to make the API more clear and uniform do the following: - Rename `Inner` -> `Bytes` - Rename `*_inner` -> `*_byte_array` - Rename the inner hash to/from methods to `*_raw_hash` Correct method prefix `into_` -> `to_` because theses methods convert owned `Copy` types. Add the trait Bound `Copy` to the `Bytes` type because we rely on this trait bound for the conversion methods to be correctly named according to convention. Because of the dependency hole created by `secp256k1` this patch changes the secp dependency to a git tag dependency that includes changes to the hashes calls required so that we can get green lights on CI in this repo.
This commit is contained in:
parent
324b6f264b
commit
161273b209
|
@ -37,7 +37,7 @@ rustdoc-args = ["--cfg", "docsrs"]
|
||||||
bitcoin-internals = { path = "../internals" }
|
bitcoin-internals = { path = "../internals" }
|
||||||
bech32 = { version = "0.9.0", default-features = false }
|
bech32 = { version = "0.9.0", default-features = false }
|
||||||
bitcoin_hashes = { version = "0.11.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"
|
hex_lit = "0.1.1"
|
||||||
|
|
||||||
base64 = { version = "0.13.0", optional = true }
|
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_json = "1.0.0"
|
||||||
serde_test = "1.0.19"
|
serde_test = "1.0.19"
|
||||||
serde_derive = "1.0.103"
|
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"
|
bincode = "1.3.1"
|
||||||
|
|
||||||
[target.'cfg(mutate)'.dev-dependencies]
|
[target.'cfg(mutate)'.dev-dependencies]
|
||||||
|
|
|
@ -82,11 +82,10 @@ use bitcoin::bip32::{ChildNumber, DerivationPath, ExtendedPrivKey, ExtendedPubKe
|
||||||
use bitcoin::consensus::encode;
|
use bitcoin::consensus::encode;
|
||||||
use bitcoin::constants::COIN_VALUE;
|
use bitcoin::constants::COIN_VALUE;
|
||||||
use bitcoin::crypto::taproot;
|
use bitcoin::crypto::taproot;
|
||||||
use bitcoin::hashes::Hash;
|
|
||||||
use bitcoin::key::{TapTweak, XOnlyPublicKey};
|
use bitcoin::key::{TapTweak, XOnlyPublicKey};
|
||||||
use bitcoin::opcodes::all::{OP_CHECKSIG, OP_CLTV, OP_DROP};
|
use bitcoin::opcodes::all::{OP_CHECKSIG, OP_CLTV, OP_DROP};
|
||||||
use bitcoin::psbt::{self, Input, Output, Psbt, PsbtSighashType};
|
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::sighash::{self, TapSighashType, SighashCache};
|
||||||
use bitcoin::taproot::{
|
use bitcoin::taproot::{
|
||||||
LeafVersion, TapLeafHash, TapSighash, TaprootBuilder, TaprootSpendInfo,
|
LeafVersion, TapLeafHash, TapSighash, TaprootBuilder, TaprootSpendInfo,
|
||||||
|
|
|
@ -435,13 +435,12 @@ impl Payload {
|
||||||
/// Constructs a [Payload] from an output script (`scriptPubkey`).
|
/// Constructs a [Payload] from an output script (`scriptPubkey`).
|
||||||
pub fn from_script(script: &Script) -> Result<Payload, Error> {
|
pub fn from_script(script: &Script) -> Result<Payload, Error> {
|
||||||
Ok(if script.is_p2pkh() {
|
Ok(if script.is_p2pkh() {
|
||||||
let mut hash_inner = [0u8; 20];
|
let bytes = script.as_bytes()[3..23].try_into().expect("statically 20B long");
|
||||||
hash_inner.copy_from_slice(&script.as_bytes()[3..23]);
|
Payload::PubkeyHash(PubkeyHash::from_byte_array(bytes))
|
||||||
Payload::PubkeyHash(PubkeyHash::from_inner(hash_inner))
|
|
||||||
} else if script.is_p2sh() {
|
} else if script.is_p2sh() {
|
||||||
let mut hash_inner = [0u8; 20];
|
let bytes = script.as_bytes()[2..22].try_into().expect("statically 20B long");
|
||||||
hash_inner.copy_from_slice(&script.as_bytes()[2..22]);
|
Payload::ScriptHash(ScriptHash::from_byte_array(bytes))
|
||||||
Payload::ScriptHash(ScriptHash::from_inner(hash_inner))
|
|
||||||
} else if script.is_witness_program() {
|
} else if script.is_witness_program() {
|
||||||
let opcode = script.first_opcode().expect("witness_version guarantees len() > 4");
|
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 payload = self.payload.inner_prog_as_bytes();
|
||||||
let xonly_pubkey = XOnlyPublicKey::from(pubkey.inner);
|
let xonly_pubkey = XOnlyPublicKey::from(pubkey.inner);
|
||||||
|
|
||||||
(*pubkey_hash.as_inner() == *payload)
|
(*pubkey_hash.as_byte_array() == *payload)
|
||||||
|| (xonly_pubkey.serialize() == *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.
|
/// Returns true if the supplied xonly public key can be used to derive the address.
|
||||||
|
|
|
@ -221,8 +221,8 @@ impl HeaderAndShortIds {
|
||||||
} else {
|
} else {
|
||||||
short_ids.push(ShortId::with_siphash_keys(
|
short_ids.push(ShortId::with_siphash_keys(
|
||||||
&match version {
|
&match version {
|
||||||
1 => tx.txid().as_hash(),
|
1 => tx.txid().to_raw_hash(),
|
||||||
2 => tx.wtxid().as_hash(),
|
2 => tx.wtxid().to_raw_hash(),
|
||||||
_ => unreachable!(),
|
_ => unreachable!(),
|
||||||
},
|
},
|
||||||
siphash_keys,
|
siphash_keys,
|
||||||
|
|
|
@ -170,7 +170,7 @@ pub struct BlockFilterWriter<'a, W> {
|
||||||
impl<'a, W: io::Write> BlockFilterWriter<'a, W> {
|
impl<'a, W: io::Write> BlockFilterWriter<'a, W> {
|
||||||
/// Creates a new [`BlockFilterWriter`] from `block`.
|
/// Creates a new [`BlockFilterWriter`] from `block`.
|
||||||
pub fn new(writer: &'a mut W, block: &'a Block) -> BlockFilterWriter<'a, W> {
|
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 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 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);
|
let writer = GcsFilterWriter::new(writer, k0, k1, M, P);
|
||||||
|
@ -225,7 +225,7 @@ pub struct BlockFilterReader {
|
||||||
impl BlockFilterReader {
|
impl BlockFilterReader {
|
||||||
/// Creates a new [`BlockFilterReader`] from `block_hash`.
|
/// Creates a new [`BlockFilterReader`] from `block_hash`.
|
||||||
pub fn new(block_hash: &BlockHash) -> BlockFilterReader {
|
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 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 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) }
|
BlockFilterReader { reader: GcsFilterReader::new(k0, k1, M, P) }
|
||||||
|
|
|
@ -257,7 +257,7 @@ impl Block {
|
||||||
|
|
||||||
/// Computes the transaction merkle root.
|
/// Computes the transaction merkle root.
|
||||||
pub fn compute_merkle_root(&self) -> Option<TxMerkleNode> {
|
pub fn compute_merkle_root(&self) -> Option<TxMerkleNode> {
|
||||||
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())
|
merkle_tree::calculate_root(hashes).map(|h| h.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -274,9 +274,9 @@ impl Block {
|
||||||
let hashes = self.txdata.iter().enumerate().map(|(i, t)| {
|
let hashes = self.txdata.iter().enumerate().map(|(i, t)| {
|
||||||
if i == 0 {
|
if i == 0 {
|
||||||
// Replace the first hash with zeroes.
|
// Replace the first hash with zeroes.
|
||||||
Wtxid::all_zeros().as_hash()
|
Wtxid::all_zeros().to_raw_hash()
|
||||||
} else {
|
} else {
|
||||||
t.wtxid().as_hash()
|
t.wtxid().to_raw_hash()
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
merkle_tree::calculate_root(hashes).map(|h| h.into())
|
merkle_tree::calculate_root(hashes).map(|h| h.into())
|
||||||
|
|
|
@ -260,7 +260,7 @@ mod test {
|
||||||
// The genesis block hash is a double-sha256 and it is displayed backwards.
|
// The genesis block hash is a double-sha256 and it is displayed backwards.
|
||||||
let genesis_hash = genesis_block(network).block_hash();
|
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.
|
// 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 want = format!("{:02x}", hash);
|
||||||
|
|
||||||
let chain_hash = ChainHash::using_genesis_block(network);
|
let chain_hash = ChainHash::using_genesis_block(network);
|
||||||
|
|
|
@ -762,37 +762,37 @@ tuple_encode!(T0, T1, T2, T3, T4, T5, T6, T7);
|
||||||
|
|
||||||
impl Encodable for sha256d::Hash {
|
impl Encodable for sha256d::Hash {
|
||||||
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
|
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
|
||||||
self.into_inner().consensus_encode(w)
|
self.as_byte_array().consensus_encode(w)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Decodable for sha256d::Hash {
|
impl Decodable for sha256d::Hash {
|
||||||
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
|
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
|
||||||
Ok(Self::from_inner(<<Self as Hash>::Inner>::consensus_decode(r)?))
|
Ok(Self::from_byte_array(<<Self as Hash>::Bytes>::consensus_decode(r)?))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Encodable for sha256::Hash {
|
impl Encodable for sha256::Hash {
|
||||||
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
|
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
|
||||||
self.into_inner().consensus_encode(w)
|
self.as_byte_array().consensus_encode(w)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Decodable for sha256::Hash {
|
impl Decodable for sha256::Hash {
|
||||||
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
|
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
|
||||||
Ok(Self::from_inner(<<Self as Hash>::Inner>::consensus_decode(r)?))
|
Ok(Self::from_byte_array(<<Self as Hash>::Bytes>::consensus_decode(r)?))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Encodable for TapLeafHash {
|
impl Encodable for TapLeafHash {
|
||||||
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
|
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
|
||||||
self.into_inner().consensus_encode(w)
|
self.as_byte_array().consensus_encode(w)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Decodable for TapLeafHash {
|
impl Decodable for TapLeafHash {
|
||||||
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
|
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
|
||||||
Ok(Self::from_inner(<<Self as Hash>::Inner>::consensus_decode(r)?))
|
Ok(Self::from_byte_array(<<Self as Hash>::Bytes>::consensus_decode(r)?))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -129,8 +129,8 @@ impl PublicKey {
|
||||||
/// Returns bitcoin 160-bit hash of the public key for witness program
|
/// Returns bitcoin 160-bit hash of the public key for witness program
|
||||||
pub fn wpubkey_hash(&self) -> Option<WPubkeyHash> {
|
pub fn wpubkey_hash(&self) -> Option<WPubkeyHash> {
|
||||||
if self.compressed {
|
if self.compressed {
|
||||||
Some(WPubkeyHash::from_inner(
|
Some(WPubkeyHash::from_byte_array(
|
||||||
hash160::Hash::hash(&self.inner.serialize()).into_inner()
|
hash160::Hash::hash(&self.inner.serialize()).to_byte_array()
|
||||||
))
|
))
|
||||||
} else {
|
} else {
|
||||||
// We can't create witness pubkey hashes for an uncompressed
|
// We can't create witness pubkey hashes for an uncompressed
|
||||||
|
|
|
@ -42,7 +42,7 @@ pub(crate) const MIDSTATE_TAPSIGHASH: [u8; 32] = [
|
||||||
macro_rules! impl_thirty_two_byte_hash {
|
macro_rules! impl_thirty_two_byte_hash {
|
||||||
($ty:ident) => {
|
($ty:ident) => {
|
||||||
impl secp256k1::ThirtyTwoByteHash for $ty {
|
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<R: Borrow<Transaction>> SighashCache<R> {
|
||||||
// ss += bytes([0])
|
// ss += bytes([0])
|
||||||
// ss += struct.pack("<i", codeseparator_pos)
|
// ss += struct.pack("<i", codeseparator_pos)
|
||||||
if let Some((hash, code_separator_pos)) = leaf_hash_code_separator {
|
if let Some((hash, code_separator_pos)) = leaf_hash_code_separator {
|
||||||
hash.into_inner().consensus_encode(&mut writer)?;
|
hash.as_byte_array().consensus_encode(&mut writer)?;
|
||||||
KEY_VERSION_0.consensus_encode(&mut writer)?;
|
KEY_VERSION_0.consensus_encode(&mut writer)?;
|
||||||
code_separator_pos.consensus_encode(&mut writer)?;
|
code_separator_pos.consensus_encode(&mut writer)?;
|
||||||
}
|
}
|
||||||
|
@ -991,7 +991,7 @@ impl<R: Borrow<Transaction>> SighashCache<R> {
|
||||||
.legacy_encode_signing_data_to(&mut enc, input_index, script_pubkey, sighash_type)
|
.legacy_encode_signing_data_to(&mut enc, input_index, script_pubkey, sighash_type)
|
||||||
.is_sighash_single_bug()?
|
.is_sighash_single_bug()?
|
||||||
{
|
{
|
||||||
Ok(LegacySighash::from_inner(UINT256_ONE))
|
Ok(LegacySighash::from_byte_array(UINT256_ONE))
|
||||||
} else {
|
} else {
|
||||||
Ok(LegacySighash::from_engine(enc))
|
Ok(LegacySighash::from_engine(enc))
|
||||||
}
|
}
|
||||||
|
@ -1202,7 +1202,7 @@ mod tests {
|
||||||
let mut enc = TapSighash::engine();
|
let mut enc = TapSighash::engine();
|
||||||
enc.input(&bytes);
|
enc.input(&bytes);
|
||||||
let hash = TapSighash::from_engine(enc);
|
let hash = TapSighash::from_engine(enc);
|
||||||
assert_eq!(expected, hash.into_inner());
|
assert_eq!(expected, hash.to_byte_array());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
@ -1436,7 +1436,7 @@ mod tests {
|
||||||
.taproot_signature_hash(input_index, &prevouts, annex, leaf_hash, sighash_type)
|
.taproot_signature_hash(input_index, &prevouts, annex, leaf_hash, sighash_type)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let expected = Vec::from_hex(expected_hash).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")]
|
#[cfg(feature = "serde")]
|
||||||
|
@ -1696,15 +1696,15 @@ mod tests {
|
||||||
let cache = cache.segwit_cache();
|
let cache = cache.segwit_cache();
|
||||||
// Parse hex into Vec because BIP143 test vector displays forwards but our sha256d::Hash displays backwards.
|
// Parse hex into Vec because BIP143 test vector displays forwards but our sha256d::Hash displays backwards.
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
cache.prevouts.into_inner(),
|
cache.prevouts.as_byte_array(),
|
||||||
&Vec::from_hex("96b827c8483d4e9b96712b6713a7b68d6e8003a781feba36c31143470b4efd37").unwrap()[..],
|
&Vec::from_hex("96b827c8483d4e9b96712b6713a7b68d6e8003a781feba36c31143470b4efd37").unwrap()[..],
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
cache.sequences.into_inner(),
|
cache.sequences.as_byte_array(),
|
||||||
&Vec::from_hex("52b0a642eea2fb7ae638c36f6252b6750293dbe574a806984b8e4d8548339a3b").unwrap()[..],
|
&Vec::from_hex("52b0a642eea2fb7ae638c36f6252b6750293dbe574a806984b8e4d8548339a3b").unwrap()[..],
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
cache.outputs.into_inner(),
|
cache.outputs.as_byte_array(),
|
||||||
&Vec::from_hex("863ef3e1a92afbfdb97f31ad0fc7683ee943e9abcf2501590ff8f6551f47e5e5").unwrap()[..],
|
&Vec::from_hex("863ef3e1a92afbfdb97f31ad0fc7683ee943e9abcf2501590ff8f6551f47e5e5").unwrap()[..],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -1732,15 +1732,15 @@ mod tests {
|
||||||
let cache = cache.segwit_cache();
|
let cache = cache.segwit_cache();
|
||||||
// Parse hex into Vec because BIP143 test vector displays forwards but our sha256d::Hash displays backwards.
|
// Parse hex into Vec because BIP143 test vector displays forwards but our sha256d::Hash displays backwards.
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
cache.prevouts.into_inner(),
|
cache.prevouts.as_byte_array(),
|
||||||
&Vec::from_hex("b0287b4a252ac05af83d2dcef00ba313af78a3e9c329afa216eb3aa2a7b4613a").unwrap()[..],
|
&Vec::from_hex("b0287b4a252ac05af83d2dcef00ba313af78a3e9c329afa216eb3aa2a7b4613a").unwrap()[..],
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
cache.sequences.into_inner(),
|
cache.sequences.as_byte_array(),
|
||||||
&Vec::from_hex("18606b350cd8bf565266bc352f0caddcf01e8fa789dd8a15386327cf8cabe198").unwrap()[..],
|
&Vec::from_hex("18606b350cd8bf565266bc352f0caddcf01e8fa789dd8a15386327cf8cabe198").unwrap()[..],
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
cache.outputs.into_inner(),
|
cache.outputs.as_byte_array(),
|
||||||
&Vec::from_hex("de984f44532e2173ca0d64314fcefe6d30da6f8cf27bafa706da61df8a226c83").unwrap()[..],
|
&Vec::from_hex("de984f44532e2173ca0d64314fcefe6d30da6f8cf27bafa706da61df8a226c83").unwrap()[..],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -1773,15 +1773,15 @@ mod tests {
|
||||||
let cache = cache.segwit_cache();
|
let cache = cache.segwit_cache();
|
||||||
// Parse hex into Vec because BIP143 test vector displays forwards but our sha256d::Hash displays backwards.
|
// Parse hex into Vec because BIP143 test vector displays forwards but our sha256d::Hash displays backwards.
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
cache.prevouts.into_inner(),
|
cache.prevouts.as_byte_array(),
|
||||||
&Vec::from_hex("74afdc312af5183c4198a40ca3c1a275b485496dd3929bca388c4b5e31f7aaa0").unwrap()[..],
|
&Vec::from_hex("74afdc312af5183c4198a40ca3c1a275b485496dd3929bca388c4b5e31f7aaa0").unwrap()[..],
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
cache.sequences.into_inner(),
|
cache.sequences.as_byte_array(),
|
||||||
&Vec::from_hex("3bb13029ce7b1f559ef5e747fcac439f1455a2ec7c5f09b72290795e70665044").unwrap()[..],
|
&Vec::from_hex("3bb13029ce7b1f559ef5e747fcac439f1455a2ec7c5f09b72290795e70665044").unwrap()[..],
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
cache.outputs.into_inner(),
|
cache.outputs.as_byte_array(),
|
||||||
&Vec::from_hex("bc4d309071414bed932f98832b27b4d76dad7e6c1346f487a8fdbb8eb90307cc").unwrap()[..],
|
&Vec::from_hex("bc4d309071414bed932f98832b27b4d76dad7e6c1346f487a8fdbb8eb90307cc").unwrap()[..],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
@ -21,7 +21,7 @@ macro_rules! impl_hashencode {
|
||||||
impl $crate::consensus::Decodable for $hashtype {
|
impl $crate::consensus::Decodable for $hashtype {
|
||||||
fn consensus_decode<R: $crate::io::Read + ?Sized>(r: &mut R) -> Result<Self, $crate::consensus::encode::Error> {
|
fn consensus_decode<R: $crate::io::Read + ?Sized>(r: &mut R) -> Result<Self, $crate::consensus::encode::Error> {
|
||||||
use $crate::hashes::Hash;
|
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 {
|
impl AsRef<$crate::blockdata::script::PushBytes> for $hashtype {
|
||||||
fn as_ref(&self) -> &$crate::blockdata::script::PushBytes {
|
fn as_ref(&self) -> &$crate::blockdata::script::PushBytes {
|
||||||
use $crate::hashes::Hash;
|
use $crate::hashes::Hash;
|
||||||
self.as_inner().as_ref()
|
self.as_byte_array().into()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<$hashtype> for $crate::blockdata::script::PushBytesBuf {
|
impl From<$hashtype> for $crate::blockdata::script::PushBytesBuf {
|
||||||
fn from(hash: $hashtype) -> Self {
|
fn from(hash: $hashtype) -> Self {
|
||||||
use $crate::hashes::Hash;
|
use $crate::hashes::Hash;
|
||||||
hash.as_inner().into()
|
hash.as_byte_array().into()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
)*
|
)*
|
||||||
|
|
|
@ -305,7 +305,7 @@ impl PartialMerkleTree {
|
||||||
if hash_used != self.hashes.len() as u32 {
|
if hash_used != self.hashes.len() as u32 {
|
||||||
return Err(NotAllHashesConsumed);
|
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
|
/// 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 {
|
fn calc_hash(&self, height: u32, pos: u32, txids: &[Txid]) -> TxMerkleNode {
|
||||||
if height == 0 {
|
if height == 0 {
|
||||||
// Hash at height 0 is the txid itself
|
// 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 {
|
} else {
|
||||||
// Calculate left hash
|
// Calculate left hash
|
||||||
let left = self.calc_hash(height - 1, pos * 2, txids);
|
let left = self.calc_hash(height - 1, pos * 2, txids);
|
||||||
|
@ -384,7 +384,7 @@ impl PartialMerkleTree {
|
||||||
*hash_used += 1;
|
*hash_used += 1;
|
||||||
if height == 0 && parent_of_match {
|
if height == 0 && parent_of_match {
|
||||||
// in case of height 0, we have a matched txid
|
// 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);
|
indexes.push(pos);
|
||||||
}
|
}
|
||||||
Ok(hash)
|
Ok(hash)
|
||||||
|
@ -573,7 +573,7 @@ mod tests {
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
// Calculate the merkle root and height
|
// 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 =
|
let merkle_root_1: TxMerkleNode =
|
||||||
merkle_tree::calculate_root(hashes).expect("hashes is not empty").into();
|
merkle_tree::calculate_root(hashes).expect("hashes is not empty").into();
|
||||||
let mut height = 1;
|
let mut height = 1;
|
||||||
|
@ -741,7 +741,7 @@ mod tests {
|
||||||
let n = rng.gen_range(0..self.hashes.len());
|
let n = rng.gen_range(0..self.hashes.len());
|
||||||
let bit = rng.gen::<u8>();
|
let bit = rng.gen::<u8>();
|
||||||
let hashes = &mut self.hashes;
|
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);
|
hash[(bit >> 3) as usize] ^= 1 << (bit & 7);
|
||||||
hashes[n] = TxMerkleNode::from_slice(&hash).unwrap();
|
hashes[n] = TxMerkleNode::from_slice(&hash).unwrap();
|
||||||
}
|
}
|
||||||
|
|
|
@ -122,7 +122,7 @@ mod tests {
|
||||||
let block: Block = deserialize(&segwit_block[..]).expect("Failed to deserialize block");
|
let block: Block = deserialize(&segwit_block[..]).expect("Failed to deserialize block");
|
||||||
assert!(block.check_merkle_root()); // Sanity check.
|
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];
|
let mut hashes_array: [sha256d::Hash; 15] = [Hash::all_zeros(); 15];
|
||||||
for (i, hash) in hashes_iter.clone().enumerate() {
|
for (i, hash) in hashes_iter.clone().enumerate() {
|
||||||
|
|
|
@ -582,7 +582,7 @@ mod test {
|
||||||
flags: BloomFlags::All,
|
flags: BloomFlags::All,
|
||||||
}),
|
}),
|
||||||
NetworkMessage::FilterAdd(FilterAdd { data: script.as_bytes().to_vec() }),
|
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::FilterClear,
|
||||||
NetworkMessage::GetCFilters(GetCFilters {
|
NetworkMessage::GetCFilters(GetCFilters {
|
||||||
filter_type: 2,
|
filter_type: 2,
|
||||||
|
|
|
@ -196,7 +196,7 @@ impl Target {
|
||||||
#[cfg_attr(all(test, mutate), mutate)]
|
#[cfg_attr(all(test, mutate), mutate)]
|
||||||
pub fn is_met_by(&self, hash: BlockHash) -> bool {
|
pub fn is_met_by(&self, hash: BlockHash) -> bool {
|
||||||
use crate::hashes::Hash;
|
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
|
hash <= self.0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1492,7 +1492,7 @@ mod tests {
|
||||||
use crate::hashes::Hash;
|
use crate::hashes::Hash;
|
||||||
|
|
||||||
let hash = BlockHash::from_str("ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c").expect("failed to parse block 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));
|
assert!(target.is_met_by(hash));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -169,7 +169,7 @@ macro_rules! impl_psbt_hash_serialize {
|
||||||
($hash_type:ty) => {
|
($hash_type:ty) => {
|
||||||
impl $crate::psbt::serialize::Serialize for $hash_type {
|
impl $crate::psbt::serialize::Serialize for $hash_type {
|
||||||
fn serialize(&self) -> $crate::prelude::Vec<u8> {
|
fn serialize(&self) -> $crate::prelude::Vec<u8> {
|
||||||
self.into_inner().to_vec()
|
self.as_byte_array().to_vec()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
|
@ -309,9 +309,9 @@ impl Deserialize for taproot::Signature {
|
||||||
impl Serialize for (XOnlyPublicKey, TapLeafHash) {
|
impl Serialize for (XOnlyPublicKey, TapLeafHash) {
|
||||||
fn serialize(&self) -> Vec<u8> {
|
fn serialize(&self) -> Vec<u8> {
|
||||||
let ser_pk = self.0.serialize();
|
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(&ser_pk);
|
||||||
buf.extend(self.1.as_inner());
|
buf.extend(self.1.as_byte_array());
|
||||||
buf
|
buf
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -79,7 +79,7 @@ impl TapTweakHash {
|
||||||
/// Converts a `TapTweakHash` into a `Scalar` ready for use with key tweaking API.
|
/// Converts a `TapTweakHash` into a `Scalar` ready for use with key tweaking API.
|
||||||
pub fn to_scalar(self) -> Scalar {
|
pub fn to_scalar(self) -> Scalar {
|
||||||
// This is statistically extremely unlikely to panic.
|
// 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<TapLeafHash> for TapNodeHash {
|
impl From<TapLeafHash> 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.
|
/// Maximum depth of a taproot tree script spend path.
|
||||||
|
@ -690,7 +690,7 @@ impl TaprootMerkleBranch {
|
||||||
|
|
||||||
/// Serializes `self` as bytes.
|
/// Serializes `self` as bytes.
|
||||||
pub fn serialize(&self) -> Vec<u8> {
|
pub fn serialize(&self) -> Vec<u8> {
|
||||||
self.0.iter().flat_map(|e| e.as_inner()).copied().collect::<Vec<u8>>()
|
self.0.iter().flat_map(|e| e.as_byte_array()).copied().collect::<Vec<u8>>()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Appends elements to proof.
|
/// Appends elements to proof.
|
||||||
|
@ -1152,10 +1152,10 @@ mod test {
|
||||||
use crate::crypto::sighash::MIDSTATE_TAPSIGHASH;
|
use crate::crypto::sighash::MIDSTATE_TAPSIGHASH;
|
||||||
|
|
||||||
// check midstate against hard-coded values
|
// check midstate against hard-coded values
|
||||||
assert_eq!(MIDSTATE_TAPLEAF, tag_engine("TapLeaf").midstate().into_inner());
|
assert_eq!(MIDSTATE_TAPLEAF, tag_engine("TapLeaf").midstate().to_byte_array());
|
||||||
assert_eq!(MIDSTATE_TAPBRANCH, tag_engine("TapBranch").midstate().into_inner());
|
assert_eq!(MIDSTATE_TAPBRANCH, tag_engine("TapBranch").midstate().to_byte_array());
|
||||||
assert_eq!(MIDSTATE_TAPTWEAK, tag_engine("TapTweak").midstate().into_inner());
|
assert_eq!(MIDSTATE_TAPTWEAK, tag_engine("TapTweak").midstate().to_byte_array());
|
||||||
assert_eq!(MIDSTATE_TAPSIGHASH, tag_engine("TapSighash").midstate().into_inner());
|
assert_eq!(MIDSTATE_TAPSIGHASH, tag_engine("TapSighash").midstate().to_byte_array());
|
||||||
|
|
||||||
// test that engine creation roundtrips
|
// test that engine creation roundtrips
|
||||||
assert_eq!(tag_engine("TapLeaf").midstate(), TapLeafTag::engine().midstate());
|
assert_eq!(tag_engine("TapLeaf").midstate(), TapLeafTag::engine().midstate());
|
||||||
|
@ -1167,12 +1167,12 @@ mod test {
|
||||||
fn empty_hash(tag_name: &str) -> [u8; 32] {
|
fn empty_hash(tag_name: &str) -> [u8; 32] {
|
||||||
let mut e = tag_engine(tag_name);
|
let mut e = tag_engine(tag_name);
|
||||||
e.input(&[]);
|
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("TapLeaf"), TapLeafHash::hash(&[]).to_byte_array());
|
||||||
assert_eq!(empty_hash("TapBranch"), TapNodeHash::hash(&[]).into_inner());
|
assert_eq!(empty_hash("TapBranch"), TapNodeHash::hash(&[]).to_byte_array());
|
||||||
assert_eq!(empty_hash("TapTweak"), TapTweakHash::hash(&[]).into_inner());
|
assert_eq!(empty_hash("TapTweak"), TapTweakHash::hash(&[]).to_byte_array());
|
||||||
assert_eq!(empty_hash("TapSighash"), TapSighash::hash(&[]).into_inner());
|
assert_eq!(empty_hash("TapSighash"), TapSighash::hash(&[]).to_byte_array());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
|
@ -125,7 +125,7 @@ mod tests {
|
||||||
impl sha256t::Tag for TestHashTag {
|
impl sha256t::Tag for TestHashTag {
|
||||||
fn engine() -> sha256::HashEngine {
|
fn engine() -> sha256::HashEngine {
|
||||||
// The TapRoot TapLeaf midstate.
|
// 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)
|
sha256::HashEngine::from_midstate(midstate, 64)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -97,7 +97,7 @@ mod tests {
|
||||||
}
|
}
|
||||||
let manual_hash = Hash::from_engine(engine);
|
let manual_hash = Hash::from_engine(engine);
|
||||||
assert_eq!(hash, manual_hash);
|
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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -192,7 +192,7 @@ impl<T: Hash> borrow::Borrow<[u8]> for Hmac<T> {
|
||||||
|
|
||||||
impl<T: Hash> Hash for Hmac<T> {
|
impl<T: Hash> Hash for Hmac<T> {
|
||||||
type Engine = HmacEngine<T>;
|
type Engine = HmacEngine<T>;
|
||||||
type Inner = T::Inner;
|
type Bytes = T::Bytes;
|
||||||
|
|
||||||
fn from_engine(mut e: HmacEngine<T>) -> Hmac<T> {
|
fn from_engine(mut e: HmacEngine<T>) -> Hmac<T> {
|
||||||
let ihash = T::from_engine(e.iengine);
|
let ihash = T::from_engine(e.iengine);
|
||||||
|
@ -207,16 +207,16 @@ impl<T: Hash> Hash for Hmac<T> {
|
||||||
T::from_slice(sl).map(Hmac)
|
T::from_slice(sl).map(Hmac)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn into_inner(self) -> Self::Inner {
|
fn to_byte_array(self) -> Self::Bytes {
|
||||||
self.0.into_inner()
|
self.0.to_byte_array()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn as_inner(&self) -> &Self::Inner {
|
fn as_byte_array(&self) -> &Self::Bytes {
|
||||||
self.0.as_inner()
|
self.0.as_byte_array()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn from_inner(inner: T::Inner) -> Self {
|
fn from_byte_array(bytes: T::Bytes) -> Self {
|
||||||
Hmac(T::from_inner(inner))
|
Hmac(T::from_byte_array(bytes))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn all_zeros() -> Self {
|
fn all_zeros() -> Self {
|
||||||
|
@ -237,8 +237,8 @@ impl<T: Hash + Serialize> Serialize for Hmac<T> {
|
||||||
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
|
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
|
||||||
impl<'de, T: Hash + Deserialize<'de>> Deserialize<'de> for Hmac<T> {
|
impl<'de, T: Hash + Deserialize<'de>> Deserialize<'de> for Hmac<T> {
|
||||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Hmac<T>, D::Error> {
|
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Hmac<T>, D::Error> {
|
||||||
let inner = Deserialize::deserialize(d)?;
|
let bytes = Deserialize::deserialize(d)?;
|
||||||
Ok(Hmac(inner))
|
Ok(Hmac(bytes))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -365,7 +365,7 @@ mod tests {
|
||||||
engine.input(&test.input);
|
engine.input(&test.input);
|
||||||
let hash = Hmac::<sha256::Hash>::from_engine(engine);
|
let hash = Hmac::<sha256::Hash>::from_engine(engine);
|
||||||
assert_eq!(&hash[..], &test.output[..]);
|
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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -97,7 +97,7 @@ macro_rules! hash_trait_impls {
|
||||||
} else {
|
} else {
|
||||||
FromHex::from_byte_iter(HexIterator::new(s)?)?
|
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),*> {
|
impl<$($gen: $gent),*> crate::Hash for Hash<$($gen),*> {
|
||||||
type Engine = HashEngine;
|
type Engine = HashEngine;
|
||||||
type Inner = [u8; $bits / 8];
|
type Bytes = [u8; $bits / 8];
|
||||||
|
|
||||||
const LEN: usize = $bits / 8;
|
const LEN: usize = $bits / 8;
|
||||||
const DISPLAY_BACKWARD: bool = $reverse;
|
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
|
self.0
|
||||||
}
|
}
|
||||||
|
|
||||||
fn as_inner(&self) -> &Self::Inner {
|
fn as_byte_array(&self) -> &Self::Bytes {
|
||||||
&self.0
|
&self.0
|
||||||
}
|
}
|
||||||
|
|
||||||
fn from_inner(inner: Self::Inner) -> Self {
|
fn from_byte_array(bytes: Self::Bytes) -> Self {
|
||||||
Self::internal_new(inner)
|
Self::internal_new(bytes)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn all_zeros() -> Self {
|
fn all_zeros() -> Self {
|
||||||
|
|
|
@ -171,7 +171,7 @@ pub trait Hash: Copy + Clone + PartialEq + Eq + PartialOrd + Ord +
|
||||||
type Engine: HashEngine;
|
type Engine: HashEngine;
|
||||||
|
|
||||||
/// The byte array that represents the hash internally.
|
/// The byte array that represents the hash internally.
|
||||||
type Inner: hex::FromHex;
|
type Bytes: hex::FromHex + Copy;
|
||||||
|
|
||||||
/// Constructs a new engine.
|
/// Constructs a new engine.
|
||||||
fn engine() -> Self::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.
|
/// true for `Sha256dHash`, so here we are.
|
||||||
const DISPLAY_BACKWARD: bool = false;
|
const DISPLAY_BACKWARD: bool = false;
|
||||||
|
|
||||||
/// Unwraps the hash and returns the underlying byte array.
|
/// Returns the underlying byte array.
|
||||||
fn into_inner(self) -> Self::Inner;
|
fn to_byte_array(self) -> Self::Bytes;
|
||||||
|
|
||||||
/// Unwraps the hash and returns a reference to the underlying byte array.
|
/// Returns a reference to the underlying byte array.
|
||||||
fn as_inner(&self) -> &Self::Inner;
|
fn as_byte_array(&self) -> &Self::Bytes;
|
||||||
|
|
||||||
/// Constructs a hash from the underlying byte array.
|
/// 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.
|
/// Returns an all zero hash.
|
||||||
///
|
///
|
||||||
|
@ -231,11 +231,11 @@ mod tests {
|
||||||
#[test]
|
#[test]
|
||||||
fn convert_newtypes() {
|
fn convert_newtypes() {
|
||||||
let h1 = TestNewtype::hash(&[]);
|
let h1 = TestNewtype::hash(&[]);
|
||||||
let h2: TestNewtype2 = h1.as_hash().into();
|
let h2: TestNewtype2 = h1.to_raw_hash().into();
|
||||||
assert_eq!(&h1[..], &h2[..]);
|
assert_eq!(&h1[..], &h2[..]);
|
||||||
|
|
||||||
let h = sha256d::Hash::hash(&[]);
|
let h = sha256d::Hash::hash(&[]);
|
||||||
let h2: TestNewtype = h.to_string().parse().unwrap();
|
let h2: TestNewtype = h.to_string().parse().unwrap();
|
||||||
assert_eq!(h2.as_hash(), h);
|
assert_eq!(h2.to_raw_hash(), h);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -480,7 +480,7 @@ mod tests {
|
||||||
}
|
}
|
||||||
let manual_hash = ripemd160::Hash::from_engine(engine);
|
let manual_hash = ripemd160::Hash::from_engine(engine);
|
||||||
assert_eq!(hash, manual_hash);
|
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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -206,7 +206,7 @@ mod tests {
|
||||||
}
|
}
|
||||||
let manual_hash = sha1::Hash::from_engine(engine);
|
let manual_hash = sha1::Hash::from_engine(engine);
|
||||||
assert_eq!(hash, manual_hash);
|
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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -46,12 +46,12 @@ fn from_engine(mut e: HashEngine) -> Hash {
|
||||||
e.input(&(8 * data_len).to_be_bytes());
|
e.input(&(8 * data_len).to_be_bytes());
|
||||||
debug_assert_eq!(e.length % BLOCK_SIZE, 0);
|
debug_assert_eq!(e.length % BLOCK_SIZE, 0);
|
||||||
|
|
||||||
Hash(e.midstate().into_inner())
|
Hash(e.midstate().to_byte_array())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(fuzzing)]
|
#[cfg(fuzzing)]
|
||||||
fn from_engine(e: HashEngine) -> Hash {
|
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] {
|
if hash == [0; 32] {
|
||||||
// Assume sha256 is secure and never generate 0-hashes (which represent invalid
|
// Assume sha256 is secure and never generate 0-hashes (which represent invalid
|
||||||
// secp256k1 secret keys, causing downstream application breakage).
|
// secp256k1 secret keys, causing downstream application breakage).
|
||||||
|
@ -111,7 +111,7 @@ impl crate::HashEngine for HashEngine {
|
||||||
impl Hash {
|
impl Hash {
|
||||||
/// Iterate the sha256 algorithm to turn a sha256 hash into a sha256d hash
|
/// Iterate the sha256 algorithm to turn a sha256 hash into a sha256d hash
|
||||||
pub fn hash_again(&self) -> sha256d::Hash {
|
pub fn hash_again(&self) -> sha256d::Hash {
|
||||||
crate::Hash::from_inner(<Self as crate::Hash>::hash(&self.0).0)
|
crate::Hash::from_byte_array(<Self as crate::Hash>::hash(&self.0).0)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -149,7 +149,7 @@ impl Midstate {
|
||||||
const DISPLAY_BACKWARD: bool = true;
|
const DISPLAY_BACKWARD: bool = true;
|
||||||
|
|
||||||
/// Construct a new [`Midstate`] from the inner value.
|
/// 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)
|
Midstate(inner)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -165,7 +165,7 @@ impl Midstate {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Unwraps the [`Midstate`] and returns the underlying byte array.
|
/// 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
|
self.0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -176,7 +176,7 @@ impl hex::FromHex for Midstate {
|
||||||
I: Iterator<Item = Result<u8, hex::Error>> + ExactSizeIterator + DoubleEndedIterator,
|
I: Iterator<Item = Result<u8, hex::Error>> + ExactSizeIterator + DoubleEndedIterator,
|
||||||
{
|
{
|
||||||
// DISPLAY_BACKWARD is true
|
// 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);
|
let manual_hash = sha256::Hash::from_engine(engine);
|
||||||
assert_eq!(hash, manual_hash);
|
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!(
|
assert_eq!(
|
||||||
engine.midstate(),
|
engine.midstate(),
|
||||||
// RPC output
|
// RPC output
|
||||||
sha256::Midstate::from_inner([
|
sha256::Midstate::from_byte_array([
|
||||||
0x0b, 0xcf, 0xe0, 0xe5, 0x4e, 0x6c, 0xc7, 0xd3,
|
0x0b, 0xcf, 0xe0, 0xe5, 0x4e, 0x6c, 0xc7, 0xd3,
|
||||||
0x4f, 0x4f, 0x7c, 0x1d, 0xf0, 0xb0, 0xf5, 0x03,
|
0x4f, 0x4f, 0x7c, 0x1d, 0xf0, 0xb0, 0xf5, 0x03,
|
||||||
0xf2, 0xf7, 0x12, 0x91, 0x2a, 0x06, 0x05, 0xb4,
|
0xf2, 0xf7, 0x12, 0x91, 0x2a, 0x06, 0x05, 0xb4,
|
||||||
|
@ -455,7 +455,7 @@ mod tests {
|
||||||
0xd5, 0x69, 0x09, 0x59,
|
0xd5, 0x69, 0x09, 0x59,
|
||||||
];
|
];
|
||||||
let midstate_engine =
|
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);
|
let hash = sha256::Hash::from_engine(midstate_engine);
|
||||||
assert_eq!(hash, sha256::Hash(HASH_EXPECTED));
|
assert_eq!(hash, sha256::Hash(HASH_EXPECTED));
|
||||||
}
|
}
|
||||||
|
|
|
@ -89,7 +89,7 @@ mod tests {
|
||||||
let sha2d_hash = sha2_hash.hash_again();
|
let sha2d_hash = sha2_hash.hash_again();
|
||||||
assert_eq!(hash, sha2d_hash);
|
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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -88,7 +88,7 @@ crate::internal_macros::hash_trait_impls!(256, true, T: Tag);
|
||||||
fn from_engine<T: Tag>(e: sha256::HashEngine) -> Hash<T> {
|
fn from_engine<T: Tag>(e: sha256::HashEngine) -> Hash<T> {
|
||||||
use crate::Hash as _;
|
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.
|
/// Macro used to define a newtype tagged hash.
|
||||||
|
@ -110,7 +110,7 @@ macro_rules! sha256t_hash_newtype {
|
||||||
|
|
||||||
impl $crate::sha256t::Tag for $tag {
|
impl $crate::sha256t::Tag for $tag {
|
||||||
fn engine() -> $crate::sha256::HashEngine {
|
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)
|
$crate::sha256::HashEngine::from_midstate(midstate, $midstate_len)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -141,7 +141,7 @@ mod tests {
|
||||||
impl sha256t::Tag for TestHashTag {
|
impl sha256t::Tag for TestHashTag {
|
||||||
fn engine() -> sha256::HashEngine {
|
fn engine() -> sha256::HashEngine {
|
||||||
// The TapRoot TapLeaf midstate.
|
// 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)
|
sha256::HashEngine::from_midstate(midstate, 64)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -379,7 +379,7 @@ mod tests {
|
||||||
}
|
}
|
||||||
let manual_hash = sha512::Hash::from_engine(engine);
|
let manual_hash = sha512::Hash::from_engine(engine);
|
||||||
assert_eq!(hash, manual_hash);
|
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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -165,7 +165,7 @@ mod tests {
|
||||||
}
|
}
|
||||||
let manual_hash = sha512_256::Hash::from_engine(engine);
|
let manual_hash = sha512_256::Hash::from_engine(engine);
|
||||||
assert_eq!(hash, manual_hash);
|
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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -173,18 +173,23 @@ macro_rules! hash_newtype {
|
||||||
$crate::borrow_slice_impl!($newtype);
|
$crate::borrow_slice_impl!($newtype);
|
||||||
|
|
||||||
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
|
#[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)
|
$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
|
#[allow(unused)] // the user of macro may not need this
|
||||||
pub fn as_hash(&self) -> $hash {
|
pub fn to_raw_hash(self) -> $hash {
|
||||||
// Hashes implement Copy so don't need into_hash.
|
|
||||||
self.0
|
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 {
|
impl $crate::_export::_core::convert::From<$hash> for $newtype {
|
||||||
|
@ -202,7 +207,7 @@ macro_rules! hash_newtype {
|
||||||
|
|
||||||
impl $crate::Hash for $newtype {
|
impl $crate::Hash for $newtype {
|
||||||
type Engine = <$hash as $crate::Hash>::Engine;
|
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 LEN: usize = <$hash as $crate::Hash>::LEN;
|
||||||
const DISPLAY_BACKWARD: bool = $crate::hash_newtype_get_direction!($hash, $(#[$($type_attrs)*])*);
|
const DISPLAY_BACKWARD: bool = $crate::hash_newtype_get_direction!($hash, $(#[$($type_attrs)*])*);
|
||||||
|
@ -221,18 +226,18 @@ macro_rules! hash_newtype {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn from_inner(inner: Self::Inner) -> Self {
|
fn from_byte_array(bytes: Self::Bytes) -> Self {
|
||||||
$newtype(<$hash as $crate::Hash>::from_inner(inner))
|
$newtype(<$hash as $crate::Hash>::from_byte_array(bytes))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn into_inner(self) -> Self::Inner {
|
fn to_byte_array(self) -> Self::Bytes {
|
||||||
self.0.into_inner()
|
self.0.to_byte_array()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn as_inner(&self) -> &Self::Inner {
|
fn as_byte_array(&self) -> &Self::Bytes {
|
||||||
self.0.as_inner()
|
self.0.as_byte_array()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
|
@ -248,12 +253,12 @@ macro_rules! hash_newtype {
|
||||||
use $crate::hex::{HexIterator, FromHex};
|
use $crate::hex::{HexIterator, FromHex};
|
||||||
use $crate::Hash;
|
use $crate::Hash;
|
||||||
|
|
||||||
let inner: <$hash as Hash>::Inner = if <Self as $crate::Hash>::DISPLAY_BACKWARD {
|
let inner: <$hash as Hash>::Bytes = if <Self as $crate::Hash>::DISPLAY_BACKWARD {
|
||||||
FromHex::from_byte_iter(HexIterator::new(s)?.rev())?
|
FromHex::from_byte_iter(HexIterator::new(s)?.rev())?
|
||||||
} else {
|
} else {
|
||||||
FromHex::from_byte_iter(HexIterator::new(s)?)?
|
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() {
|
fn hash_as_ref_array() {
|
||||||
let hash = sha256::Hash::hash(&[3, 50]);
|
let hash = sha256::Hash::hash(&[3, 50]);
|
||||||
let r = AsRef::<[u8; 32]>::as_ref(&hash);
|
let r = AsRef::<[u8; 32]>::as_ref(&hash);
|
||||||
assert_eq!(r, hash.as_inner());
|
assert_eq!(r, hash.as_byte_array());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn hash_as_ref_slice() {
|
fn hash_as_ref_slice() {
|
||||||
let hash = sha256::Hash::hash(&[3, 50]);
|
let hash = sha256::Hash::hash(&[3, 50]);
|
||||||
let r = AsRef::<[u8]>::as_ref(&hash);
|
let r = AsRef::<[u8]>::as_ref(&hash);
|
||||||
assert_eq!(r, hash.as_inner());
|
assert_eq!(r, hash.as_byte_array());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
@ -390,7 +395,7 @@ mod test {
|
||||||
|
|
||||||
let hash = sha256::Hash::hash(&[3, 50]);
|
let hash = sha256::Hash::hash(&[3, 50]);
|
||||||
let borrowed: &[u8] = hash.borrow();
|
let borrowed: &[u8] = hash.borrow();
|
||||||
assert_eq!(borrowed, hash.as_inner());
|
assert_eq!(borrowed, hash.as_byte_array());
|
||||||
}
|
}
|
||||||
|
|
||||||
hash_newtype! {
|
hash_newtype! {
|
||||||
|
@ -430,13 +435,13 @@ mod test {
|
||||||
fn inner_hash_as_ref_array() {
|
fn inner_hash_as_ref_array() {
|
||||||
let hash = TestHash::all_zeros();
|
let hash = TestHash::all_zeros();
|
||||||
let r = AsRef::<[u8; 32]>::as_ref(&hash);
|
let r = AsRef::<[u8; 32]>::as_ref(&hash);
|
||||||
assert_eq!(r, hash.as_inner());
|
assert_eq!(r, hash.as_byte_array());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn inner_hash_as_ref_slice() {
|
fn inner_hash_as_ref_slice() {
|
||||||
let hash = TestHash::all_zeros();
|
let hash = TestHash::all_zeros();
|
||||||
let r = AsRef::<[u8]>::as_ref(&hash);
|
let r = AsRef::<[u8]>::as_ref(&hash);
|
||||||
assert_eq!(r, hash.as_inner());
|
assert_eq!(r, hash.as_byte_array());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue