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
10 changes: 2 additions & 8 deletions bitcoin/examples/ecdsa-psbt-simple.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,7 @@ const SPEND_AMOUNT: Amount = Amount::from_sat_u32(25_000_000);
const CHANGE_AMOUNT: Amount = Amount::from_sat_u32(4_990_000); // 10_000 sat fee.

// Derive the external address xpriv.
fn get_external_address_xpriv(
master_xpriv: Xpriv,
index: u32,
) -> Xpriv {
fn get_external_address_xpriv(master_xpriv: Xpriv, index: u32) -> Xpriv {
let derivation_path =
BIP84_DERIVATION_PATH.into_derivation_path().expect("valid derivation path");
let child_xpriv =
Expand All @@ -69,10 +66,7 @@ fn get_external_address_xpriv(
}

// Derive the internal address xpriv.
fn get_internal_address_xpriv(
master_xpriv: Xpriv,
index: u32,
) -> Xpriv {
fn get_internal_address_xpriv(master_xpriv: Xpriv, index: u32) -> Xpriv {
let derivation_path =
BIP84_DERIVATION_PATH.into_derivation_path().expect("valid derivation path");
let child_xpriv =
Expand Down
12 changes: 3 additions & 9 deletions bitcoin/examples/ecdsa-psbt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,7 @@ impl ColdStorage {
// Hardened children require secret data to derive.

let path = "84h/0h/0h".into_derivation_path()?;
let account_0_xpriv =
master_xpriv.derive_xpriv(&path).expect("derivation path is short");
let account_0_xpriv = master_xpriv.derive_xpriv(&path).expect("derivation path is short");
let account_0_xpub = Xpub::from_xpriv(&account_0_xpriv);

let path = INPUT_UTXO_DERIVATION_PATH.into_derivation_path()?;
Expand All @@ -131,10 +130,7 @@ impl ColdStorage {
fn master_fingerprint(&self) -> Fingerprint { self.master_xpub.fingerprint() }

/// Signs `psbt` with this signer.
fn sign_psbt(
&self,
mut psbt: Psbt,
) -> Result<Psbt> {
fn sign_psbt(&self, mut psbt: Psbt) -> Result<Psbt> {
match psbt.sign(&self.master_xpriv) {
Ok(keys) => assert_eq!(keys.len(), 1),
Err((_, e)) => {
Expand Down Expand Up @@ -249,9 +245,7 @@ impl WatchOnly {
/// "m/84h/0h/0h/1/0"). A real wallet would have access to the chain so could determine if an
/// address has been used or not. We ignore this detail and just re-use the first change address
/// without loss of generality.
fn change_address(
&self,
) -> Result<(CompressedPublicKey, Address, DerivationPath)> {
fn change_address(&self) -> Result<(CompressedPublicKey, Address, DerivationPath)> {
let path = [ChildNumber::ONE_NORMAL, ChildNumber::ZERO_NORMAL];
let derived = self.account_0_xpub.derive_xpub(path)?;

Expand Down
10 changes: 2 additions & 8 deletions bitcoin/examples/taproot-psbt-simple.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,7 @@ const SPEND_AMOUNT: Amount = Amount::from_sat_u32(25_000_000);
const CHANGE_AMOUNT: Amount = Amount::from_sat_u32(4_990_000); // 10_000 sat fee.

// Derive the external address xpriv.
fn get_external_address_xpriv(
master_xpriv: Xpriv,
index: u32,
) -> Xpriv {
fn get_external_address_xpriv(master_xpriv: Xpriv, index: u32) -> Xpriv {
let derivation_path =
BIP86_DERIVATION_PATH.into_derivation_path().expect("valid derivation path");
let child_xpriv =
Expand All @@ -67,10 +64,7 @@ fn get_external_address_xpriv(
}

// Derive the internal address xpriv.
fn get_internal_address_xpriv(
master_xpriv: Xpriv,
index: u32,
) -> Xpriv {
fn get_internal_address_xpriv(master_xpriv: Xpriv, index: u32) -> Xpriv {
let derivation_path =
BIP86_DERIVATION_PATH.into_derivation_path().expect("valid derivation path");
let child_xpriv =
Expand Down
9 changes: 3 additions & 6 deletions bitcoin/examples/taproot-psbt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -291,8 +291,7 @@ fn generate_bip86_key_spend_tx(
.get(&input.tap_internal_key.ok_or("internal key missing in PSBT")?)
.ok_or("missing Taproot key origin")?;

let secret_key =
master_xpriv.derive_xpriv(derivation_path)?.to_private_key().inner;
let secret_key = master_xpriv.derive_xpriv(derivation_path)?.to_private_key().inner;
sign_psbt_taproot(
secret_key,
input.tap_internal_key.unwrap(),
Expand Down Expand Up @@ -482,10 +481,8 @@ impl BenefactorWallet {
.derive_xpriv(&new_derivation_path)
.expect("derivation path is short")
.to_keypair();
let beneficiary_key = self
.beneficiary_xpub
.derive_xpub(&new_derivation_path)?
.to_x_only_public_key();
let beneficiary_key =
self.beneficiary_xpub.derive_xpub(&new_derivation_path)?.to_x_only_public_key();

// Build up the leaf script and combine with internal key into a Taproot commitment
let lock_time = absolute::LockTime::from_height(
Expand Down
14 changes: 3 additions & 11 deletions bitcoin/src/bip152.rs
Original file line number Diff line number Diff line change
Expand Up @@ -400,9 +400,7 @@ impl BlockTransactions {

#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for ShortId {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
Ok(Self(u.arbitrary()?))
}
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> { Ok(Self(u.arbitrary()?)) }
}

#[cfg(feature = "arbitrary")]
Expand All @@ -427,20 +425,14 @@ impl<'a> Arbitrary<'a> for HeaderAndShortIds {
#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for BlockTransactions {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
Ok(Self {
block_hash: u.arbitrary()?,
transactions: Vec::<Transaction>::arbitrary(u)?,
})
Ok(Self { block_hash: u.arbitrary()?, transactions: Vec::<Transaction>::arbitrary(u)? })
}
}

#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for BlockTransactionsRequest {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
Ok(Self {
block_hash: u.arbitrary()?,
indexes: Vec::<u64>::arbitrary(u)?,
})
Ok(Self { block_hash: u.arbitrary()?, indexes: Vec::<u64>::arbitrary(u)? })
}
}

Expand Down
8 changes: 2 additions & 6 deletions bitcoin/src/bip158.rs
Original file line number Diff line number Diff line change
Expand Up @@ -486,9 +486,7 @@ pub struct BitStreamReader<'a, R: ?Sized> {

impl<'a, R: BufRead + ?Sized> BitStreamReader<'a, R> {
/// Constructs a new [`BitStreamReader`] that reads bitwise from a given `reader`.
pub fn new(reader: &'a mut R) -> Self {
BitStreamReader { buffer: [0u8], reader, offset: 8 }
}
pub fn new(reader: &'a mut R) -> Self { BitStreamReader { buffer: [0u8], reader, offset: 8 } }

/// Reads nbit bits, returning the bits in a `u64` starting with the rightmost bit.
///
Expand Down Expand Up @@ -534,9 +532,7 @@ pub struct BitStreamWriter<'a, W> {

impl<'a, W: Write> BitStreamWriter<'a, W> {
/// Constructs a new [`BitStreamWriter`] that writes bitwise to a given `writer`.
pub fn new(writer: &'a mut W) -> Self {
BitStreamWriter { buffer: [0u8], writer, offset: 0 }
}
pub fn new(writer: &'a mut W) -> Self { BitStreamWriter { buffer: [0u8], writer, offset: 0 } }

/// Writes nbits bits from data.
pub fn write(&mut self, data: u64, mut nbits: u8) -> Result<usize, io::Error> {
Expand Down
64 changes: 16 additions & 48 deletions bitcoin/src/bip32.rs
Original file line number Diff line number Diff line change
Expand Up @@ -617,9 +617,7 @@ impl From<base58::Error> for ParseError {
}

impl From<InvalidBase58PayloadLengthError> for ParseError {
fn from(e: InvalidBase58PayloadLengthError) -> Self {
Self::InvalidBase58PayloadLength(e)
}
fn from(e: InvalidBase58PayloadLengthError) -> Self { Self::InvalidBase58PayloadLength(e) }
}

/// A BIP-0032 error
Expand Down Expand Up @@ -735,9 +733,7 @@ impl Xpriv {
}

/// Constructs a new extended public key from this extended private key.
pub fn to_xpub(self) -> Xpub {
Xpub::from_xpriv(&self)
}
pub fn to_xpub(self) -> Xpub { Xpub::from_xpriv(&self) }

/// Constructs a new BIP-0340 keypair for Schnorr signatures and Taproot use matching the internal
/// secret key representation.
Expand All @@ -750,20 +746,14 @@ impl Xpriv {
///
/// The `path` argument can be both of type `DerivationPath` or `Vec<ChildNumber>`.
#[deprecated(since = "TBD", note = "use `derive_xpriv()` instead")]
pub fn derive_priv<P: AsRef<[ChildNumber]>>(
&self,
path: P,
) -> Result<Self, DerivationError> {
pub fn derive_priv<P: AsRef<[ChildNumber]>>(&self, path: P) -> Result<Self, DerivationError> {
self.derive_xpriv(path)
}

/// Derives an extended private key from a path.
///
/// The `path` argument can be both of type `DerivationPath` or `Vec<ChildNumber>`.
pub fn derive_xpriv<P: AsRef<[ChildNumber]>>(
&self,
path: P,
) -> Result<Self, DerivationError> {
pub fn derive_xpriv<P: AsRef<[ChildNumber]>>(&self, path: P) -> Result<Self, DerivationError> {
let mut sk: Self = *self;
for cnum in path.as_ref() {
sk = sk.ckd_priv(*cnum)?;
Expand All @@ -772,10 +762,7 @@ impl Xpriv {
}

/// Private->Private child key derivation
fn ckd_priv(
&self,
i: ChildNumber,
) -> Result<Self, DerivationError> {
fn ckd_priv(&self, i: ChildNumber) -> Result<Self, DerivationError> {
let mut engine = HmacEngine::<sha512::HashEngine>::new(&self.chain_code[..]);
match i {
ChildNumber::Normal { .. } => {
Expand All @@ -793,9 +780,10 @@ impl Xpriv {

engine.input(&u32::from(i).to_be_bytes());
let hmac: Hmac<sha512::Hash> = engine.finalize();
let sk =
secp256k1::SecretKey::from_secret_bytes(*hmac.as_byte_array().split_array::<32, 32>().0)
.expect("statistically impossible to hit");
let sk = secp256k1::SecretKey::from_secret_bytes(
*hmac.as_byte_array().split_array::<32, 32>().0,
)
.expect("statistically impossible to hit");
let tweaked =
sk.add_tweak(&self.private_key.into()).expect("statistically impossible to hit");

Expand Down Expand Up @@ -852,9 +840,7 @@ impl Xpriv {
}

/// Returns the HASH160 of the public key belonging to the xpriv
pub fn identifier(&self) -> XKeyIdentifier {
Xpub::from_xpriv(self).identifier()
}
pub fn identifier(&self) -> XKeyIdentifier { Xpub::from_xpriv(self).identifier() }

/// Returns the first four bytes of the identifier
pub fn fingerprint(&self) -> Fingerprint {
Expand All @@ -865,9 +851,7 @@ impl Xpriv {
impl Xpub {
/// Constructs a new extended public key from an extended private key.
#[deprecated(since = "TBD", note = "use `from_xpriv()` instead")]
pub fn from_priv(sk: &Xpriv) -> Self {
Self::from_xpriv(sk)
}
pub fn from_priv(sk: &Xpriv) -> Self { Self::from_xpriv(sk) }

/// Constructs a new extended public key from an extended private key.
pub fn from_xpriv(xpriv: &Xpriv) -> Self {
Expand Down Expand Up @@ -901,20 +885,14 @@ impl Xpub {
///
/// The `path` argument can be any type implementing `AsRef<ChildNumber>`, such as `DerivationPath`, for instance.
#[deprecated(since = "TBD", note = "use `derive_xpub()` instead")]
pub fn derive_pub<P: AsRef<[ChildNumber]>>(
&self,
path: P,
) -> Result<Self, DerivationError> {
pub fn derive_pub<P: AsRef<[ChildNumber]>>(&self, path: P) -> Result<Self, DerivationError> {
self.derive_xpub(path)
}

/// Attempts to derive an extended public key from a path.
///
/// The `path` argument can be any type implementing `AsRef<ChildNumber>`, such as `DerivationPath`, for instance.
pub fn derive_xpub<P: AsRef<[ChildNumber]>>(
&self,
path: P,
) -> Result<Self, DerivationError> {
pub fn derive_xpub<P: AsRef<[ChildNumber]>>(&self, path: P) -> Result<Self, DerivationError> {
let mut pk: Self = *self;
for cnum in path.as_ref() {
pk = pk.ckd_pub(*cnum)?
Expand Down Expand Up @@ -946,10 +924,7 @@ impl Xpub {
}

/// Public->Public child key derivation
pub fn ckd_pub(
&self,
i: ChildNumber,
) -> Result<Self, DerivationError> {
pub fn ckd_pub(&self, i: ChildNumber) -> Result<Self, DerivationError> {
let (sk, chain_code) = self.ckd_pub_tweak(i)?;
let tweaked =
self.public_key.add_exp_tweak(&sk.into()).expect("cryptographically unreachable");
Expand Down Expand Up @@ -1305,10 +1280,7 @@ mod tests {
// Check derivation convenience method for Xpub, should error
// appropriately if any ChildNumber is hardened
if path.0.iter().any(|cnum| cnum.is_hardened()) {
assert_eq!(
pk.derive_xpub(&path),
Err(DerivationError::CannotDeriveHardenedChild)
);
assert_eq!(pk.derive_xpub(&path), Err(DerivationError::CannotDeriveHardenedChild));
} else {
assert_eq!(&pk.derive_xpub(&path).unwrap().to_string()[..], expected_pk);
}
Expand All @@ -1323,10 +1295,7 @@ mod tests {
assert_eq!(pk, pk2);
}
Hardened { .. } => {
assert_eq!(
pk.ckd_pub(num),
Err(DerivationError::CannotDeriveHardenedChild)
);
assert_eq!(pk.ckd_pub(num), Err(DerivationError::CannotDeriveHardenedChild));
pk = Xpub::from_xpriv(&sk);
}
}
Expand Down Expand Up @@ -1387,7 +1356,6 @@ mod tests {

#[test]
fn vector_1() {

let seed = hex!("000102030405060708090a0b0c0d0e0f");

// m
Expand Down
2 changes: 1 addition & 1 deletion bitcoin/src/blockdata/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use crate::consensus::encode::{self, Decodable, Encodable, WriteExt as _};
use crate::merkle_tree::{MerkleNode as _, TxMerkleNode, WitnessMerkleNode};
use crate::network::Params;
use crate::prelude::Vec;
use crate::script::{self, ScriptIntError, ScriptExt as _};
use crate::script::{self, ScriptExt as _, ScriptIntError};
use crate::transaction::{Coinbase, Transaction, TransactionExt as _, Wtxid};
use crate::{internal_macros, BlockTime, Target, Weight, Work};

Expand Down
7 changes: 3 additions & 4 deletions bitcoin/src/blockdata/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ pub mod locktime {
pub use units::locktime::absolute::{error, Height, LockTime, MedianTimePast};
#[doc(no_inline)]
pub use units::locktime::absolute::{
ConversionError, IncompatibleHeightError, IncompatibleTimeError, ParseHeightError, ParseTimeError,
ConversionError, IncompatibleHeightError, IncompatibleTimeError, ParseHeightError,
ParseTimeError,
};

#[deprecated(since = "TBD", note = "use `MedianTimePast` instead")]
Expand Down Expand Up @@ -76,9 +77,7 @@ pub mod locktime {

/// Re-export everything from the `units::locktime::relative` module.
#[doc(inline)]
pub use units::locktime::relative::{
error, LockTime, NumberOf512Seconds, NumberOfBlocks,
};
pub use units::locktime::relative::{error, LockTime, NumberOf512Seconds, NumberOfBlocks};
#[doc(no_inline)]
pub use units::locktime::relative::{
DisabledLockTimeError, InvalidHeightError, InvalidTimeError, IsSatisfiedByError,
Expand Down
8 changes: 5 additions & 3 deletions bitcoin/src/blockdata/script/push_bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

//! Contains `PushBytes` & co

use core::ops::{Deref, DerefMut};
use core::fmt;
use core::ops::{Deref, DerefMut};

use crate::crypto::{ecdsa, taproot};
use crate::prelude::{Borrow, BorrowMut};
Expand Down Expand Up @@ -422,14 +422,16 @@ impl BorrowMut<PushBytes> for PushBytesBuf {
impl AsRef<PushBytes> for ecdsa::SerializedSignature {
#[inline]
fn as_ref(&self) -> &PushBytes {
<&PushBytes>::try_from(<Self as AsRef<[u8]>>::as_ref(self)).expect("max length 73 bytes is valid")
<&PushBytes>::try_from(<Self as AsRef<[u8]>>::as_ref(self))
.expect("max length 73 bytes is valid")
}
}

impl AsRef<PushBytes> for taproot::SerializedSignature {
#[inline]
fn as_ref(&self) -> &PushBytes {
<&PushBytes>::try_from(<Self as AsRef<[u8]>>::as_ref(self)).expect("max length 65 bytes is valid")
<&PushBytes>::try_from(<Self as AsRef<[u8]>>::as_ref(self))
.expect("max length 65 bytes is valid")
}
}

Expand Down
6 changes: 4 additions & 2 deletions bitcoin/src/blockdata/script/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -395,13 +395,15 @@ fn scriptint_round_trip() {
Ok(i),
PushBytes::read_scriptint(
<&PushBytes>::try_from(build_scriptint(i).as_slice()).unwrap()
).map(i64::from)
)
.map(i64::from)
);
assert_eq!(
Ok(-i),
PushBytes::read_scriptint(
<&PushBytes>::try_from(build_scriptint(-i).as_slice()).unwrap()
).map(i64::from)
)
.map(i64::from)
);
assert_eq!(Ok(i), read_scriptint_non_minimal(&build_scriptint(i)).map(i64::from));
assert_eq!(Ok(-i), read_scriptint_non_minimal(&build_scriptint(-i)).map(i64::from));
Expand Down
Loading