Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

hashes: make hex optional #2711

Draft
wants to merge 8 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 1 addition & 2 deletions Cargo-minimal.lock
Original file line number Diff line number Diff line change
Expand Up @@ -165,8 +165,7 @@ checksum = "62aca2aba2d62b4a7f5b33f3712cb1b0692779a56fb510499d5c0aa594daeaf3"
[[package]]
name = "hex-conservative"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1aa273bf451e37ed35ced41c71a5e2a4e29064afb104158f2514bcd71c2c986"
source = "git+https://github.com/tcharding/hex-conservative?branch=05-16-fmt#a06b7ed236a56b881f1b60f213fea04880bde4c4"
dependencies = [
"arrayvec",
]
Expand Down
3 changes: 1 addition & 2 deletions Cargo-recent.lock
Original file line number Diff line number Diff line change
Expand Up @@ -164,8 +164,7 @@ checksum = "62aca2aba2d62b4a7f5b33f3712cb1b0692779a56fb510499d5c0aa594daeaf3"
[[package]]
name = "hex-conservative"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1aa273bf451e37ed35ced41c71a5e2a4e29064afb104158f2514bcd71c2c986"
source = "git+https://github.com/tcharding/hex-conservative?branch=05-16-fmt#a06b7ed236a56b881f1b60f213fea04880bde4c4"
dependencies = [
"arrayvec",
]
Expand Down
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,7 @@ path = "io"

[patch.crates-io.bitcoin-units]
path = "units"

[patch.crates-io.hex-conservative]
git = "https://github.com/tcharding/hex-conservative"
branch = "05-16-fmt"
2 changes: 1 addition & 1 deletion base58/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ use core::{fmt, str};
#[cfg(feature = "std")]
pub use std::{string::String, vec::Vec};

use hashes::{sha256d, Hash};
use hashes::sha256d;

use crate::error::{IncorrectChecksumError, TooShortError};

Expand Down
1 change: 0 additions & 1 deletion bitcoin/examples/sign-tx-segwit-v0.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

use std::str::FromStr;

use bitcoin::hashes::Hash;
use bitcoin::locktime::absolute;
use bitcoin::secp256k1::{rand, Message, Secp256k1, SecretKey, Signing};
use bitcoin::sighash::{EcdsaSighashType, SighashCache};
Expand Down
1 change: 0 additions & 1 deletion bitcoin/examples/sign-tx-taproot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

use std::str::FromStr;

use bitcoin::hashes::Hash;
use bitcoin::key::{Keypair, TapTweak, TweakedKeypair, UntweakedPublicKey};
use bitcoin::locktime::absolute;
use bitcoin::secp256k1::{rand, Message, Secp256k1, SecretKey, Signing, Verification};
Expand Down
2 changes: 1 addition & 1 deletion bitcoin/src/address/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ use core::marker::PhantomData;
use core::str::FromStr;

use bech32::primitives::hrp::Hrp;
use hashes::{sha256, Hash, HashEngine};
use hashes::{sha256, HashEngine};
use secp256k1::{Secp256k1, Verification, XOnlyPublicKey};

use crate::blockdata::constants::{
Expand Down
2 changes: 1 addition & 1 deletion bitcoin/src/bip152.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use core::{convert, fmt, mem};
#[cfg(feature = "std")]
use std::error;

use hashes::{sha256, siphash24, Hash};
use hashes::{sha256, siphash24};
use internals::impl_array_newtype;
use io::{BufRead, Write};

Expand Down
6 changes: 3 additions & 3 deletions bitcoin/src/bip158.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
use core::cmp::{self, Ordering};
use core::fmt::{self, Display, Formatter};

use hashes::{sha256d, siphash24, Hash};
use hashes::{sha256d, siphash24};
use internals::write_err;
use io::{BufRead, Write};

Expand All @@ -58,9 +58,9 @@ const M: u64 = 784931;

hashes::hash_newtype! {
/// Filter hash, as defined in BIP-157
pub struct FilterHash(sha256d::Hash);
pub struct FilterHash(sha256d);
/// Filter header, as defined in BIP-157
pub struct FilterHeader(sha256d::Hash);
pub struct FilterHeader(sha256d);
}

impl_hashencode!(FilterHash);
Expand Down
20 changes: 10 additions & 10 deletions bitcoin/src/bip32.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use core::ops::Index;
use core::str::FromStr;
use core::{fmt, slice};

use hashes::{hash160, hash_newtype, sha512, Hash, HashEngine, Hmac, HmacEngine};
use hashes::{hash160, hash_newtype, hmac, HashEngine};
use internals::{impl_array_newtype, write_err};
use io::Write;
use secp256k1::{Secp256k1, XOnlyPublicKey};
Expand Down Expand Up @@ -43,7 +43,8 @@ impl_array_newtype!(ChainCode, u8, 32);
impl_bytes_newtype!(ChainCode, 32);

impl ChainCode {
fn from_hmac(hmac: Hmac<sha512::Hash>) -> Self {
/// Creates a `ChainCdoe` from the hash created with a `hmac::Engine<sha512::Engine>`.
fn from_hmac(hmac: hmac::Hash<64>) -> Self {
hmac.as_ref()[32..].try_into().expect("half of hmac is guaranteed to be 32 bytes")
}
}
Expand All @@ -56,7 +57,7 @@ impl_bytes_newtype!(Fingerprint, 4);

hash_newtype! {
/// Extended key identifier as defined in BIP-32.
pub struct XKeyIdentifier(hash160::Hash);
pub struct XKeyIdentifier(hash160);
}

/// Extended private key
Expand Down Expand Up @@ -556,9 +557,9 @@ impl From<InvalidBase58PayloadLengthError> for Error {
impl Xpriv {
/// Construct a new master key from a seed value
pub fn new_master(network: impl Into<NetworkKind>, seed: &[u8]) -> Result<Xpriv, Error> {
let mut hmac_engine: HmacEngine<sha512::Hash> = HmacEngine::new(b"Bitcoin seed");
let mut hmac_engine = hmac::new_engine_sha512(b"Bitcoin seed");
hmac_engine.input(seed);
let hmac_result: Hmac<sha512::Hash> = Hmac::from_engine(hmac_engine);
let hmac_result = hmac::Hash::from_engine(hmac_engine);

Ok(Xpriv {
network: network.into(),
Expand Down Expand Up @@ -599,7 +600,7 @@ impl Xpriv {

/// Private->Private child key derivation
fn ckd_priv<C: secp256k1::Signing>(&self, secp: &Secp256k1<C>, i: ChildNumber) -> Xpriv {
let mut hmac_engine: HmacEngine<sha512::Hash> = HmacEngine::new(&self.chain_code[..]);
let mut hmac_engine = hmac::new_engine_sha512(&self.chain_code[..]);
match i {
ChildNumber::Normal { .. } => {
// Non-hardened key: compute public data and use that
Expand All @@ -615,7 +616,7 @@ impl Xpriv {
}

hmac_engine.input(&u32::from(i).to_be_bytes());
let hmac_result: Hmac<sha512::Hash> = Hmac::from_engine(hmac_engine);
let hmac_result = hmac::Hash::from_engine(hmac_engine);
let sk = secp256k1::SecretKey::from_slice(&hmac_result.as_ref()[..32])
.expect("statistically impossible to hit");
let tweaked =
Expand Down Expand Up @@ -730,12 +731,11 @@ impl Xpub {
match i {
ChildNumber::Hardened { .. } => Err(Error::CannotDeriveFromHardenedKey),
ChildNumber::Normal { index: n } => {
let mut hmac_engine: HmacEngine<sha512::Hash> =
HmacEngine::new(&self.chain_code[..]);
let mut hmac_engine = hmac::new_engine_sha512(&self.chain_code[..]);
hmac_engine.input(&self.public_key.serialize()[..]);
hmac_engine.input(&n.to_be_bytes());

let hmac_result: Hmac<sha512::Hash> = Hmac::from_engine(hmac_engine);
let hmac_result = hmac::Hash::from_engine(hmac_engine);

let private_key = secp256k1::SecretKey::from_slice(&hmac_result.as_ref()[..32])?;
let chain_code = ChainCode::from_hmac(hmac_result);
Expand Down
16 changes: 8 additions & 8 deletions bitcoin/src/blockdata/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

use core::fmt;

use hashes::{sha256d, Hash, HashEngine};
use hashes::{sha256d, HashEngine};
use io::{BufRead, Write};

use super::Weight;
Expand All @@ -23,13 +23,13 @@ use crate::{merkle_tree, VarInt};

hashes::hash_newtype! {
/// A bitcoin block hash.
pub struct BlockHash(sha256d::Hash);
pub struct BlockHash(sha256d);
/// A hash of the Merkle tree branch or root for transactions.
pub struct TxMerkleNode(sha256d::Hash);
pub struct TxMerkleNode(pub(crate) sha256d);
/// A hash corresponding to the Merkle tree root for witness data.
pub struct WitnessMerkleNode(sha256d::Hash);
pub struct WitnessMerkleNode(sha256d);
/// A hash corresponding to the witness structure commitment in the coinbase transaction.
pub struct WitnessCommitment(sha256d::Hash);
pub struct WitnessCommitment(sha256d);
}
impl_hashencode!(BlockHash);
impl_hashencode!(TxMerkleNode);
Expand Down Expand Up @@ -291,7 +291,7 @@ impl Block {

/// Computes the transaction merkle root.
pub fn compute_merkle_root(&self) -> Option<TxMerkleNode> {
let hashes = self.txdata.iter().map(|obj| obj.compute_txid().to_raw_hash());
let hashes = self.txdata.iter().map(|obj| obj.compute_txid());
merkle_tree::calculate_root(hashes).map(|h| h.into())
}

Expand All @@ -311,9 +311,9 @@ impl Block {
let hashes = self.txdata.iter().enumerate().map(|(i, t)| {
if i == 0 {
// Replace the first hash with zeroes.
Wtxid::all_zeros().to_raw_hash()
Wtxid::all_zeros()
} else {
t.compute_wtxid().to_raw_hash()
t.compute_wtxid()
}
});
merkle_tree::calculate_root(hashes).map(|h| h.into())
Expand Down
2 changes: 1 addition & 1 deletion bitcoin/src/blockdata/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
//! consensus code. In particular, it defines the genesis block and its
//! single transaction.

use hashes::{sha256d, Hash};
use hashes::sha256d;
use hex_lit::hex;
use internals::impl_array_newtype;

Expand Down
1 change: 0 additions & 1 deletion bitcoin/src/blockdata/script/borrowed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use core::ops::{
Bound, Index, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive,
};

use hashes::Hash;
use secp256k1::{Secp256k1, Verification};

use super::PushBytes;
Expand Down
4 changes: 2 additions & 2 deletions bitcoin/src/blockdata/script/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,9 @@ pub use self::{

hashes::hash_newtype! {
/// A hash of Bitcoin Script bytecode.
pub struct ScriptHash(hash160::Hash);
pub struct ScriptHash(hash160);
/// SegWit version of a Bitcoin Script bytecode hash.
pub struct WScriptHash(sha256::Hash);
pub struct WScriptHash(sha256);
}
impl_asref_push_bytes!(ScriptHash, WScriptHash);

Expand Down
1 change: 0 additions & 1 deletion bitcoin/src/blockdata/script/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

use core::str::FromStr;

use hashes::Hash;
use hex_lit::hex;

use super::*;
Expand Down
1 change: 0 additions & 1 deletion bitcoin/src/blockdata/script/witness_program.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@

use core::fmt;

use hashes::Hash as _;
use internals::array_vec::ArrayVec;
use secp256k1::{Secp256k1, Verification};

Expand Down
20 changes: 10 additions & 10 deletions bitcoin/src/blockdata/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

use core::{cmp, fmt, str};

use hashes::{sha256d, Hash};
use hashes::sha256d;
use internals::write_err;
use io::{BufRead, Write};
use units::parse;
Expand Down Expand Up @@ -43,10 +43,10 @@ hashes::hash_newtype! {
/// versions of the Bitcoin Core software itself, this and other [`sha256d::Hash`] types, are
/// serialized in reverse byte order when converted to a hex string via [`std::fmt::Display`]
/// trait operations. See [`hashes::Hash::DISPLAY_BACKWARD`] for more details.
pub struct Txid(sha256d::Hash);
pub struct Txid(pub(crate) sha256d);

/// A bitcoin witness transaction ID.
pub struct Wtxid(sha256d::Hash);
pub struct Wtxid(pub(crate) sha256d);
}
impl_hashencode!(Txid);
impl_hashencode!(Wtxid);
Expand Down Expand Up @@ -2442,22 +2442,22 @@ mod tests {
let outpoint = OutPoint::default();

let debug = "OutPoint { txid: 0000000000000000000000000000000000000000000000000000000000000000, vout: 4294967295 }";
assert_eq!(debug, format!("{:?}", &outpoint));
assert_eq!(format!("{:?}", &outpoint), debug);

let display = "0000000000000000000000000000000000000000000000000000000000000000:4294967295";
assert_eq!(display, format!("{}", &outpoint));
assert_eq!(format!("{}", &outpoint), display);

let pretty_debug = "OutPoint {\n txid: 0000000000000000000000000000000000000000000000000000000000000000,\n vout: 4294967295,\n}";
assert_eq!(pretty_debug, format!("{:#?}", &outpoint));
let pretty_debug = "OutPoint {\n txid: 0x0000000000000000000000000000000000000000000000000000000000000000,\n vout: 4294967295,\n}";
assert_eq!(format!("{:#?}", &outpoint), pretty_debug);

let debug_txid = "0000000000000000000000000000000000000000000000000000000000000000";
assert_eq!(debug_txid, format!("{:?}", &outpoint.txid));
assert_eq!(format!("{:?}", &outpoint.txid), debug_txid);

let display_txid = "0000000000000000000000000000000000000000000000000000000000000000";
assert_eq!(display_txid, format!("{}", &outpoint.txid));
assert_eq!(format!("{}", &outpoint.txid), display_txid);

let pretty_txid = "0x0000000000000000000000000000000000000000000000000000000000000000";
assert_eq!(pretty_txid, format!("{:#}", &outpoint.txid));
assert_eq!(format!("{:#}", &outpoint.txid), pretty_txid);
}
}

Expand Down
10 changes: 5 additions & 5 deletions bitcoin/src/consensus/encode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

use core::{fmt, mem};

use hashes::{sha256, sha256d, Hash};
use hashes::{sha256, sha256d};
use hex::error::{InvalidCharError, OddLengthStringError};
use internals::write_err;
use io::{BufRead, Cursor, Read, Write};
Expand Down Expand Up @@ -767,7 +767,7 @@ impl Decodable for Box<[u8]> {

/// Does a double-SHA256 on `data` and returns the first 4 bytes.
fn sha2_checksum(data: &[u8]) -> [u8; 4] {
let checksum = <sha256d::Hash as Hash>::hash(data);
let checksum = sha256d::Hash::hash(data);
[checksum[0], checksum[1], checksum[2], checksum[3]]
}

Expand Down Expand Up @@ -868,7 +868,7 @@ impl Encodable for sha256d::Hash {

impl Decodable for sha256d::Hash {
fn consensus_decode<R: BufRead + ?Sized>(r: &mut R) -> Result<Self, Error> {
Ok(Self::from_byte_array(<<Self as Hash>::Bytes>::consensus_decode(r)?))
Ok(Self::from_byte_array(<[u8; sha256d::Hash::LEN]>::consensus_decode(r)?))
}
}

Expand All @@ -880,7 +880,7 @@ impl Encodable for sha256::Hash {

impl Decodable for sha256::Hash {
fn consensus_decode<R: BufRead + ?Sized>(r: &mut R) -> Result<Self, Error> {
Ok(Self::from_byte_array(<<Self as Hash>::Bytes>::consensus_decode(r)?))
Ok(Self::from_byte_array(<[u8; sha256::Hash::LEN]>::consensus_decode(r)?))
}
}

Expand All @@ -892,7 +892,7 @@ impl Encodable for TapLeafHash {

impl Decodable for TapLeafHash {
fn consensus_decode<R: BufRead + ?Sized>(r: &mut R) -> Result<Self, Error> {
Ok(Self::from_byte_array(<<Self as Hash>::Bytes>::consensus_decode(r)?))
Ok(Self::from_byte_array(<[u8; TapLeafHash::LEN]>::consensus_decode(r)?))
}
}

Expand Down
6 changes: 3 additions & 3 deletions bitcoin/src/crypto/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use core::fmt::{self, Write as _};
use core::ops;
use core::str::FromStr;

use hashes::{hash160, Hash};
use hashes::hash160;
use hex::{FromHex, HexToArrayError};
use internals::array_vec::ArrayVec;
use internals::write_err;
Expand Down Expand Up @@ -255,9 +255,9 @@ impl FromStr for PublicKey {

hashes::hash_newtype! {
/// A hash of a public key.
pub struct PubkeyHash(hash160::Hash);
pub struct PubkeyHash(hash160);
/// SegWit version of a public key hash.
pub struct WPubkeyHash(hash160::Hash);
pub struct WPubkeyHash(hash160);
}
impl_asref_push_bytes!(PubkeyHash, WPubkeyHash);

Expand Down