Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions bitcoin/examples/bip32.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ use std::env;

use bitcoin::address::{Address, KnownHrp};
use bitcoin::bip32::{ChildNumber, DerivationPath, Xpriv, Xpub};
use bitcoin::hex;
use bitcoin::{CompressedPublicKey, NetworkKind};
use bitcoin::{hex, CompressedPublicKey, NetworkKind};

fn main() {
// This example derives root xprv from a 32-byte seed,
Expand Down
4 changes: 2 additions & 2 deletions bitcoin/src/blockdata/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,10 @@ pub use primitives::block::{
};
#[doc(no_inline)]
pub use primitives::block::{InvalidBlockError, ParseBlockError, ParseHeaderError};
#[doc(inline)]
pub use units::block::{BlockHeight, BlockHeightInterval, BlockMtp, BlockMtpInterval};
#[doc(no_inline)]
pub use units::block::TooBigForRelativeHeightError;
#[doc(inline)]
pub use units::block::{BlockHeight, BlockHeightInterval, BlockMtp, BlockMtpInterval};

#[deprecated(since = "TBD", note = "use `BlockHeightInterval` instead")]
#[doc(hidden)]
Expand Down
3 changes: 1 addition & 2 deletions bitcoin/src/blockdata/script/owned.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ use super::{
opcode_to_verify, write_scriptint, Builder, Error, Instruction, PushBytes, ScriptBuf,
ScriptExtPriv as _, ScriptPubKeyBuf,
};
use crate::hex;
use crate::key::{
PubkeyHash, PublicKey, TapTweak, TweakedPublicKey, UntweakedPublicKey, WPubkeyHash,
};
Expand All @@ -21,7 +20,7 @@ use crate::script::witness_program::{WitnessProgram, P2A_PROGRAM};
use crate::script::witness_version::WitnessVersion;
use crate::script::{self, ScriptHash, WScriptHash};
use crate::taproot::TapNodeHash;
use crate::{consensus, internal_macros};
use crate::{consensus, hex, internal_macros};

internal_macros::define_extension_trait! {
/// Extension functionality for the [`ScriptBuf`] type.
Expand Down
6 changes: 3 additions & 3 deletions bitcoin/src/blockdata/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1281,10 +1281,9 @@ mod tests {
use super::*;
use crate::consensus::encode::{deserialize, serialize};
use crate::constants::WITNESS_SCALE_FACTOR;
use crate::hex;
use crate::parse_int;
use crate::script::ScriptSigBuf;
use crate::sighash::EcdsaSighashType;
use crate::{hex, parse_int};

const SOME_TX: &str = "0100000001a15d57094aa7a21a28cb20b59aab8fc7d1149a3bdbcddba9c622e4f5f6a99ece010000006c493046022100f93bb0e7d8db7bd46e40132d1f8242026e045f03a0efe71bbb8e3f475e970d790221009337cd7f1f929f00cc6ff01f03729b069a7c21b59b1736ddfee5db5946c5da8c0121033b9b137ee87d5a812d6f506efdd37f0affa7ffc310711c06c7f3e097c9447c52ffffffff0100e1f505000000001976a9140389035a9225b3839e2bbf32d826a1e222031fd888ac00000000";

Expand Down Expand Up @@ -1639,7 +1638,8 @@ mod tests {

#[test]
fn huge_witness() {
let hex = hex::decode_to_vec(include_str!("../../tests/data/huge_witness.hex").trim()).unwrap();
let hex =
hex::decode_to_vec(include_str!("../../tests/data/huge_witness.hex").trim()).unwrap();
deserialize::<Transaction>(&hex).unwrap();
}

Expand Down
8 changes: 2 additions & 6 deletions bitcoin/src/consensus/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,15 +136,11 @@ pub mod hex {
}

impl super::IntoDeError for DecodeInitError {
fn into_de_error<E: serde::de::Error>(self) -> E {
serde::de::Error::custom(self.0)
}
fn into_de_error<E: serde::de::Error>(self) -> E { serde::de::Error::custom(self.0) }
}

impl super::IntoDeError for DecodeError {
fn into_de_error<E: serde::de::Error>(self) -> E {
serde::de::Error::custom(self.0)
}
fn into_de_error<E: serde::de::Error>(self) -> E { serde::de::Error::custom(self.0) }
}
}

Expand Down
12 changes: 8 additions & 4 deletions bitcoin/src/crypto/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -705,15 +705,19 @@ impl FromStr for PublicKey {
match s.len() {
66 => {
let bytes = hex::decode_to_array::<33>(s).map_err(|e| match e {
DecodeFixedLengthBytesError::InvalidChar(e) => ParsePublicKeyError::InvalidChar(e),
DecodeFixedLengthBytesError::InvalidLength(_) => unreachable!("length checked already"),
DecodeFixedLengthBytesError::InvalidChar(e) =>
ParsePublicKeyError::InvalidChar(e),
DecodeFixedLengthBytesError::InvalidLength(_) =>
unreachable!("length checked already"),
})?;
Ok(Self::from_slice(&bytes)?)
}
130 => {
let bytes = hex::decode_to_array::<65>(s).map_err(|e| match e {
DecodeFixedLengthBytesError::InvalidChar(e) => ParsePublicKeyError::InvalidChar(e),
DecodeFixedLengthBytesError::InvalidLength(_) => unreachable!("length checked already"),
DecodeFixedLengthBytesError::InvalidChar(e) =>
ParsePublicKeyError::InvalidChar(e),
DecodeFixedLengthBytesError::InvalidLength(_) =>
unreachable!("length checked already"),
})?;
Ok(Self::from_slice(&bytes)?)
}
Expand Down
27 changes: 17 additions & 10 deletions bitcoin/src/crypto/sighash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -339,8 +339,7 @@ impl<'s> ScriptPath<'s> {
pub fn leaf_hash(&self) -> TapLeafHash {
let mut enc = sha256t::Hash::<TapLeafTag>::engine();

enc
.write_all(&[self.leaf_version.to_consensus()])
enc.write_all(&[self.leaf_version.to_consensus()])
.expect("writing to hash engine should never fail");
enc = hashes::encode_to_engine(self.script, enc);

Expand Down Expand Up @@ -649,12 +648,16 @@ impl<R: Borrow<Transaction>> SighashCache<R> {
if !anyone_can_pay {
writer.write_all(&self.common_cache().prevouts.to_byte_array())?;
writer.write_all(
&self.taproot_cache(prevouts.get_all().map_err(SigningDataError::sighash)?).amounts.to_byte_array()
&self
.taproot_cache(prevouts.get_all().map_err(SigningDataError::sighash)?)
.amounts
.to_byte_array(),
)?;
writer.write_all(
&self.taproot_cache(prevouts.get_all().map_err(SigningDataError::sighash)?)
&self
.taproot_cache(prevouts.get_all().map_err(SigningDataError::sighash)?)
.script_pubkeys
.to_byte_array()
.to_byte_array(),
)?;
writer.write_all(&self.common_cache().sequences.to_byte_array())?;
}
Expand Down Expand Up @@ -714,7 +717,8 @@ impl<R: Borrow<Transaction>> SighashCache<R> {
// sha_single_output (32): the SHA256 of the corresponding output in CTxOut format.
if sighash == TapSighashType::Single {
let mut enc = sha256::Hash::engine();
let txout = self.tx
let txout = self
.tx
.borrow()
.outputs
.get(input_index)
Expand Down Expand Up @@ -863,7 +867,8 @@ impl<R: Borrow<Transaction>> SighashCache<R> {
&& input_index < self.tx.borrow().outputs.len()
{
let mut single_enc = LegacySighash::engine();
single_enc = hashes::encode_to_engine(&self.tx.borrow().outputs[input_index], single_enc);
single_enc =
hashes::encode_to_engine(&self.tx.borrow().outputs[input_index], single_enc);
let hash = LegacySighash::from_engine(single_enc);
writer.write_all(hash.as_byte_array())?;
} else {
Expand Down Expand Up @@ -1136,7 +1141,10 @@ impl<R: Borrow<Transaction>> SighashCache<R> {
let mut enc_script_pubkeys = sha256::Hash::engine();
for prevout in prevouts {
enc_amounts = hashes::encode_to_engine(&prevout.borrow().amount, enc_amounts);
enc_script_pubkeys = hashes::encode_to_engine(&(*prevout.borrow().script_pubkey), enc_script_pubkeys);
enc_script_pubkeys = hashes::encode_to_engine(
&(*prevout.borrow().script_pubkey),
enc_script_pubkeys,
);
}
TaprootCache {
amounts: sha256::Hash::from_engine(enc_amounts),
Expand Down Expand Up @@ -1536,12 +1544,11 @@ mod tests {

use super::*;
use crate::consensus::deserialize;
use crate::hex;
use crate::locktime::absolute;
use crate::script::{
ScriptBufExt as _, ScriptPubKey, ScriptPubKeyBuf, TapScriptBuf, WitnessScriptBuf,
};
use crate::TxIn;
use crate::{hex, TxIn};

extern crate serde_json;

Expand Down
3 changes: 1 addition & 2 deletions bitcoin/src/psbt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1308,7 +1308,6 @@ mod tests {

use super::*;
use crate::bip32::{ChildNumber, DerivationPath};
use crate::hex;
use crate::locktime::absolute;
use crate::network::NetworkKind;
use crate::psbt::serialize::{Deserialize, Serialize};
Expand All @@ -1317,7 +1316,7 @@ mod tests {
};
use crate::transaction::{self, OutPoint, TxIn};
use crate::witness::Witness;
use crate::Sequence;
use crate::{hex, Sequence};

#[track_caller]
pub fn hex_psbt(s: &str) -> Result<Psbt, crate::psbt::error::Error> {
Expand Down
5 changes: 2 additions & 3 deletions bitcoin/tests/bip_174.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,12 @@ use std::collections::BTreeMap;
use bitcoin::amount::{Amount, Denomination};
use bitcoin::bip32::{Fingerprint, IntoDerivationPath, KeySource, Xpriv, Xpub};
use bitcoin::consensus::encode::{deserialize, serialize_hex};
use bitcoin::hex;
use bitcoin::opcodes::all::OP_0;
use bitcoin::psbt::{Psbt, PsbtSighashType};
use bitcoin::script::{PushBytes, ScriptBuf, ScriptBufExt as _};
use bitcoin::{
absolute, script, transaction, NetworkKind, OutPoint, PrivateKey, PublicKey, ScriptPubKeyBuf,
ScriptSigBuf, Sequence, Transaction, TxIn, TxOut, Witness,
absolute, hex, script, transaction, NetworkKind, OutPoint, PrivateKey, PublicKey,
ScriptPubKeyBuf, ScriptSigBuf, Sequence, Transaction, TxIn, TxOut, Witness,
};

#[track_caller]
Expand Down
8 changes: 4 additions & 4 deletions bitcoin/tests/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,14 @@ use std::collections::BTreeMap;
use bincode::serialize;
use bitcoin::bip32::{ChildNumber, KeySource, Xpriv, Xpub};
use bitcoin::hashes::{hash160, ripemd160, sha256, sha256d};
use bitcoin::hex;
use bitcoin::locktime::{absolute, relative};
use bitcoin::psbt::{raw, Input, Output, Psbt, PsbtSighashType};
use bitcoin::script::ScriptBufExt as _;
use bitcoin::sighash::{EcdsaSighashType, TapSighashType};
use bitcoin::taproot::{self, ControlBlock, LeafVersion, TapTree, TaprootBuilder};
use bitcoin::witness::Witness;
use bitcoin::{
ecdsa, transaction, Address, Amount, NetworkKind, OutPoint, PrivateKey, PublicKey,
ecdsa, hex, transaction, Address, Amount, NetworkKind, OutPoint, PrivateKey, PublicKey,
ScriptPubKeyBuf, ScriptSigBuf, Sequence, TapScriptBuf, Target, Transaction, TxIn, TxOut, Txid,
Work,
};
Expand Down Expand Up @@ -99,8 +98,9 @@ fn serde_regression_out_point() {

#[test]
fn serde_regression_witness() {
let w0 = hex::decode_to_vec("03d2e15674941bad4a996372cb87e1856d3652606d98562fe39c5e9e7e413f2105")
.unwrap();
let w0 =
hex::decode_to_vec("03d2e15674941bad4a996372cb87e1856d3652606d98562fe39c5e9e7e413f2105")
.unwrap();
let w1 = hex::decode_to_vec("000000").unwrap();
let vec = [w0, w1];
let witness = Witness::from_slice(&vec);
Expand Down
116 changes: 55 additions & 61 deletions consensus_encoding/src/decode/decoders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -382,10 +382,8 @@ where
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.state {
Decoder2State::First(a, b) =>
f.debug_tuple("First").field(a).field(b).finish(),
Decoder2State::Second(out, b) =>
f.debug_tuple("Second").field(out).field(b).finish(),
Decoder2State::First(a, b) => f.debug_tuple("First").field(a).field(b).finish(),
Decoder2State::Second(out, b) => f.debug_tuple("Second").field(out).field(b).finish(),
Decoder2State::Errored => write!(f, "Errored"),
}
}
Expand Down Expand Up @@ -1122,12 +1120,10 @@ mod tests {
let got = decoder.end().unwrap_err();
assert!(matches!(
got,
CompactSizeDecoderError(E::ValueExceedsLimit(
LengthPrefixExceedsMaxError {
limit: MAX_VEC_SIZE,
value: EXCESS_VEC_SIZE,
}
)),
CompactSizeDecoderError(E::ValueExceedsLimit(LengthPrefixExceedsMaxError {
limit: MAX_VEC_SIZE,
value: EXCESS_VEC_SIZE,
})),
));
}

Expand All @@ -1147,12 +1143,10 @@ mod tests {
let got = decoder.end().unwrap_err();
assert!(matches!(
got,
CompactSizeDecoderError(E::ValueExceedsLimit(
LengthPrefixExceedsMaxError {
limit: 240,
value: 241,
}
)),
CompactSizeDecoderError(E::ValueExceedsLimit(LengthPrefixExceedsMaxError {
limit: 240,
value: 241,
})),
));
}

Expand Down Expand Up @@ -1329,51 +1323,51 @@ mod tests {
#[test]
#[cfg(feature = "alloc")]
fn vec_decoder_empty() {
// Empty with a couple of arbitrary extra bytes.
let encoded = vec![0x00, 0xFF, 0xFF];
let mut slice = encoded.as_slice();
let mut decoder = Test::decoder();
assert!(!decoder.push_bytes(&mut slice).unwrap());
let got = decoder.end().unwrap();
let want = Test(vec![]);
assert_eq!(got, want);
}
#[test]
#[cfg(feature = "alloc")]
fn vec_decoder_one_item() {
let encoded = vec![0x01, 0xEF, 0xBE, 0xAD, 0xDE];
let mut slice = encoded.as_slice();
let mut decoder = Test::decoder();
decoder.push_bytes(&mut slice).unwrap();
let got = decoder.end().unwrap();
let want = Test(vec![Inner(0xDEAD_BEEF)]);
assert_eq!(got, want);
}
#[test]
#[cfg(feature = "alloc")]
fn vec_decoder_two_items() {
let encoded = vec![0x02, 0xEF, 0xBE, 0xAD, 0xDE, 0xBE, 0xBA, 0xFE, 0xCA];
let mut slice = encoded.as_slice();
let mut decoder = Test::decoder();
decoder.push_bytes(&mut slice).unwrap();
let got = decoder.end().unwrap();
let want = Test(vec![Inner(0xDEAD_BEEF), Inner(0xCAFE_BABE)]);
assert_eq!(got, want);
}
#[test]
#[cfg(feature = "alloc")]
// Empty with a couple of arbitrary extra bytes.
let encoded = vec![0x00, 0xFF, 0xFF];

let mut slice = encoded.as_slice();
let mut decoder = Test::decoder();
assert!(!decoder.push_bytes(&mut slice).unwrap());

let got = decoder.end().unwrap();
let want = Test(vec![]);

assert_eq!(got, want);
}

#[test]
#[cfg(feature = "alloc")]
fn vec_decoder_one_item() {
let encoded = vec![0x01, 0xEF, 0xBE, 0xAD, 0xDE];

let mut slice = encoded.as_slice();
let mut decoder = Test::decoder();
decoder.push_bytes(&mut slice).unwrap();

let got = decoder.end().unwrap();
let want = Test(vec![Inner(0xDEAD_BEEF)]);

assert_eq!(got, want);
}

#[test]
#[cfg(feature = "alloc")]
fn vec_decoder_two_items() {
let encoded = vec![0x02, 0xEF, 0xBE, 0xAD, 0xDE, 0xBE, 0xBA, 0xFE, 0xCA];

let mut slice = encoded.as_slice();
let mut decoder = Test::decoder();
decoder.push_bytes(&mut slice).unwrap();

let got = decoder.end().unwrap();
let want = Test(vec![Inner(0xDEAD_BEEF), Inner(0xCAFE_BABE)]);

assert_eq!(got, want);
}

#[test]
#[cfg(feature = "alloc")]
fn vec_decoder_reserves_in_batches() {
// A small number of extra elements so we extend exactly by the remainder
// instead of another full batch.
Expand Down
Loading