From e3ca08ef4abac6b7184a74d7c500b2f7ccbe46a8 Mon Sep 17 00:00:00 2001 From: valued mammal Date: Tue, 31 Mar 2026 15:00:49 -0400 Subject: [PATCH 1/3] fmt: Set style edition to 2021 This is to reduce noise related to formatting when we change the rust edition to 2024. --- rustfmt.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/rustfmt.toml b/rustfmt.toml index 505d959b..1b52dc8d 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,3 +1,4 @@ comment_width = 100 format_code_in_doc_comments = true wrap_comments = true +style_edition = "2021" From 8ea0cc2ce74ea6af42aa6ec8cb9ac4b4d88351b7 Mon Sep 17 00:00:00 2001 From: valued mammal Date: Tue, 31 Mar 2026 15:11:26 -0400 Subject: [PATCH 2/3] chore: Update rust edition to 2024 in Cargo.toml Removed explicit `ref` binding modifiers, as otherwise rustc complains with "cannot explicitly borrow within an implicitly borrowing pattern." Refer to https://doc.rust-lang.org/reference/patterns.html#binding-modes for details. --- Cargo.toml | 2 +- src/descriptor/mod.rs | 2 +- src/descriptor/policy.rs | 12 +++++------- 3 files changed, 7 insertions(+), 9 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index a2ced37e..04c0baa1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,7 +9,7 @@ keywords = ["bitcoin", "wallet", "descriptor", "psbt"] readme = "README.md" license = "MIT OR Apache-2.0" authors = ["Bitcoin Dev Kit Developers"] -edition = "2021" +edition = "2024" rust-version = "1.85.0" [package.metadata.docs.rs] diff --git a/src/descriptor/mod.rs b/src/descriptor/mod.rs index 60cadf7d..e2acbe89 100644 --- a/src/descriptor/mod.rs +++ b/src/descriptor/mod.rs @@ -237,7 +237,7 @@ impl IntoWalletDescriptor for DescriptorTemplateOut { // reset the `network_kind` to make sure the wallet struct gets a // descriptor with the right `network_kind` everywhere. let pk = match pk { - DescriptorPublicKey::XPub(ref xpub) => { + DescriptorPublicKey::XPub(xpub) => { let mut xpub = xpub.clone(); xpub.xkey.network = self.network_kind; diff --git a/src/descriptor/policy.rs b/src/descriptor/policy.rs index 044937cb..9d3ac62d 100644 --- a/src/descriptor/policy.rs +++ b/src/descriptor/policy.rs @@ -319,8 +319,8 @@ impl Satisfaction { Satisfaction::PartialComplete { .. } => Err(PolicyError::AddOnPartialComplete), Satisfaction::Partial { n, - ref mut conditions, - ref mut items, + conditions, + items, .. } => { if inner_index >= *n || items.contains(&inner_index) { @@ -1133,17 +1133,15 @@ impl ExtractPolicy for Descriptor { secp, ))), ShInner::Ms(ms) => Ok(ms.extract_policy(signers, build_sat, secp)?), - ShInner::SortedMulti(ref keys) => make_sortedmulti(keys, signers, build_sat, secp), + ShInner::SortedMulti(keys) => make_sortedmulti(keys, signers, build_sat, secp), ShInner::Wsh(wsh) => match wsh.as_inner() { WshInner::Ms(ms) => Ok(ms.extract_policy(signers, build_sat, secp)?), - WshInner::SortedMulti(ref keys) => { - make_sortedmulti(keys, signers, build_sat, secp) - } + WshInner::SortedMulti(keys) => make_sortedmulti(keys, signers, build_sat, secp), }, }, Descriptor::Wsh(wsh) => match wsh.as_inner() { WshInner::Ms(ms) => Ok(ms.extract_policy(signers, build_sat, secp)?), - WshInner::SortedMulti(ref keys) => make_sortedmulti(keys, signers, build_sat, secp), + WshInner::SortedMulti(keys) => make_sortedmulti(keys, signers, build_sat, secp), }, Descriptor::Bare(ms) => Ok(ms.as_inner().extract_policy(signers, build_sat, secp)?), Descriptor::Tr(tr) => { From 3adf695c34eaa91b34ea14a9daf4cf1437094a2a Mon Sep 17 00:00:00 2001 From: valued mammal Date: Tue, 31 Mar 2026 15:23:08 -0400 Subject: [PATCH 3/3] fmt: Adopt 2024 style edition Removed style_edition from rustfmt.toml and ran cargo +nightly fmt. --- examples/bitcoind_rpc.rs | 6 +- examples/compiler.rs | 2 +- examples/electrum.rs | 4 +- examples/esplora_async.rs | 6 +- examples/esplora_blocking.rs | 4 +- examples/mnemonic_to_descriptors.rs | 2 +- examples/policy.rs | 2 +- rustfmt.toml | 1 - src/descriptor/checksum.rs | 4 +- src/descriptor/dsl.rs | 75 +++++++++------- src/descriptor/mod.rs | 49 ++++++---- src/descriptor/policy.rs | 30 +++---- src/descriptor/template.rs | 6 +- src/keys/bip39.rs | 23 +++-- src/keys/mod.rs | 20 +++-- src/lib.rs | 2 +- src/persist_test_utils.rs | 13 ++- src/test_utils.rs | 16 ++-- src/types.rs | 2 +- src/wallet/changeset.rs | 6 +- src/wallet/coin_selection.rs | 18 ++-- src/wallet/error.rs | 9 +- src/wallet/event.rs | 2 +- src/wallet/export.rs | 9 +- src/wallet/migration.rs | 4 +- src/wallet/mod.rs | 47 +++++----- src/wallet/params.rs | 4 +- src/wallet/persisted.rs | 2 +- src/wallet/signer.rs | 19 ++-- src/wallet/tx_builder.rs | 56 ++++++------ src/wallet/utils.rs | 6 +- tests/add_foreign_utxo.rs | 4 +- tests/build_fee_bump.rs | 6 +- tests/common.rs | 2 +- tests/persisted_wallet.rs | 14 +-- tests/psbt.rs | 18 ++-- tests/wallet.rs | 134 +++++++++++++++++----------- tests/wallet_event.rs | 2 +- 38 files changed, 364 insertions(+), 265 deletions(-) diff --git a/examples/bitcoind_rpc.rs b/examples/bitcoind_rpc.rs index f0bbd729..c63f2b0d 100644 --- a/examples/bitcoind_rpc.rs +++ b/examples/bitcoind_rpc.rs @@ -1,16 +1,16 @@ use bdk_bitcoind_rpc::{ - bitcoincore_rpc::{Auth, Client, RpcApi}, Emitter, MempoolEvent, + bitcoincore_rpc::{Auth, Client, RpcApi}, }; use bdk_wallet::rusqlite::Connection; use bdk_wallet::{ - bitcoin::{Block, Network}, KeychainKind, Wallet, + bitcoin::{Block, Network}, }; use clap::{self, Parser}; use std::{ path::PathBuf, - sync::{mpsc::sync_channel, Arc}, + sync::{Arc, mpsc::sync_channel}, thread::spawn, time::Instant, }; diff --git a/examples/compiler.rs b/examples/compiler.rs index b2b307ba..2a28519f 100644 --- a/examples/compiler.rs +++ b/examples/compiler.rs @@ -18,8 +18,8 @@ use core::error::Error; use std::str::FromStr; use bitcoin::Network; -use miniscript::policy::Concrete; use miniscript::Descriptor; +use miniscript::policy::Concrete; use bdk_wallet::{KeychainKind, Wallet}; diff --git a/examples/electrum.rs b/examples/electrum.rs index 8ccbe130..e89c1175 100644 --- a/examples/electrum.rs +++ b/examples/electrum.rs @@ -1,12 +1,12 @@ -use bdk_electrum::electrum_client; use bdk_electrum::BdkElectrumClient; +use bdk_electrum::electrum_client; +use bdk_wallet::Wallet; use bdk_wallet::bitcoin::Amount; use bdk_wallet::bitcoin::FeeRate; use bdk_wallet::bitcoin::Network; use bdk_wallet::chain::collections::HashSet; use bdk_wallet::psbt::PsbtUtils; use bdk_wallet::rusqlite::Connection; -use bdk_wallet::Wallet; use bdk_wallet::{KeychainKind, SignOptions}; use std::io::Write; use std::thread::sleep; diff --git a/examples/esplora_async.rs b/examples/esplora_async.rs index 6e19069c..1780b287 100644 --- a/examples/esplora_async.rs +++ b/examples/esplora_async.rs @@ -1,12 +1,12 @@ -use bdk_esplora::{esplora_client, EsploraAsyncExt}; +use bdk_esplora::{EsploraAsyncExt, esplora_client}; use bdk_wallet::{ + KeychainKind, SignOptions, Wallet, bitcoin::{Amount, FeeRate, Network}, psbt::PsbtUtils, rusqlite::Connection, - KeychainKind, SignOptions, Wallet, }; use std::{collections::BTreeSet, io::Write}; -use tokio::time::{sleep, Duration}; +use tokio::time::{Duration, sleep}; const SEND_AMOUNT: Amount = Amount::from_sat(5000); const STOP_GAP: usize = 5; diff --git a/examples/esplora_blocking.rs b/examples/esplora_blocking.rs index 3131bec0..179a7d79 100644 --- a/examples/esplora_blocking.rs +++ b/examples/esplora_blocking.rs @@ -1,9 +1,9 @@ -use bdk_esplora::{esplora_client, EsploraExt}; +use bdk_esplora::{EsploraExt, esplora_client}; use bdk_wallet::rusqlite::Connection; use bdk_wallet::{ + KeychainKind, SignOptions, Wallet, bitcoin::{Amount, FeeRate, Network}, psbt::PsbtUtils, - KeychainKind, SignOptions, Wallet, }; use std::thread::sleep; use std::time::Duration; diff --git a/examples/mnemonic_to_descriptors.rs b/examples/mnemonic_to_descriptors.rs index 888da97b..bf876e34 100644 --- a/examples/mnemonic_to_descriptors.rs +++ b/examples/mnemonic_to_descriptors.rs @@ -7,9 +7,9 @@ // licenses. use anyhow::anyhow; +use bdk_wallet::bitcoin::NetworkKind; use bdk_wallet::bitcoin::bip32::DerivationPath; use bdk_wallet::bitcoin::secp256k1::Secp256k1; -use bdk_wallet::bitcoin::NetworkKind; use bdk_wallet::descriptor; use bdk_wallet::descriptor::IntoWalletDescriptor; use bdk_wallet::keys::bip39::{Language, Mnemonic, WordCount}; diff --git a/examples/policy.rs b/examples/policy.rs index fe99af21..0d417f45 100644 --- a/examples/policy.rs +++ b/examples/policy.rs @@ -13,7 +13,7 @@ extern crate bdk_wallet; use core::error::Error; -use bdk_wallet::descriptor::{policy::BuildSatisfaction, ExtractPolicy, IntoWalletDescriptor}; +use bdk_wallet::descriptor::{ExtractPolicy, IntoWalletDescriptor, policy::BuildSatisfaction}; use bdk_wallet::signer::SignersContainer; use bitcoin::NetworkKind; diff --git a/rustfmt.toml b/rustfmt.toml index 1b52dc8d..505d959b 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,4 +1,3 @@ comment_width = 100 format_code_in_doc_comments = true wrap_comments = true -style_edition = "2021" diff --git a/src/descriptor/checksum.rs b/src/descriptor/checksum.rs index 24937d7d..b202dd94 100644 --- a/src/descriptor/checksum.rs +++ b/src/descriptor/checksum.rs @@ -77,7 +77,9 @@ mod test { #[test] fn test_calc_checksum_invalid_character() { let sparkle_heart = unsafe { core::str::from_utf8_unchecked(&[240, 159, 146, 150]) }; - let invalid_desc = format!("wpkh(tprv8ZgxMBicQKsPdpkqS7Eair4YxjcuuvDPNYmKX3sCniCf16tHEVrjjiSXEkFRnUH77yXc6ZcwHHcL{sparkle_heart}fjdi5qUvw3VDfgYiH5mNsj5izuiu2N/1/2/*)"); + let invalid_desc = format!( + "wpkh(tprv8ZgxMBicQKsPdpkqS7Eair4YxjcuuvDPNYmKX3sCniCf16tHEVrjjiSXEkFRnUH77yXc6ZcwHHcL{sparkle_heart}fjdi5qUvw3VDfgYiH5mNsj5izuiu2N/1/2/*)" + ); assert_matches!( calc_checksum(&invalid_desc), diff --git a/src/descriptor/dsl.rs b/src/descriptor/dsl.rs index 1f5b1119..22505b60 100644 --- a/src/descriptor/dsl.rs +++ b/src/descriptor/dsl.rs @@ -82,10 +82,10 @@ macro_rules! impl_top_level_pk { #[macro_export] macro_rules! impl_top_level_tr { ( $internal_key:expr, $tap_tree:expr ) => {{ + use $crate::miniscript::Tap; use $crate::miniscript::descriptor::{ Descriptor, DescriptorPublicKey, KeyMap, TapTree, Tr, }; - use $crate::miniscript::Tap; #[allow(unused_imports)] use $crate::keys::{DescriptorKey, IntoDescriptorKey, ValidNetworkKinds}; @@ -361,27 +361,13 @@ macro_rules! apply_modifier { }) }}; - ( a: $inner:expr ) => {{ - $crate::apply_modifier!(Alt, $inner) - }}; - ( s: $inner:expr ) => {{ - $crate::apply_modifier!(Swap, $inner) - }}; - ( c: $inner:expr ) => {{ - $crate::apply_modifier!(Check, $inner) - }}; - ( d: $inner:expr ) => {{ - $crate::apply_modifier!(DupIf, $inner) - }}; - ( v: $inner:expr ) => {{ - $crate::apply_modifier!(Verify, $inner) - }}; - ( j: $inner:expr ) => {{ - $crate::apply_modifier!(NonZero, $inner) - }}; - ( n: $inner:expr ) => {{ - $crate::apply_modifier!(ZeroNotEqual, $inner) - }}; + ( a: $inner:expr ) => {{ $crate::apply_modifier!(Alt, $inner) }}; + ( s: $inner:expr ) => {{ $crate::apply_modifier!(Swap, $inner) }}; + ( c: $inner:expr ) => {{ $crate::apply_modifier!(Check, $inner) }}; + ( d: $inner:expr ) => {{ $crate::apply_modifier!(DupIf, $inner) }}; + ( v: $inner:expr ) => {{ $crate::apply_modifier!(Verify, $inner) }}; + ( j: $inner:expr ) => {{ $crate::apply_modifier!(NonZero, $inner) }}; + ( n: $inner:expr ) => {{ $crate::apply_modifier!(ZeroNotEqual, $inner) }}; // Modifiers expanded to other operators ( t: $inner:expr ) => {{ @@ -833,10 +819,10 @@ mod test { use alloc::string::ToString; use core::str::FromStr; - use bitcoin::{bip32, secp256k1::Secp256k1, Network, NetworkKind, PrivateKey}; + use bitcoin::{Network, NetworkKind, PrivateKey, bip32, secp256k1::Secp256k1}; use miniscript::{ - descriptor::{DescriptorPublicKey, KeyMap}, Descriptor, Legacy, Segwitv0, + descriptor::{DescriptorPublicKey, KeyMap}, }; use crate::descriptor::{DescriptorError, DescriptorMeta}; @@ -888,10 +874,12 @@ mod test { .unwrap(); check( - descriptor!(bare(multi(1,pubkey1,pubkey2))), + descriptor!(bare(multi(1, pubkey1, pubkey2))), false, true, - &["512103a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd21032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af52ae"], + &[ + "512103a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd21032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af52ae", + ], ); check( descriptor!(pk(pubkey1)), @@ -1182,9 +1170,18 @@ mod test { let (key1, _key_map, _valid_network_kinds) = desc_key1.extract(&secp).unwrap(); let (key2, _key_map, _valid_network_kinds) = desc_key2.extract(&secp).unwrap(); let (key3, _key_map, _valid_network_kinds) = desc_key3.extract(&secp).unwrap(); - assert_eq!(key_map.get(&key1).unwrap().to_string(), "tprv8ZgxMBicQKsPcx5nBGsR63Pe8KnRUqmbJNENAfGftF3yuXoMMoVJJcYeUw5eVkm9WBPjWYt6HMWYJNesB5HaNVBaFc1M6dRjWSYnmewUMYy/0/*"); - assert_eq!(key_map.get(&key2).unwrap().to_string(), "tprv8ZgxMBicQKsPegBHHnq7YEgM815dG24M2Jk5RVqipgDxF1HJ1tsnT815X5Fd5FRfMVUs8NZs9XCb6y9an8hRPThnhfwfXJ36intaekySHGF/2147483647'/0/*"); - assert_eq!(key_map.get(&key3).unwrap().to_string(), "tprv8ZgxMBicQKsPdZXrcHNLf5JAJWFAoJ2TrstMRdSKtEggz6PddbuSkvHKM9oKJyFgZV1B7rw8oChspxyYbtmEXYyg1AjfWbL3ho3XHDpHRZf/10/20/30/40/*"); + assert_eq!( + key_map.get(&key1).unwrap().to_string(), + "tprv8ZgxMBicQKsPcx5nBGsR63Pe8KnRUqmbJNENAfGftF3yuXoMMoVJJcYeUw5eVkm9WBPjWYt6HMWYJNesB5HaNVBaFc1M6dRjWSYnmewUMYy/0/*" + ); + assert_eq!( + key_map.get(&key2).unwrap().to_string(), + "tprv8ZgxMBicQKsPegBHHnq7YEgM815dG24M2Jk5RVqipgDxF1HJ1tsnT815X5Fd5FRfMVUs8NZs9XCb6y9an8hRPThnhfwfXJ36intaekySHGF/2147483647'/0/*" + ); + assert_eq!( + key_map.get(&key3).unwrap().to_string(), + "tprv8ZgxMBicQKsPdZXrcHNLf5JAJWFAoJ2TrstMRdSKtEggz6PddbuSkvHKM9oKJyFgZV1B7rw8oChspxyYbtmEXYyg1AjfWbL3ho3XHDpHRZf/10/20/30/40/*" + ); } // Verify that the `ScriptContext` is correctly validated (i.e. passing a type that only @@ -1197,7 +1194,10 @@ mod test { let desc_key: DescriptorKey = (xprv, path).into_descriptor_key().unwrap(); let (desc, _key_map, _valid_network_kinds) = descriptor!(pkh(desc_key)).unwrap(); - assert_eq!(desc.to_string(), "pkh(tpubD6NzVbkrYhZ4WR7a4vY1VT3khMJMeAxVsfq9TBJyJWrNk247zCJtV7AWf6UJP7rAVsn8NNKdJi3gFyKPTmWZS9iukb91xbn2HbFSMQm2igY/0/*)#yrnz9pp2"); + assert_eq!( + desc.to_string(), + "pkh(tpubD6NzVbkrYhZ4WR7a4vY1VT3khMJMeAxVsfq9TBJyJWrNk247zCJtV7AWf6UJP7rAVsn8NNKdJi3gFyKPTmWZS9iukb91xbn2HbFSMQm2igY/0/*)#yrnz9pp2" + ); } #[test] @@ -1207,7 +1207,10 @@ mod test { let (descriptor, _, _) = descriptor!(wsh(thresh(2,n:d:v:older(1),s:pk(private_key),s:pk(private_key)))).unwrap(); - assert_eq!(descriptor.to_string(), "wsh(thresh(2,ndv:older(1),s:pk(02e96fe52ef0e22d2f131dd425ce1893073a3c6ad20e8cac36726393dfb4856a4c),s:pk(02e96fe52ef0e22d2f131dd425ce1893073a3c6ad20e8cac36726393dfb4856a4c)))#zzk3ux8g") + assert_eq!( + descriptor.to_string(), + "wsh(thresh(2,ndv:older(1),s:pk(02e96fe52ef0e22d2f131dd425ce1893073a3c6ad20e8cac36726393dfb4856a4c),s:pk(02e96fe52ef0e22d2f131dd425ce1893073a3c6ad20e8cac36726393dfb4856a4c)))#zzk3ux8g" + ) } #[test] @@ -1239,7 +1242,10 @@ mod test { let (descriptor, _, _) = descriptor!(tr(private_key, { pk(private_key), pk(private_key) })).unwrap(); - assert_eq!(descriptor.to_string(), "tr(02e96fe52ef0e22d2f131dd425ce1893073a3c6ad20e8cac36726393dfb4856a4c,{pk(02e96fe52ef0e22d2f131dd425ce1893073a3c6ad20e8cac36726393dfb4856a4c),pk(02e96fe52ef0e22d2f131dd425ce1893073a3c6ad20e8cac36726393dfb4856a4c)})#xy5fjw6d") + assert_eq!( + descriptor.to_string(), + "tr(02e96fe52ef0e22d2f131dd425ce1893073a3c6ad20e8cac36726393dfb4856a4c,{pk(02e96fe52ef0e22d2f131dd425ce1893073a3c6ad20e8cac36726393dfb4856a4c),pk(02e96fe52ef0e22d2f131dd425ce1893073a3c6ad20e8cac36726393dfb4856a4c)})#xy5fjw6d" + ) } #[test] @@ -1248,6 +1254,9 @@ mod test { PrivateKey::from_wif("cSQPHDBwXGjVzWRqAHm6zfvQhaTuj1f2bFH58h55ghbjtFwvmeXR").unwrap(); let (descriptor, _, _) = descriptor!(tr(private_key, pk(private_key))).unwrap(); - assert_eq!(descriptor.to_string(), "tr(02e96fe52ef0e22d2f131dd425ce1893073a3c6ad20e8cac36726393dfb4856a4c,pk(02e96fe52ef0e22d2f131dd425ce1893073a3c6ad20e8cac36726393dfb4856a4c))#lzl2vmc7") + assert_eq!( + descriptor.to_string(), + "tr(02e96fe52ef0e22d2f131dd425ce1893073a3c6ad20e8cac36726393dfb4856a4c,pk(02e96fe52ef0e22d2f131dd425ce1893073a3c6ad20e8cac36726393dfb4856a4c))#lzl2vmc7" + ) } } diff --git a/src/descriptor/mod.rs b/src/descriptor/mod.rs index e2acbe89..ea52e86c 100644 --- a/src/descriptor/mod.rs +++ b/src/descriptor/mod.rs @@ -21,9 +21,10 @@ use alloc::string::String; use alloc::vec::Vec; use bitcoin::{ + NetworkKind, PublicKey, TxOut, bip32::{ChildNumber, DerivationPath, Fingerprint, KeySource, Xpub}, key::XOnlyPublicKey, - psbt, secp256k1, taproot, NetworkKind, PublicKey, TxOut, + psbt, secp256k1, taproot, }; use miniscript::descriptor::{ DefiniteDescriptorKey, DescriptorMultiXKey, DescriptorSecretKey, DescriptorType, @@ -618,8 +619,8 @@ mod test { use assert_matches::assert_matches; use bitcoin::hex::FromHex; use bitcoin::secp256k1::Secp256k1; - use bitcoin::{bip32, Psbt}; use bitcoin::{NetworkKind, ScriptBuf}; + use bitcoin::{Psbt, bip32}; use super::*; use crate::psbt::PsbtUtils; @@ -642,9 +643,11 @@ mod test { ) .unwrap(); - assert!(descriptor - .derive_from_psbt_input(&psbt.inputs[0], psbt.get_utxo_for(0), &Secp256k1::new()) - .is_some()); + assert!( + descriptor + .derive_from_psbt_input(&psbt.inputs[0], psbt.get_utxo_for(0), &Secp256k1::new()) + .is_some() + ); } #[test] @@ -673,9 +676,11 @@ mod test { ) .unwrap(); - assert!(descriptor - .derive_from_psbt_input(&psbt.inputs[0], psbt.get_utxo_for(0), &Secp256k1::new()) - .is_some()); + assert!( + descriptor + .derive_from_psbt_input(&psbt.inputs[0], psbt.get_utxo_for(0), &Secp256k1::new()) + .is_some() + ); } #[test] @@ -697,9 +702,11 @@ mod test { ) .unwrap(); - assert!(descriptor - .derive_from_psbt_input(&psbt.inputs[0], psbt.get_utxo_for(0), &Secp256k1::new()) - .is_some()); + assert!( + descriptor + .derive_from_psbt_input(&psbt.inputs[0], psbt.get_utxo_for(0), &Secp256k1::new()) + .is_some() + ); } #[test] @@ -727,14 +734,16 @@ mod test { ) .unwrap(); - assert!(descriptor - .derive_from_psbt_input(&psbt.inputs[0], psbt.get_utxo_for(0), &Secp256k1::new()) - .is_some()); + assert!( + descriptor + .derive_from_psbt_input(&psbt.inputs[0], psbt.get_utxo_for(0), &Secp256k1::new()) + .is_some() + ); } #[test] fn test_to_wallet_descriptor_fixup_network_kinds() { - use crate::keys::{any_network_kind, IntoDescriptorKey}; + use crate::keys::{IntoDescriptorKey, any_network_kind}; let secp = Secp256k1::new(); @@ -766,7 +775,10 @@ mod test { wildcard: Wildcard::Unhardened, }); - assert_eq!(wallet_desc.to_string(), "wpkh(tpubD6NzVbkrYhZ4XtJzoDja5snUjBNQRP5B3f4Hyn1T1x6PVPxzzVjvw6nJx2D8RBCxog9GEVjZoyStfepTz7TtKoBVdkCtnc7VCJh9dD4RAU9/0/*)#a3svx0ha"); + assert_eq!( + wallet_desc.to_string(), + "wpkh(tpubD6NzVbkrYhZ4XtJzoDja5snUjBNQRP5B3f4Hyn1T1x6PVPxzzVjvw6nJx2D8RBCxog9GEVjZoyStfepTz7TtKoBVdkCtnc7VCJh9dD4RAU9/0/*)#a3svx0ha" + ); assert_eq!( keymap .get(&desc_pubkey) @@ -870,7 +882,10 @@ mod test { .into_wallet_descriptor(&secp, NetworkKind::Test) .unwrap(); let wallet_desc_str = wallet_desc.to_string(); - assert_eq!(wallet_desc_str, "wpkh(tpubD6NzVbkrYhZ4XHndKkuB8FifXm8r5FQHwrN6oZuWCz13qb93rtgKvD4PQsqC4HP4yhV3tA2fqr2RbY5mNXfM7RxXUoeABoDtsFUq2zJq6YK/1/2/*)#67ju93jw"); + assert_eq!( + wallet_desc_str, + "wpkh(tpubD6NzVbkrYhZ4XHndKkuB8FifXm8r5FQHwrN6oZuWCz13qb93rtgKvD4PQsqC4HP4yhV3tA2fqr2RbY5mNXfM7RxXUoeABoDtsFUq2zJq6YK/1/2/*)#67ju93jw" + ); let (wallet_desc2, _) = wallet_desc_str .into_wallet_descriptor(&secp, NetworkKind::Test) diff --git a/src/descriptor/policy.rs b/src/descriptor/policy.rs index 9d3ac62d..2d13153e 100644 --- a/src/descriptor/policy.rs +++ b/src/descriptor/policy.rs @@ -42,22 +42,22 @@ use core::cmp::max; use core::fmt; use bitcoin::{ - absolute, + PublicKey, Sequence, absolute, bip32::Fingerprint, hashes::{hash160, ripemd160, sha256}, key::XOnlyPublicKey, psbt::{self, Psbt}, - relative, PublicKey, Sequence, + relative, }; use miniscript::descriptor::{ DescriptorPublicKey, ShInner, SinglePub, SinglePubKey, SortedMultiVec, WshInner, }; use miniscript::miniscript::limits::{MAX_PUBKEYS_IN_CHECKSIGADD, MAX_PUBKEYS_PER_MULTISIG}; use miniscript::{ - hash256, psbt::PsbtInputSatisfier, Descriptor, Miniscript, Satisfier, ScriptContext, SigType, - Terminal, Threshold, ToPublicKey, + Descriptor, Miniscript, Satisfier, ScriptContext, SigType, Terminal, Threshold, ToPublicKey, + hash256, psbt::PsbtInputSatisfier, }; -use serde::{ser::SerializeMap, Serialize, Serializer}; +use serde::{Serialize, Serializer, ser::SerializeMap}; use crate::collections::{BTreeMap, HashSet, VecDeque}; use crate::descriptor::ExtractPolicy; @@ -66,9 +66,9 @@ use crate::types::IndexOutOfBoundsError; use crate::wallet::signer::{SignerId, SignersContainer}; use crate::wallet::utils::{After, Older, SecpCtx}; +use super::XKeyUtils; use super::checksum::calc_checksum; use super::error::Error; -use super::XKeyUtils; /// A unique identifier for a key #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)] @@ -1179,20 +1179,20 @@ mod test { use assert_matches::assert_matches; use core::str::FromStr; - use bitcoin::{bip32, secp256k1::Secp256k1, Network, NetworkKind}; + use bitcoin::{Network, NetworkKind, bip32, secp256k1::Secp256k1}; use crate::keys::{DescriptorKey, IntoDescriptorKey}; use crate::wallet::signer::SignersContainer; use crate::{ descriptor, descriptor::{ - policy::SatisfiableItem::{EcdsaSignature, Multisig, Thresh}, ExtractPolicy, IntoWalletDescriptor, + policy::SatisfiableItem::{EcdsaSignature, Multisig, Thresh}, }, }; - const TPRV0_STR:&str = "tprv8ZgxMBicQKsPdZXrcHNLf5JAJWFAoJ2TrstMRdSKtEggz6PddbuSkvHKM9oKJyFgZV1B7rw8oChspxyYbtmEXYyg1AjfWbL3ho3XHDpHRZf"; - const TPRV1_STR:&str = "tprv8ZgxMBicQKsPdpkqS7Eair4YxjcuuvDPNYmKX3sCniCf16tHEVrjjiSXEkFRnUH77yXc6ZcwHHcLNfjdi5qUvw3VDfgYiH5mNsj5izuiu2N"; + const TPRV0_STR: &str = "tprv8ZgxMBicQKsPdZXrcHNLf5JAJWFAoJ2TrstMRdSKtEggz6PddbuSkvHKM9oKJyFgZV1B7rw8oChspxyYbtmEXYyg1AjfWbL3ho3XHDpHRZf"; + const TPRV1_STR: &str = "tprv8ZgxMBicQKsPdpkqS7Eair4YxjcuuvDPNYmKX3sCniCf16tHEVrjjiSXEkFRnUH77yXc6ZcwHHcLNfjdi5qUvw3VDfgYiH5mNsj5izuiu2N"; const PATH: &str = "m/44'/1'/0'/0"; @@ -1595,16 +1595,16 @@ mod test { ); } - const ALICE_TPRV_STR:&str = "tprv8ZgxMBicQKsPf6T5X327efHnvJDr45Xnb8W4JifNWtEoqXu9MRYS4v1oYe6DFcMVETxy5w3bqpubYRqvcVTqovG1LifFcVUuJcbwJwrhYzP"; - const BOB_TPRV_STR:&str = "tprv8ZgxMBicQKsPeinZ155cJAn117KYhbaN6MV3WeG6sWhxWzcvX1eg1awd4C9GpUN1ncLEM2rzEvunAg3GizdZD4QPPCkisTz99tXXB4wZArp"; - const CAROL_TPRV_STR:&str = "tprv8ZgxMBicQKsPdC3CicFifuLCEyVVdXVUNYorxUWj3iGZ6nimnLAYAY9SYB7ib8rKzRxrCKFcEytCt6szwd2GHnGPRCBLAEAoSVDefSNk4Bt"; + const ALICE_TPRV_STR: &str = "tprv8ZgxMBicQKsPf6T5X327efHnvJDr45Xnb8W4JifNWtEoqXu9MRYS4v1oYe6DFcMVETxy5w3bqpubYRqvcVTqovG1LifFcVUuJcbwJwrhYzP"; + const BOB_TPRV_STR: &str = "tprv8ZgxMBicQKsPeinZ155cJAn117KYhbaN6MV3WeG6sWhxWzcvX1eg1awd4C9GpUN1ncLEM2rzEvunAg3GizdZD4QPPCkisTz99tXXB4wZArp"; + const CAROL_TPRV_STR: &str = "tprv8ZgxMBicQKsPdC3CicFifuLCEyVVdXVUNYorxUWj3iGZ6nimnLAYAY9SYB7ib8rKzRxrCKFcEytCt6szwd2GHnGPRCBLAEAoSVDefSNk4Bt"; const ALICE_BOB_PATH: &str = "m/0'"; #[test] fn test_extract_satisfaction() { const ALICE_SIGNED_PSBT: &str = "cHNidP8BAFMBAAAAAZb0njwT2wRS3AumaaP3yb7T4MxOePpSWih4Nq+jWChMAQAAAAD/////Af4lAAAAAAAAF6kUXv2Fn+YemPP4PUpNR1ZbU16/eRCHAAAAAAABASuJJgAAAAAAACIAIERw5kTLo9DUH9QDJSClHQwPpC7VGJ+ZMDpa8U+2fzcYIgIDeAtjYQk/Vfu4db2+68hyMKjc38+kWl5sP5QH8L42ZstHMEQCIBj0jLjUeVYXNQ6cqB+gbtvuKMjV54wSgWlm1cfcgpHVAiBa3DtC9l/1Mt4IDCvR7mmwQd3eAP/m5++81euhJNSrgQEBBUdSIQN4C2NhCT9V+7h1vb7ryHIwqNzfz6RaXmw/lAfwvjZmyyEC+GE/y+LptI8xmiR6sOe998IGzybox0Qfz4+BQl1nmYhSriIGAvhhP8vi6bSPMZokerDnvffCBs8m6MdEH8+PgUJdZ5mIDBwu7j4AAACAAAAAACIGA3gLY2EJP1X7uHW9vuvIcjCo3N/PpFpebD+UB/C+NmbLDMkRfC4AAACAAAAAAAAA"; - const BOB_SIGNED_PSBT: &str = "cHNidP8BAFMBAAAAAZb0njwT2wRS3AumaaP3yb7T4MxOePpSWih4Nq+jWChMAQAAAAD/////Af4lAAAAAAAAF6kUXv2Fn+YemPP4PUpNR1ZbU16/eRCHAAAAAAABASuJJgAAAAAAACIAIERw5kTLo9DUH9QDJSClHQwPpC7VGJ+ZMDpa8U+2fzcYIgIC+GE/y+LptI8xmiR6sOe998IGzybox0Qfz4+BQl1nmYhIMEUCIQD5zDtM5MwklurwJ5aW76RsO36Iqyu+6uMdVlhL6ws2GQIgesAiz4dbKS7UmhDsC/c1ezu0o6hp00UUtsCMfUZ4anYBAQVHUiEDeAtjYQk/Vfu4db2+68hyMKjc38+kWl5sP5QH8L42ZsshAvhhP8vi6bSPMZokerDnvffCBs8m6MdEH8+PgUJdZ5mIUq4iBgL4YT/L4um0jzGaJHqw5733wgbPJujHRB/Pj4FCXWeZiAwcLu4+AAAAgAAAAAAiBgN4C2NhCT9V+7h1vb7ryHIwqNzfz6RaXmw/lAfwvjZmywzJEXwuAAAAgAAAAAAAAA=="; - const ALICE_BOB_SIGNED_PSBT: &str = "cHNidP8BAFMBAAAAAZb0njwT2wRS3AumaaP3yb7T4MxOePpSWih4Nq+jWChMAQAAAAD/////Af4lAAAAAAAAF6kUXv2Fn+YemPP4PUpNR1ZbU16/eRCHAAAAAAABASuJJgAAAAAAACIAIERw5kTLo9DUH9QDJSClHQwPpC7VGJ+ZMDpa8U+2fzcYIgIC+GE/y+LptI8xmiR6sOe998IGzybox0Qfz4+BQl1nmYhIMEUCIQD5zDtM5MwklurwJ5aW76RsO36Iqyu+6uMdVlhL6ws2GQIgesAiz4dbKS7UmhDsC/c1ezu0o6hp00UUtsCMfUZ4anYBIgIDeAtjYQk/Vfu4db2+68hyMKjc38+kWl5sP5QH8L42ZstHMEQCIBj0jLjUeVYXNQ6cqB+gbtvuKMjV54wSgWlm1cfcgpHVAiBa3DtC9l/1Mt4IDCvR7mmwQd3eAP/m5++81euhJNSrgQEBBUdSIQN4C2NhCT9V+7h1vb7ryHIwqNzfz6RaXmw/lAfwvjZmyyEC+GE/y+LptI8xmiR6sOe998IGzybox0Qfz4+BQl1nmYhSriIGAvhhP8vi6bSPMZokerDnvffCBs8m6MdEH8+PgUJdZ5mIDBwu7j4AAACAAAAAACIGA3gLY2EJP1X7uHW9vuvIcjCo3N/PpFpebD+UB/C+NmbLDMkRfC4AAACAAAAAAAEHAAEI2wQARzBEAiAY9Iy41HlWFzUOnKgfoG7b7ijI1eeMEoFpZtXH3IKR1QIgWtw7QvZf9TLeCAwr0e5psEHd3gD/5ufvvNXroSTUq4EBSDBFAiEA+cw7TOTMJJbq8CeWlu+kbDt+iKsrvurjHVZYS+sLNhkCIHrAIs+HWyku1JoQ7Av3NXs7tKOoadNFFLbAjH1GeGp2AUdSIQN4C2NhCT9V+7h1vb7ryHIwqNzfz6RaXmw/lAfwvjZmyyEC+GE/y+LptI8xmiR6sOe998IGzybox0Qfz4+BQl1nmYhSrgAA"; + const BOB_SIGNED_PSBT: &str = "cHNidP8BAFMBAAAAAZb0njwT2wRS3AumaaP3yb7T4MxOePpSWih4Nq+jWChMAQAAAAD/////Af4lAAAAAAAAF6kUXv2Fn+YemPP4PUpNR1ZbU16/eRCHAAAAAAABASuJJgAAAAAAACIAIERw5kTLo9DUH9QDJSClHQwPpC7VGJ+ZMDpa8U+2fzcYIgIC+GE/y+LptI8xmiR6sOe998IGzybox0Qfz4+BQl1nmYhIMEUCIQD5zDtM5MwklurwJ5aW76RsO36Iqyu+6uMdVlhL6ws2GQIgesAiz4dbKS7UmhDsC/c1ezu0o6hp00UUtsCMfUZ4anYBAQVHUiEDeAtjYQk/Vfu4db2+68hyMKjc38+kWl5sP5QH8L42ZsshAvhhP8vi6bSPMZokerDnvffCBs8m6MdEH8+PgUJdZ5mIUq4iBgL4YT/L4um0jzGaJHqw5733wgbPJujHRB/Pj4FCXWeZiAwcLu4+AAAAgAAAAAAiBgN4C2NhCT9V+7h1vb7ryHIwqNzfz6RaXmw/lAfwvjZmywzJEXwuAAAAgAAAAAAAAA=="; + const ALICE_BOB_SIGNED_PSBT: &str = "cHNidP8BAFMBAAAAAZb0njwT2wRS3AumaaP3yb7T4MxOePpSWih4Nq+jWChMAQAAAAD/////Af4lAAAAAAAAF6kUXv2Fn+YemPP4PUpNR1ZbU16/eRCHAAAAAAABASuJJgAAAAAAACIAIERw5kTLo9DUH9QDJSClHQwPpC7VGJ+ZMDpa8U+2fzcYIgIC+GE/y+LptI8xmiR6sOe998IGzybox0Qfz4+BQl1nmYhIMEUCIQD5zDtM5MwklurwJ5aW76RsO36Iqyu+6uMdVlhL6ws2GQIgesAiz4dbKS7UmhDsC/c1ezu0o6hp00UUtsCMfUZ4anYBIgIDeAtjYQk/Vfu4db2+68hyMKjc38+kWl5sP5QH8L42ZstHMEQCIBj0jLjUeVYXNQ6cqB+gbtvuKMjV54wSgWlm1cfcgpHVAiBa3DtC9l/1Mt4IDCvR7mmwQd3eAP/m5++81euhJNSrgQEBBUdSIQN4C2NhCT9V+7h1vb7ryHIwqNzfz6RaXmw/lAfwvjZmyyEC+GE/y+LptI8xmiR6sOe998IGzybox0Qfz4+BQl1nmYhSriIGAvhhP8vi6bSPMZokerDnvffCBs8m6MdEH8+PgUJdZ5mIDBwu7j4AAACAAAAAACIGA3gLY2EJP1X7uHW9vuvIcjCo3N/PpFpebD+UB/C+NmbLDMkRfC4AAACAAAAAAAEHAAEI2wQARzBEAiAY9Iy41HlWFzUOnKgfoG7b7ijI1eeMEoFpZtXH3IKR1QIgWtw7QvZf9TLeCAwr0e5psEHd3gD/5ufvvNXroSTUq4EBSDBFAiEA+cw7TOTMJJbq8CeWlu+kbDt+iKsrvurjHVZYS+sLNhkCIHrAIs+HWyku1JoQ7Av3NXs7tKOoadNFFLbAjH1GeGp2AUdSIQN4C2NhCT9V+7h1vb7ryHIwqNzfz6RaXmw/lAfwvjZmyyEC+GE/y+LptI8xmiR6sOe998IGzybox0Qfz4+BQl1nmYhSrgAA"; let secp = Secp256k1::new(); diff --git a/src/descriptor/template.rs b/src/descriptor/template.rs index 86dfbb90..86c5fa89 100644 --- a/src/descriptor/template.rs +++ b/src/descriptor/template.rs @@ -14,14 +14,14 @@ //! This module contains the definition of various common script templates that are ready to be //! used. See the documentation of each template for an example. -use bitcoin::{bip32, NetworkKind}; +use bitcoin::{NetworkKind, bip32}; use miniscript::{Legacy, Segwitv0, Tap}; use super::{ExtendedDescriptor, IntoWalletDescriptor, KeyMap}; use crate::descriptor::DescriptorError; use crate::keys::{DerivableKey, IntoDescriptorKey, ValidNetworkKinds}; use crate::wallet::utils::SecpCtx; -use crate::{descriptor, KeychainKind}; +use crate::{KeychainKind, descriptor}; /// Type alias for the return type of [`DescriptorTemplate`], [`descriptor!`](crate::descriptor!) /// and others. @@ -644,8 +644,8 @@ mod test { use assert_matches::assert_matches; use bitcoin::Network; - use miniscript::descriptor::{DescriptorPublicKey, KeyMap}; use miniscript::Descriptor; + use miniscript::descriptor::{DescriptorPublicKey, KeyMap}; use crate::descriptor::{DescriptorError, DescriptorMeta}; use crate::keys::ValidNetworkKinds; diff --git a/src/keys/bip39.rs b/src/keys/bip39.rs index 8cd710cf..7e59ea54 100644 --- a/src/keys/bip39.rs +++ b/src/keys/bip39.rs @@ -16,12 +16,12 @@ use alloc::string::String; -use bitcoin::{bip32, Network}; +use bitcoin::{Network, bip32}; use miniscript::ScriptContext; use super::{ - any_network_kind, DerivableKey, DescriptorKey, ExtendedKey, GeneratableKey, GeneratedKey, - KeyError, + DerivableKey, DescriptorKey, ExtendedKey, GeneratableKey, GeneratedKey, KeyError, + any_network_kind, }; pub use bip39::{Error, Language, Mnemonic}; @@ -160,7 +160,7 @@ mod test { use bip39::{Language, Mnemonic}; use bitcoin::bip32; - use crate::keys::{any_network_kind, GeneratableKey, GeneratedKey}; + use crate::keys::{GeneratableKey, GeneratedKey, any_network_kind}; #[test] fn test_keys_bip39_mnemonic() { @@ -171,7 +171,10 @@ mod test { let key = (mnemonic, path); let (desc, keys, network_kinds) = crate::descriptor!(wpkh(key)).unwrap(); - assert_eq!(desc.to_string(), "wpkh([be83839f/44'/0'/0']xpub6DCQ1YcqvZtSwGWMrwHELPehjWV3f2MGZ69yBADTxFEUAoLwb5Mp5GniQK6tTp3AgbngVz9zEFbBJUPVnkG7LFYt8QMTfbrNqs6FNEwAPKA/0/*)#0r8v4nkv"); + assert_eq!( + desc.to_string(), + "wpkh([be83839f/44'/0'/0']xpub6DCQ1YcqvZtSwGWMrwHELPehjWV3f2MGZ69yBADTxFEUAoLwb5Mp5GniQK6tTp3AgbngVz9zEFbBJUPVnkG7LFYt8QMTfbrNqs6FNEwAPKA/0/*)#0r8v4nkv" + ); assert_eq!(keys.len(), 1); assert_eq!(network_kinds, any_network_kind()); } @@ -185,7 +188,10 @@ mod test { let key = ((mnemonic, Some("passphrase".into())), path); let (desc, keys, network_kinds) = crate::descriptor!(wpkh(key)).unwrap(); - assert_eq!(desc.to_string(), "wpkh([8f6cb80c/44'/0'/0']xpub6DWYS8bbihFevy29M4cbw4ZR3P5E12jB8R88gBDWCTCNpYiDHhYWNywrCF9VZQYagzPmsZpxXpytzSoxynyeFr4ZyzheVjnpLKuse4fiwZw/0/*)#h0j0tg5m"); + assert_eq!( + desc.to_string(), + "wpkh([8f6cb80c/44'/0'/0']xpub6DWYS8bbihFevy29M4cbw4ZR3P5E12jB8R88gBDWCTCNpYiDHhYWNywrCF9VZQYagzPmsZpxXpytzSoxynyeFr4ZyzheVjnpLKuse4fiwZw/0/*)#h0j0tg5m" + ); assert_eq!(keys.len(), 1); assert_eq!(network_kinds, any_network_kind()); } @@ -211,7 +217,10 @@ mod test { ) .unwrap(); assert_eq!(generated_mnemonic.valid_network_kinds, any_network_kind()); - assert_eq!(generated_mnemonic.to_string(), "primary fetch primary fetch primary fetch primary fetch primary fetch primary fetch primary fetch primary fetch primary fetch primary fetch primary fetch primary foster"); + assert_eq!( + generated_mnemonic.to_string(), + "primary fetch primary fetch primary fetch primary fetch primary fetch primary fetch primary fetch primary fetch primary fetch primary fetch primary fetch primary foster" + ); } #[test] diff --git a/src/keys/mod.rs b/src/keys/mod.rs index f6901e27..538413ef 100644 --- a/src/keys/mod.rs +++ b/src/keys/mod.rs @@ -24,10 +24,9 @@ use crate::descriptor::{CheckMiniscript, DescriptorError}; use crate::wallet::utils::SecpCtx; use bitcoin::{ - bip32, + NetworkKind, PrivateKey, PublicKey, bip32, key::XOnlyPublicKey, secp256k1::{self, Secp256k1, Signing}, - NetworkKind, PrivateKey, PublicKey, }; use miniscript::{ descriptor::{Descriptor, DescriptorMultiXKey, DescriptorXKey, Wildcard}, @@ -35,11 +34,11 @@ use miniscript::{ }; use rand_core::{CryptoRng, RngCore}; +pub use miniscript::ScriptContext; pub use miniscript::descriptor::{ DescriptorPublicKey, DescriptorSecretKey, KeyMap, SinglePriv, SinglePub, SinglePubKey, SortedMultiVec, }; -pub use miniscript::ScriptContext; #[cfg(feature = "keys-bip39")] #[cfg_attr(docsrs, doc(cfg(feature = "keys-bip39")))] @@ -229,8 +228,8 @@ impl ExtScriptContext for Ctx { /// use bdk_wallet::bitcoin::PublicKey; /// /// use bdk_wallet::keys::{ -/// mainnet_network_kind, DescriptorKey, DescriptorPublicKey, IntoDescriptorKey, KeyError, -/// ScriptContext, SinglePub, SinglePubKey, +/// DescriptorKey, DescriptorPublicKey, IntoDescriptorKey, KeyError, ScriptContext, SinglePub, +/// SinglePubKey, mainnet_network_kind, /// }; /// /// pub struct MyKeyType { @@ -391,7 +390,7 @@ impl From for ExtendedKey { /// an [`Xpub`] can implement only the required `into_extended_key()` method. /// /// ``` -/// use bdk_wallet::bitcoin::{bip32, NetworkKind}; +/// use bdk_wallet::bitcoin::{NetworkKind, bip32}; /// use bdk_wallet::keys::{DerivableKey, ExtendedKey, KeyError, ScriptContext}; /// /// struct MyCustomKeyType { @@ -419,9 +418,9 @@ impl From for ExtendedKey { /// For types that don't internally encode the [`NetworkKind`] in which they are valid, only the /// network kind specified in the [`Xpriv`] or [`Xpub`] will be considered valid. /// ``` -/// use bdk_wallet::bitcoin::{bip32, NetworkKind}; +/// use bdk_wallet::bitcoin::{NetworkKind, bip32}; /// use bdk_wallet::keys::{ -/// any_network_kind, DerivableKey, DescriptorKey, ExtendedKey, KeyError, ScriptContext, +/// DerivableKey, DescriptorKey, ExtendedKey, KeyError, ScriptContext, any_network_kind, /// }; /// /// struct MyCustomKeyType { @@ -1081,7 +1080,10 @@ mod test { bip32::Xpriv::generate_with_entropy_default(TEST_ENTROPY).unwrap(); assert_eq!(generated_xprv.valid_network_kinds, mainnet_network_kind()); - assert_eq!(generated_xprv.to_string(), "xprv9s21ZrQH143K4Xr1cJyqTvuL2FWR8eicgY9boWqMBv8MDVUZ65AXHnzBrK1nyomu6wdcabRgmGTaAKawvhAno1V5FowGpTLVx3jxzE5uk3Q"); + assert_eq!( + generated_xprv.to_string(), + "xprv9s21ZrQH143K4Xr1cJyqTvuL2FWR8eicgY9boWqMBv8MDVUZ65AXHnzBrK1nyomu6wdcabRgmGTaAKawvhAno1V5FowGpTLVx3jxzE5uk3Q" + ); } #[test] diff --git a/src/lib.rs b/src/lib.rs index ecc15b85..127e766a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -44,8 +44,8 @@ pub(crate) use bdk_chain::collections; pub use bdk_chain::rusqlite; #[cfg(feature = "rusqlite")] pub use bdk_chain::rusqlite_impl; -pub use descriptor::template; pub use descriptor::HdKeyPaths; +pub use descriptor::template; pub use signer; pub use signer::SignOptions; pub use tx_builder::*; diff --git a/src/persist_test_utils.rs b/src/persist_test_utils.rs index 729d7ef4..19515d4a 100644 --- a/src/persist_test_utils.rs +++ b/src/persist_test_utils.rs @@ -1,17 +1,18 @@ //! Utilities for testing custom persistence backends for `bdk_wallet` use crate::{ + ChangeSet, WalletPersister, bitcoin::{ - absolute, key::Secp256k1, transaction, Address, Amount, Network, OutPoint, ScriptBuf, - Transaction, TxIn, TxOut, Txid, + Address, Amount, Network, OutPoint, ScriptBuf, Transaction, TxIn, TxOut, Txid, absolute, + key::Secp256k1, transaction, }, chain::{ + ConfirmationBlockTime, DescriptorExt, Merge, SpkIterator, keychain_txout::{self}, - local_chain, tx_graph, ConfirmationBlockTime, DescriptorExt, Merge, SpkIterator, + local_chain, tx_graph, }, locked_outpoints, miniscript::descriptor::{Descriptor, DescriptorPublicKey}, - ChangeSet, WalletPersister, }; macro_rules! block_id { @@ -24,9 +25,7 @@ macro_rules! block_id { } macro_rules! hash { - ($index:literal) => {{ - bitcoin::hashes::Hash::hash($index.as_bytes()) - }}; + ($index:literal) => {{ bitcoin::hashes::Hash::hash($index.as_bytes()) }}; } use std::fmt::Debug; diff --git a/src/test_utils.rs b/src/test_utils.rs index ff288ac8..94f29a07 100644 --- a/src/test_utils.rs +++ b/src/test_utils.rs @@ -6,8 +6,8 @@ use core::str::FromStr; use bdk_chain::{BlockId, CheckPoint, ConfirmationBlockTime, TxUpdate}; use bitcoin::{ - absolute, hashes::Hash, transaction, Address, Amount, BlockHash, FeeRate, Network, OutPoint, - Transaction, TxIn, TxOut, Txid, + Address, Amount, BlockHash, FeeRate, Network, OutPoint, Transaction, TxIn, TxOut, Txid, + absolute, hashes::Hash, transaction, }; use crate::{KeychainKind, Update, Wallet}; @@ -143,8 +143,10 @@ pub fn get_test_wpkh() -> &'static str { /// `wpkh` xpriv and change descriptor pub fn get_test_wpkh_and_change_desc() -> (&'static str, &'static str) { - ("wpkh(tprv8ZgxMBicQKsPdy6LMhUtFHAgpocR8GC6QmwMSFpZs7h6Eziw3SpThFfczTDh5rW2krkqffa11UpX3XkeTTB2FvzZKWXqPY54Y6Rq4AQ5R8L/84'/1'/0'/0/*)", - "wpkh(tprv8ZgxMBicQKsPdy6LMhUtFHAgpocR8GC6QmwMSFpZs7h6Eziw3SpThFfczTDh5rW2krkqffa11UpX3XkeTTB2FvzZKWXqPY54Y6Rq4AQ5R8L/84'/1'/0'/1/*)") + ( + "wpkh(tprv8ZgxMBicQKsPdy6LMhUtFHAgpocR8GC6QmwMSFpZs7h6Eziw3SpThFfczTDh5rW2krkqffa11UpX3XkeTTB2FvzZKWXqPY54Y6Rq4AQ5R8L/84'/1'/0'/0/*)", + "wpkh(tprv8ZgxMBicQKsPdy6LMhUtFHAgpocR8GC6QmwMSFpZs7h6Eziw3SpThFfczTDh5rW2krkqffa11UpX3XkeTTB2FvzZKWXqPY54Y6Rq4AQ5R8L/84'/1'/0'/1/*)", + ) } /// `wsh` descriptor with policy `and(pk(A),older(6))` @@ -196,8 +198,10 @@ pub fn get_test_tr_single_sig_xprv() -> &'static str { /// taproot xpriv and change descriptor pub fn get_test_tr_single_sig_xprv_and_change_desc() -> (&'static str, &'static str) { - ("tr(tprv8ZgxMBicQKsPdDArR4xSAECuVxeX1jwwSXR4ApKbkYgZiziDc4LdBy2WvJeGDfUSE4UT4hHhbgEwbdq8ajjUHiKDegkwrNU6V55CxcxonVN/0/*)", - "tr(tprv8ZgxMBicQKsPdDArR4xSAECuVxeX1jwwSXR4ApKbkYgZiziDc4LdBy2WvJeGDfUSE4UT4hHhbgEwbdq8ajjUHiKDegkwrNU6V55CxcxonVN/1/*)") + ( + "tr(tprv8ZgxMBicQKsPdDArR4xSAECuVxeX1jwwSXR4ApKbkYgZiziDc4LdBy2WvJeGDfUSE4UT4hHhbgEwbdq8ajjUHiKDegkwrNU6V55CxcxonVN/0/*)", + "tr(tprv8ZgxMBicQKsPdDArR4xSAECuVxeX1jwwSXR4ApKbkYgZiziDc4LdBy2WvJeGDfUSE4UT4hHhbgEwbdq8ajjUHiKDegkwrNU6V55CxcxonVN/1/*)", + ) } /// taproot descriptor with taptree diff --git a/src/types.rs b/src/types.rs index 8009c616..a416a1c7 100644 --- a/src/types.rs +++ b/src/types.rs @@ -15,7 +15,7 @@ use core::convert::AsRef; use core::fmt; use bitcoin::transaction::{OutPoint, Sequence, TxOut}; -use bitcoin::{psbt, Weight}; +use bitcoin::{Weight, psbt}; use serde::{Deserialize, Serialize}; diff --git a/src/wallet/changeset.rs b/src/wallet/changeset.rs index 44c71822..1bc51845 100644 --- a/src/wallet/changeset.rs +++ b/src/wallet/changeset.rs @@ -1,5 +1,5 @@ use bdk_chain::{ - indexed_tx_graph, keychain_txout, local_chain, tx_graph, ConfirmationBlockTime, Merge, + ConfirmationBlockTime, Merge, indexed_tx_graph, keychain_txout, local_chain, tx_graph, }; use miniscript::{Descriptor, DescriptorPublicKey}; use serde::{Deserialize, Serialize}; @@ -249,8 +249,8 @@ impl ChangeSet { /// Recover a [`ChangeSet`] from sqlite database. pub fn from_sqlite(db_tx: &chain::rusqlite::Transaction) -> chain::rusqlite::Result { use bitcoin::{OutPoint, Txid}; - use chain::rusqlite::OptionalExtension; use chain::Impl; + use chain::rusqlite::OptionalExtension; let mut changeset = Self::default(); @@ -305,8 +305,8 @@ impl ChangeSet { &self, db_tx: &chain::rusqlite::Transaction, ) -> chain::rusqlite::Result<()> { - use chain::rusqlite::named_params; use chain::Impl; + use chain::rusqlite::named_params; let mut descriptor_statement = db_tx.prepare_cached(&format!( "INSERT INTO {}(id, descriptor) VALUES(:id, :descriptor) ON CONFLICT(id) DO UPDATE SET descriptor=:descriptor", diff --git a/src/wallet/coin_selection.rs b/src/wallet/coin_selection.rs index 2ccbeffb..31601a94 100644 --- a/src/wallet/coin_selection.rs +++ b/src/wallet/coin_selection.rs @@ -101,14 +101,14 @@ //! # Ok::<(), anyhow::Error>(()) //! ``` -use crate::wallet::utils::IsDust; use crate::Utxo; use crate::WeightedUtxo; +use crate::wallet::utils::IsDust; use bitcoin::{Amount, FeeRate, SignedAmount}; use alloc::vec::Vec; -use bitcoin::consensus::encode::serialize; use bitcoin::TxIn; +use bitcoin::consensus::encode::serialize; use bitcoin::{Script, Weight}; use core::convert::TryInto; @@ -727,7 +727,7 @@ fn calculate_cs_result( mod test { use assert_matches::assert_matches; use bitcoin::hashes::Hash; - use bitcoin::{psbt, OutPoint, Sequence}; + use bitcoin::{OutPoint, Sequence, psbt}; use chain::{ChainPosition, ConfirmationBlockTime}; use core::str::FromStr; use rand::rngs::StdRng; @@ -739,7 +739,7 @@ mod test { use crate::types::*; use rand::prelude::SliceRandom; - use rand::{thread_rng, Rng, RngCore, SeedableRng}; + use rand::{Rng, RngCore, SeedableRng, thread_rng}; // signature len (1WU) + signature and sighash (72WU) // + pubkey len (1WU) + pubkey (33WU) @@ -1120,10 +1120,12 @@ mod test { assert_eq!(result.selected.len(), 3); assert_eq!(result.selected_amount(), Amount::from_sat(500_000)); assert_eq!(result.fee_amount, Amount::from_sat(204)); - assert!(result - .selected - .iter() - .all(|utxo| matches!(utxo, Utxo::Local(..)))); + assert!( + result + .selected + .iter() + .all(|utxo| matches!(utxo, Utxo::Local(..))) + ); } #[test] diff --git a/src/wallet/error.rs b/src/wallet/error.rs index b75411c0..9f7cd003 100644 --- a/src/wallet/error.rs +++ b/src/wallet/error.rs @@ -14,12 +14,12 @@ use crate::descriptor::policy::PolicyError; use crate::descriptor::{DescriptorError, ExtendedDescriptor}; use crate::wallet::coin_selection; -use crate::{descriptor, KeychainKind, LoadWithPersistError}; +use crate::{KeychainKind, LoadWithPersistError, descriptor}; use alloc::{ boxed::Box, string::{String, ToString}, }; -use bitcoin::{absolute, psbt, Amount, BlockHash, Network, OutPoint, Sequence, Txid}; +use bitcoin::{Amount, BlockHash, Network, OutPoint, Sequence, Txid, absolute, psbt}; use core::fmt; /// The error type when loading a [`Wallet`] from a [`ChangeSet`]. @@ -233,7 +233,10 @@ impl fmt::Display for CreateTxError { requested, required, } => { - write!(f, "TxBuilder requested timelock of `{requested}`, but at least `{required}` is required to spend from this script") + write!( + f, + "TxBuilder requested timelock of `{requested}`, but at least `{required}` is required to spend from this script" + ) } CreateTxError::RbfSequenceCsv { sequence, csv } => { write!( diff --git a/src/wallet/event.rs b/src/wallet/event.rs index 0f46568d..b53862db 100644 --- a/src/wallet/event.rs +++ b/src/wallet/event.rs @@ -1,8 +1,8 @@ //! User facing wallet events. +use crate::Wallet; use crate::collections::BTreeMap; use crate::wallet::ChainPosition::{Confirmed, Unconfirmed}; -use crate::Wallet; use alloc::sync::Arc; use alloc::vec::Vec; use bitcoin::{Transaction, Txid}; diff --git a/src/wallet/export.rs b/src/wallet/export.rs index b169bba7..6a6cc967 100644 --- a/src/wallet/export.rs +++ b/src/wallet/export.rs @@ -716,11 +716,11 @@ mod test { use core::str::FromStr; use bdk_chain::BlockId; - use bitcoin::{hashes::Hash, BlockHash, Network}; + use bitcoin::{BlockHash, Network, hashes::Hash}; use super::*; - use crate::test_utils::*; use crate::Wallet; + use crate::test_utils::*; fn get_test_wallet(descriptor: &str, change_descriptor: &str, network: Network) -> Wallet { let mut wallet = Wallet::create(descriptor.to_string(), change_descriptor.to_string()) @@ -820,7 +820,10 @@ mod test { let wallet = get_test_wallet(descriptor, change_descriptor, Network::Bitcoin); let export = FullyNodedExport::export_wallet(&wallet, "Test Label", true).unwrap(); - assert_eq!(export.to_string(), "{\"descriptor\":\"wpkh(xprv9s21ZrQH143K4CTb63EaMxja1YiTnSEWKMbn23uoEnAzxjdUJRQkazCAtzxGm4LSoTSVTptoV9RbchnKPW9HxKtZumdyxyikZFDLhogJ5Uj/44\'/0\'/0\'/0/*)\",\"blockheight\":5000,\"label\":\"Test Label\"}"); + assert_eq!( + export.to_string(), + "{\"descriptor\":\"wpkh(xprv9s21ZrQH143K4CTb63EaMxja1YiTnSEWKMbn23uoEnAzxjdUJRQkazCAtzxGm4LSoTSVTptoV9RbchnKPW9HxKtZumdyxyikZFDLhogJ5Uj/44\'/0\'/0\'/0/*)\",\"blockheight\":5000,\"label\":\"Test Label\"}" + ); } #[test] diff --git a/src/wallet/migration.rs b/src/wallet/migration.rs index 3111a08e..dc67deb6 100644 --- a/src/wallet/migration.rs +++ b/src/wallet/migration.rs @@ -13,8 +13,8 @@ //! This module provides helper functions and types to assist users in migrating wallet data //! when upgrading between major versions of the `bdk_wallet` crate. -use crate::rusqlite::{self, Connection}; use crate::KeychainKind::{self, External, Internal}; +use crate::rusqlite::{self, Connection}; use alloc::{ string::{FromUtf8Error, String, ToString}, vec::Vec, @@ -104,8 +104,8 @@ pub fn get_pre_v1_wallet_keychains( #[cfg(test)] mod test { - use crate::rusqlite::{self, Connection}; use crate::KeychainKind::{External, Internal}; + use crate::rusqlite::{self, Connection}; const SCHEMA_SQL: &str = "CREATE TABLE last_derivation_indices (keychain TEXT, value INTEGER); CREATE UNIQUE INDEX idx_indices_keychain ON last_derivation_indices(keychain); diff --git a/src/wallet/mod.rs b/src/wallet/mod.rs index b4eb7709..2fa00d92 100644 --- a/src/wallet/mod.rs +++ b/src/wallet/mod.rs @@ -23,7 +23,8 @@ use core::fmt::{Debug, Display}; use core::{cmp::Ordering, fmt, mem, ops::Deref}; use bdk_chain::{ - indexed_tx_graph, + BlockId, CanonicalizationParams, ChainPosition, ConfirmationBlockTime, DescriptorExt, + FullTxOut, Indexed, IndexedTxGraph, Indexer, Merge, indexed_tx_graph, indexer::keychain_txout::KeychainTxOutIndex, local_chain::{ApplyHeaderError, CannotConnectError, CheckPoint, CheckPointIter, LocalChain}, spk_client::{ @@ -31,18 +32,16 @@ use bdk_chain::{ SyncResponse, }, tx_graph::{CalculateFeeError, CanonicalTx, TxGraph, TxUpdate}, - BlockId, CanonicalizationParams, ChainPosition, ConfirmationBlockTime, DescriptorExt, - FullTxOut, Indexed, IndexedTxGraph, Indexer, Merge, }; use bitcoin::{ - absolute, + Address, Amount, Block, FeeRate, Network, NetworkKind, OutPoint, Psbt, ScriptBuf, Sequence, + SignedAmount, Transaction, TxOut, Txid, Weight, Witness, absolute, consensus::encode::serialize, constants::genesis_block, psbt, secp256k1::Secp256k1, sighash::{EcdsaSighashType, TapSighashType}, - transaction, Address, Amount, Block, FeeRate, Network, NetworkKind, OutPoint, Psbt, ScriptBuf, - Sequence, SignedAmount, Transaction, TxOut, Txid, Weight, Witness, + transaction, }; use miniscript::{ descriptor::KeyMap, @@ -66,9 +65,9 @@ pub(crate) mod utils; use crate::collections::{BTreeMap, HashMap, HashSet}; use crate::descriptor::{ - check_wallet_descriptor, error::Error as DescriptorError, policy::BuildSatisfaction, DerivedDescriptor, DescriptorMeta, ExtendedDescriptor, ExtractPolicy, IntoWalletDescriptor, - Policy, XKeyUtils, + Policy, XKeyUtils, check_wallet_descriptor, error::Error as DescriptorError, + policy::BuildSatisfaction, }; use crate::psbt::PsbtUtils; use crate::types::*; @@ -77,7 +76,7 @@ use crate::wallet::{ error::{BuildFeeBumpError, CreateTxError, MiniscriptPsbtError}, signer::{SignOptions, SignerError, SignerOrdering, SignersContainer, TransactionSigner}, tx_builder::{FeePolicy, TxBuilder, TxParams}, - utils::{check_nsequence_rbf, After, Older, SecpCtx}, + utils::{After, Older, SecpCtx, check_nsequence_rbf}, }; // re-exports @@ -520,7 +519,7 @@ impl Wallet { keychain: KeychainKind::Internal, loaded: Some(Box::new(desc)), expected: None, - })) + })); } // Parameters must match. Some(make_desc) => { @@ -1294,7 +1293,7 @@ impl Wallet { let version = match params.version { Some(transaction::Version(0)) => return Err(CreateTxError::Version0), Some(transaction::Version::ONE) if requirements.csv.is_some() => { - return Err(CreateTxError::Version1Csv) + return Err(CreateTxError::Version1Csv); } Some(v) => v, None => transaction::Version::TWO, @@ -1347,7 +1346,7 @@ impl Wallet { return Err(CreateTxError::LockTime { requested: x, required: requirements.timelock.unwrap(), - }) + }); } }; @@ -1361,7 +1360,7 @@ impl Wallet { (None, Some(csv)) => csv, // Requested sequence is incompatible with requirements. (Some(sequence), Some(csv)) if !check_nsequence_rbf(sequence, csv) => { - return Err(CreateTxError::RbfSequenceCsv { sequence, csv }) + return Err(CreateTxError::RbfSequenceCsv { sequence, csv }); } // Use requested nSequence value. (Some(sequence), _) => sequence, @@ -2985,16 +2984,18 @@ mod test { let received = wallet.filter_utxos(¶ms, wallet.latest_checkpoint().block_id().height); // Notice expected doesn't include the first output from two_output_tx as it should be // filtered out. - let expected = vec![wallet - .get_utxo(OutPoint { txid, vout: 1 }) - .map(|utxo| WeightedUtxo { - satisfaction_weight: wallet - .public_descriptor(utxo.keychain) - .max_weight_to_satisfy() - .unwrap(), - utxo: Utxo::Local(utxo), - }) - .unwrap()]; + let expected = vec![ + wallet + .get_utxo(OutPoint { txid, vout: 1 }) + .map(|utxo| WeightedUtxo { + satisfaction_weight: wallet + .public_descriptor(utxo.keychain) + .max_weight_to_satisfy() + .unwrap(), + utxo: Utxo::Local(utxo), + }) + .unwrap(), + ]; assert_eq!(expected, received); } diff --git a/src/wallet/params.rs b/src/wallet/params.rs index 4868074b..249e192d 100644 --- a/src/wallet/params.rs +++ b/src/wallet/params.rs @@ -5,10 +5,10 @@ use bitcoin::{BlockHash, Network, NetworkKind}; use miniscript::descriptor::KeyMap; use crate::{ - descriptor::{DescriptorError, ExtendedDescriptor, IntoWalletDescriptor}, - utils::SecpCtx, AsyncWalletPersister, CreateWithPersistError, KeychainKind, LoadWithPersistError, Wallet, WalletPersister, + descriptor::{DescriptorError, ExtendedDescriptor, IntoWalletDescriptor}, + utils::SecpCtx, }; use super::{ChangeSet, LoadError, PersistedWallet}; diff --git a/src/wallet/persisted.rs b/src/wallet/persisted.rs index 82572399..7ef33982 100644 --- a/src/wallet/persisted.rs +++ b/src/wallet/persisted.rs @@ -11,8 +11,8 @@ use chain::Merge; use crate::error::LoadError; use crate::{ - descriptor::{calc_checksum, DescriptorError}, ChangeSet, CreateParams, LoadParams, Wallet, + descriptor::{DescriptorError, calc_checksum}, }; /// Trait that persists [`PersistedWallet`]. diff --git a/src/wallet/signer.rs b/src/wallet/signer.rs index 88050db5..ea1f7b61 100644 --- a/src/wallet/signer.rs +++ b/src/wallet/signer.rs @@ -93,9 +93,9 @@ use bitcoin::bip32::{ChildNumber, DerivationPath, Fingerprint, Xpriv}; use bitcoin::hashes::hash160; use bitcoin::secp256k1::Message; use bitcoin::sighash::{EcdsaSighashType, TapSighash, TapSighashType}; +use bitcoin::{PrivateKey, Psbt, PublicKey}; use bitcoin::{ecdsa, psbt, sighash, taproot}; use bitcoin::{key::TapTweak, key::XOnlyPublicKey, secp256k1}; -use bitcoin::{PrivateKey, Psbt, PublicKey}; use miniscript::descriptor::{ Descriptor, DescriptorMultiXKey, DescriptorPublicKey, DescriptorSecretKey, DescriptorXKey, @@ -178,7 +178,10 @@ impl fmt::Display for SignerError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::MissingKey => write!(f, "Missing private key"), - Self::InvalidKey => write!(f, "The private key in use has the right fingerprint but derives differently than expected"), + Self::InvalidKey => write!( + f, + "The private key in use has the right fingerprint but derives differently than expected" + ), Self::UserCanceled => write!(f, "The user canceled the operation"), Self::InputIndexOutOfRange(err) => write!(f, "{err}"), Self::MissingNonWitnessUtxo => write!(f, "Missing non-witness UTXO"), @@ -188,7 +191,10 @@ impl fmt::Display for SignerError { Self::MissingHdKeypath => write!(f, "Missing fingerprint and derivation path"), Self::NonStandardSighash => write!(f, "The psbt contains a non standard sighash"), Self::InvalidSighash => write!(f, "Invalid SIGHASH for the signing context in use"), - Self::SighashTaproot(err) => write!(f, "Error while computing the hash to sign a Taproot input: {err}"), + Self::SighashTaproot(err) => write!( + f, + "Error while computing the hash to sign a Taproot input: {err}" + ), Self::Psbt(err) => write!(f, "Error computing the sighash: {err}"), Self::MiniscriptPsbt(err) => write!(f, "Miniscript PSBT error: {err}"), Self::External(err) => write!(f, "{err}"), @@ -927,9 +933,8 @@ mod signers_container_tests { use assert_matches::assert_matches; use bitcoin::{ - bip32, + NetworkKind, bip32, secp256k1::{All, Secp256k1}, - NetworkKind, }; use core::str::FromStr; use miniscript::ScriptContext; @@ -1032,8 +1037,8 @@ mod signers_container_tests { } } - const TPRV0_STR:&str = "tprv8ZgxMBicQKsPdZXrcHNLf5JAJWFAoJ2TrstMRdSKtEggz6PddbuSkvHKM9oKJyFgZV1B7rw8oChspxyYbtmEXYyg1AjfWbL3ho3XHDpHRZf"; - const TPRV1_STR:&str = "tprv8ZgxMBicQKsPdpkqS7Eair4YxjcuuvDPNYmKX3sCniCf16tHEVrjjiSXEkFRnUH77yXc6ZcwHHcLNfjdi5qUvw3VDfgYiH5mNsj5izuiu2N"; + const TPRV0_STR: &str = "tprv8ZgxMBicQKsPdZXrcHNLf5JAJWFAoJ2TrstMRdSKtEggz6PddbuSkvHKM9oKJyFgZV1B7rw8oChspxyYbtmEXYyg1AjfWbL3ho3XHDpHRZf"; + const TPRV1_STR: &str = "tprv8ZgxMBicQKsPdpkqS7Eair4YxjcuuvDPNYmKX3sCniCf16tHEVrjjiSXEkFRnUH77yXc6ZcwHHcLNfjdi5qUvw3VDfgYiH5mNsj5izuiu2N"; const PATH: &str = "m/44'/1'/0'/0"; diff --git a/src/wallet/tx_builder.rs b/src/wallet/tx_builder.rs index 767cd5a4..5af8b678 100644 --- a/src/wallet/tx_builder.rs +++ b/src/wallet/tx_builder.rs @@ -44,8 +44,8 @@ use alloc::sync::Arc; use bitcoin::psbt::{self, Psbt}; use bitcoin::script::PushBytes; use bitcoin::{ - absolute, transaction::Version, Amount, FeeRate, OutPoint, ScriptBuf, Sequence, Transaction, - TxIn, TxOut, Txid, Weight, + Amount, FeeRate, OutPoint, ScriptBuf, Sequence, Transaction, TxIn, TxOut, Txid, Weight, + absolute, transaction::Version, }; use rand_core::RngCore; @@ -931,9 +931,9 @@ mod test { }; } + use bitcoin::TxOut; use bitcoin::consensus::deserialize; use bitcoin::hex::FromHex; - use bitcoin::TxOut; use super::*; #[test] @@ -1023,7 +1023,7 @@ mod test { #[test] fn test_output_ordering_custom_with_sha256() { - use bitcoin::hashes::{sha256, Hash}; + use bitcoin::hashes::{Hash, sha256}; let original_tx = ordering_test_tx!(); let mut tx_1 = original_tx.clone(); @@ -1158,7 +1158,7 @@ mod test { fn test_exclude_unconfirmed() { use crate::test_utils::*; use bdk_chain::BlockId; - use bitcoin::{hashes::Hash, BlockHash, Network}; + use bitcoin::{BlockHash, Network, hashes::Hash}; let mut wallet = Wallet::create_single(get_test_tr_single_sig()) .network(Network::Regtest) @@ -1248,7 +1248,7 @@ mod test { fn test_build_fee_bump_remove_change_output_single_desc() { use crate::test_utils::*; use bdk_chain::BlockId; - use bitcoin::{hashes::Hash, BlockHash, Network}; + use bitcoin::{BlockHash, Network, hashes::Hash}; let mut wallet = Wallet::create_single(get_test_tr_single_sig()) .network(Network::Regtest) @@ -1343,32 +1343,36 @@ mod test { let mut builder = wallet2.build_tx(); // add foreign UTXO with satisfaction weight x - assert!(builder - .add_foreign_utxo( - utxo1.outpoint, - psbt::Input { - non_witness_utxo: Some(tx1.as_ref().clone()), - ..Default::default() - }, - satisfaction_weight, - ) - .is_ok()); + assert!( + builder + .add_foreign_utxo( + utxo1.outpoint, + psbt::Input { + non_witness_utxo: Some(tx1.as_ref().clone()), + ..Default::default() + }, + satisfaction_weight, + ) + .is_ok() + ); let modified_satisfaction_weight = satisfaction_weight - Weight::from_wu(6); assert_ne!(satisfaction_weight, modified_satisfaction_weight); // add foreign UTXO with same outpoint but satisfaction weight x - 6wu - assert!(builder - .add_foreign_utxo( - utxo1.outpoint, - psbt::Input { - non_witness_utxo: Some(tx1.as_ref().clone()), - ..Default::default() - }, - modified_satisfaction_weight, - ) - .is_ok()); + assert!( + builder + .add_foreign_utxo( + utxo1.outpoint, + psbt::Input { + non_witness_utxo: Some(tx1.as_ref().clone()), + ..Default::default() + }, + modified_satisfaction_weight, + ) + .is_ok() + ); assert_eq!(builder.params.utxos.len(), 1); assert_eq!( diff --git a/src/wallet/utils.rs b/src/wallet/utils.rs index adf239f9..02007964 100644 --- a/src/wallet/utils.rs +++ b/src/wallet/utils.rs @@ -12,7 +12,7 @@ use alloc::sync::Arc; use bitcoin::secp256k1::{All, Secp256k1}; use bitcoin::{ - absolute, relative, Amount, FeeRate, Script, Sequence, SignedAmount, Transaction, Txid, + Amount, FeeRate, Script, Sequence, SignedAmount, Transaction, Txid, absolute, relative, }; use chain::{ChainPosition, ConfirmationBlockTime}; use miniscript::{MiniscriptKey, Satisfier, ToPublicKey}; @@ -170,11 +170,11 @@ mod test { // otherwise it's time-based pub(crate) const SEQUENCE_LOCKTIME_TYPE_FLAG: u32 = 1 << 22; - use super::{check_nsequence_rbf, shuffle_slice, IsDust}; + use super::{IsDust, check_nsequence_rbf, shuffle_slice}; use crate::bitcoin::{Address, Network, Sequence}; use alloc::vec::Vec; use core::str::FromStr; - use rand::{rngs::StdRng, thread_rng, SeedableRng}; + use rand::{SeedableRng, rngs::StdRng, thread_rng}; #[test] fn test_is_dust() { diff --git a/tests/add_foreign_utxo.rs b/tests/add_foreign_utxo.rs index 1dd0a8c9..14df67a5 100644 --- a/tests/add_foreign_utxo.rs +++ b/tests/add_foreign_utxo.rs @@ -1,11 +1,11 @@ use std::str::FromStr; +use bdk_wallet::KeychainKind; use bdk_wallet::psbt::PsbtUtils; use bdk_wallet::signer::SignOptions; use bdk_wallet::test_utils::*; use bdk_wallet::tx_builder::AddForeignUtxoError; -use bdk_wallet::KeychainKind; -use bitcoin::{psbt, Address, Amount}; +use bitcoin::{Address, Amount, psbt}; mod common; diff --git a/tests/build_fee_bump.rs b/tests/build_fee_bump.rs index 4a243dfa..8df2eb57 100644 --- a/tests/build_fee_bump.rs +++ b/tests/build_fee_bump.rs @@ -2,14 +2,14 @@ use std::str::FromStr; use assert_matches::assert_matches; use bdk_chain::{ChainPosition, ConfirmationBlockTime}; +use bdk_wallet::KeychainKind; use bdk_wallet::coin_selection::LargestFirstCoinSelection; use bdk_wallet::error::CreateTxError; use bdk_wallet::psbt::PsbtUtils; use bdk_wallet::test_utils::*; -use bdk_wallet::KeychainKind; use bitcoin::{ - absolute, hashes::Hash, psbt, transaction, Address, Amount, FeeRate, OutPoint, ScriptBuf, - Sequence, Transaction, TxOut, Weight, + Address, Amount, FeeRate, OutPoint, ScriptBuf, Sequence, Transaction, TxOut, Weight, absolute, + hashes::Hash, psbt, transaction, }; mod common; diff --git a/tests/common.rs b/tests/common.rs index c7a9b9c5..37795f05 100644 --- a/tests/common.rs +++ b/tests/common.rs @@ -1,7 +1,7 @@ #![allow(unused)] use bitcoin::secp256k1::Secp256k1; -use miniscript::{descriptor::KeyMap, Descriptor, DescriptorPublicKey}; +use miniscript::{Descriptor, DescriptorPublicKey, descriptor::KeyMap}; /// The satisfaction size of P2WPKH is 108 WU = /// 1 (elements in witness) + 1 (size) + 72 (signature + sighash) + 1 (size) + 33 (pubkey). diff --git a/tests/persisted_wallet.rs b/tests/persisted_wallet.rs index f0a9bbab..2e009378 100644 --- a/tests/persisted_wallet.rs +++ b/tests/persisted_wallet.rs @@ -5,7 +5,7 @@ use anyhow::Context; use assert_matches::assert_matches; use bdk_chain::DescriptorId; use bdk_chain::{ - keychain_txout::DEFAULT_LOOKAHEAD, ChainPosition, ConfirmationBlockTime, DescriptorExt, + ChainPosition, ConfirmationBlockTime, DescriptorExt, keychain_txout::DEFAULT_LOOKAHEAD, }; use bdk_wallet::coin_selection::InsufficientFunds; use bdk_wallet::descriptor::IntoWalletDescriptor; @@ -18,8 +18,8 @@ use bitcoin::constants::ChainHash; use bitcoin::hashes::Hash; use bitcoin::key::Secp256k1; use bitcoin::{ - absolute, secp256k1, transaction, Amount, BlockHash, Network, NetworkKind, ScriptBuf, - Transaction, TxOut, + Amount, BlockHash, Network, NetworkKind, ScriptBuf, Transaction, TxOut, absolute, secp256k1, + transaction, }; use miniscript::{Descriptor, DescriptorPublicKey}; @@ -266,8 +266,12 @@ fn wallet_load_checks() -> anyhow::Result<()> { ); let mainnet_hash = BlockHash::from_byte_array(ChainHash::BITCOIN.to_bytes()); assert_matches!( - Wallet::load().check_genesis_hash(mainnet_hash).load_wallet(&mut open_db(&file_path)?), - Err(LoadWithPersistError::InvalidChangeSet(LoadError::Mismatch(LoadMismatch::Genesis { .. }))), + Wallet::load() + .check_genesis_hash(mainnet_hash) + .load_wallet(&mut open_db(&file_path)?), + Err(LoadWithPersistError::InvalidChangeSet(LoadError::Mismatch( + LoadMismatch::Genesis { .. } + ))), "unexpected genesis hash check result: mainnet hash (check) is not testnet hash (loaded)", ); assert_matches!( diff --git a/tests/psbt.rs b/tests/psbt.rs index 08c4acc9..ece8f8e6 100644 --- a/tests/psbt.rs +++ b/tests/psbt.rs @@ -1,6 +1,6 @@ use bdk_wallet::bitcoin::{Amount, FeeRate, Psbt, TxIn}; use bdk_wallet::test_utils::*; -use bdk_wallet::{psbt, KeychainKind, SignOptions}; +use bdk_wallet::{KeychainKind, SignOptions, psbt}; use core::str::FromStr; // from bip 174 @@ -80,7 +80,9 @@ fn test_psbt_fee_rate_with_witness_utxo() { let expected_fee_rate = FeeRate::from_sat_per_kwu(310); - let (mut wallet, _) = get_funded_wallet_single("wpkh(tprv8ZgxMBicQKsPd3EupYiPRhaMooHKUHJxNsTfYuScep13go8QFfHdtkG9nRkFGb7busX4isf6X9dURGCoKgitaApQ6MupRhZMcELAxTBRJgS/*)"); + let (mut wallet, _) = get_funded_wallet_single( + "wpkh(tprv8ZgxMBicQKsPd3EupYiPRhaMooHKUHJxNsTfYuScep13go8QFfHdtkG9nRkFGb7busX4isf6X9dURGCoKgitaApQ6MupRhZMcELAxTBRJgS/*)", + ); let addr = wallet.peek_address(KeychainKind::External, 0); let mut builder = wallet.build_tx(); builder.drain_to(addr.script_pubkey()).drain_wallet(); @@ -105,7 +107,9 @@ fn test_psbt_fee_rate_with_nonwitness_utxo() { let expected_fee_rate = FeeRate::from_sat_per_kwu(310); - let (mut wallet, _) = get_funded_wallet_single("pkh(tprv8ZgxMBicQKsPd3EupYiPRhaMooHKUHJxNsTfYuScep13go8QFfHdtkG9nRkFGb7busX4isf6X9dURGCoKgitaApQ6MupRhZMcELAxTBRJgS/*)"); + let (mut wallet, _) = get_funded_wallet_single( + "pkh(tprv8ZgxMBicQKsPd3EupYiPRhaMooHKUHJxNsTfYuScep13go8QFfHdtkG9nRkFGb7busX4isf6X9dURGCoKgitaApQ6MupRhZMcELAxTBRJgS/*)", + ); let addr = wallet.peek_address(KeychainKind::External, 0); let mut builder = wallet.build_tx(); builder.drain_to(addr.script_pubkey()).drain_wallet(); @@ -129,7 +133,9 @@ fn test_psbt_fee_rate_with_missing_txout() { let expected_fee_rate = FeeRate::from_sat_per_kwu(310); - let (mut wpkh_wallet, _) = get_funded_wallet_single("wpkh(tprv8ZgxMBicQKsPd3EupYiPRhaMooHKUHJxNsTfYuScep13go8QFfHdtkG9nRkFGb7busX4isf6X9dURGCoKgitaApQ6MupRhZMcELAxTBRJgS/*)"); + let (mut wpkh_wallet, _) = get_funded_wallet_single( + "wpkh(tprv8ZgxMBicQKsPd3EupYiPRhaMooHKUHJxNsTfYuScep13go8QFfHdtkG9nRkFGb7busX4isf6X9dURGCoKgitaApQ6MupRhZMcELAxTBRJgS/*)", + ); let addr = wpkh_wallet.peek_address(KeychainKind::External, 0); let mut builder = wpkh_wallet.build_tx(); builder.drain_to(addr.script_pubkey()).drain_wallet(); @@ -157,10 +163,10 @@ fn test_psbt_fee_rate_with_missing_txout() { #[test] fn test_psbt_multiple_internalkey_signers() { - use bdk_wallet::signer::{SignerContext, SignerOrdering, SignerWrapper}; use bdk_wallet::KeychainKind; + use bdk_wallet::signer::{SignerContext, SignerOrdering, SignerWrapper}; use bitcoin::key::TapTweak; - use bitcoin::secp256k1::{schnorr, Keypair, Message, Secp256k1, XOnlyPublicKey}; + use bitcoin::secp256k1::{Keypair, Message, Secp256k1, XOnlyPublicKey, schnorr}; use bitcoin::sighash::{Prevouts, SighashCache, TapSighashType}; use bitcoin::{PrivateKey, TxOut}; use std::sync::Arc; diff --git a/tests/wallet.rs b/tests/wallet.rs index c6048593..cce8e127 100644 --- a/tests/wallet.rs +++ b/tests/wallet.rs @@ -3,13 +3,13 @@ use std::sync::Arc; use assert_matches::assert_matches; use bdk_chain::{BlockId, CanonicalizationParams, ConfirmationBlockTime}; +use bdk_wallet::KeychainKind; use bdk_wallet::coin_selection; -use bdk_wallet::descriptor::{calc_checksum, DescriptorError}; +use bdk_wallet::descriptor::{DescriptorError, calc_checksum}; use bdk_wallet::error::CreateTxError; use bdk_wallet::psbt::PsbtUtils; use bdk_wallet::signer::{SignOptions, SignerError}; use bdk_wallet::test_utils::*; -use bdk_wallet::KeychainKind; use bdk_wallet::{AddressInfo, Balance, PersistedWallet, Update, Wallet, WalletTx}; use bitcoin::constants::COINBASE_MATURITY; use bitcoin::hashes::Hash; @@ -17,11 +17,11 @@ use bitcoin::script::PushBytesBuf; use bitcoin::sighash::{EcdsaSighashType, TapSighashType}; use bitcoin::taproot::TapNodeHash; use bitcoin::{ - absolute, transaction, Address, Amount, BlockHash, FeeRate, Network, OutPoint, ScriptBuf, - Sequence, SignedAmount, Transaction, TxIn, TxOut, Txid, + Address, Amount, BlockHash, FeeRate, Network, OutPoint, ScriptBuf, Sequence, SignedAmount, + Transaction, TxIn, TxOut, Txid, absolute, transaction, }; -use rand::rngs::StdRng; use rand::SeedableRng; +use rand::rngs::StdRng; mod common; @@ -812,7 +812,9 @@ fn test_create_tx_input_hd_keypaths() { use bitcoin::bip32::{DerivationPath, Fingerprint}; use core::str::FromStr; - let (mut wallet, _) = get_funded_wallet_single("wpkh([d34db33f/44'/0'/0']tpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/0/*)"); + let (mut wallet, _) = get_funded_wallet_single( + "wpkh([d34db33f/44'/0'/0']tpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/0/*)", + ); let addr = wallet.next_unused_address(KeychainKind::External); let mut builder = wallet.build_tx(); builder.drain_to(addr.script_pubkey()).drain_wallet(); @@ -833,7 +835,9 @@ fn test_create_tx_output_hd_keypaths() { use bitcoin::bip32::{DerivationPath, Fingerprint}; use core::str::FromStr; - let (mut wallet, _) = get_funded_wallet_single("wpkh([d34db33f/44'/0'/0']tpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/0/*)"); + let (mut wallet, _) = get_funded_wallet_single( + "wpkh([d34db33f/44'/0'/0']tpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/0/*)", + ); let addr = wallet.next_unused_address(KeychainKind::External); let mut builder = wallet.build_tx(); @@ -1125,7 +1129,9 @@ fn test_create_tx_policy_path_use_csv() { #[test] fn test_create_tx_policy_path_ignored_subtree_with_csv() { - let (mut wallet, _) = get_funded_wallet_single("wsh(or_d(pk(cRjo6jqfVNP33HhSS76UhXETZsGTZYx8FMFvR9kpbtCSV1PmdZdu),or_i(and_v(v:pkh(cVpPVruEDdmutPzisEsYvtST1usBR3ntr8pXSyt6D2YYqXRyPcFW),older(30)),and_v(v:pkh(cMnkdebixpXMPfkcNEjjGin7s94hiehAH4mLbYkZoh9KSiNNmqC8),older(90)))))"); + let (mut wallet, _) = get_funded_wallet_single( + "wsh(or_d(pk(cRjo6jqfVNP33HhSS76UhXETZsGTZYx8FMFvR9kpbtCSV1PmdZdu),or_i(and_v(v:pkh(cVpPVruEDdmutPzisEsYvtST1usBR3ntr8pXSyt6D2YYqXRyPcFW),older(30)),and_v(v:pkh(cMnkdebixpXMPfkcNEjjGin7s94hiehAH4mLbYkZoh9KSiNNmqC8),older(90)))))", + ); let external_policy = wallet.policies(KeychainKind::External).unwrap().unwrap(); let root_id = external_policy.id; @@ -1147,7 +1153,9 @@ fn test_create_tx_policy_path_ignored_subtree_with_csv() { #[test] fn test_create_tx_global_xpubs_with_origin() { use bitcoin::bip32; - let (mut wallet, _) = get_funded_wallet_single("wpkh([73756c7f/48'/0'/0'/2']tpubDCKxNyM3bLgbEX13Mcd8mYxbVg9ajDkWXMh29hMWBurKfVmBfWAM96QVP3zaUcN51HvkZ3ar4VwP82kC8JZhhux8vFQoJintSpVBwpFvyU3/0/*)"); + let (mut wallet, _) = get_funded_wallet_single( + "wpkh([73756c7f/48'/0'/0'/2']tpubDCKxNyM3bLgbEX13Mcd8mYxbVg9ajDkWXMh29hMWBurKfVmBfWAM96QVP3zaUcN51HvkZ3ar4VwP82kC8JZhhux8vFQoJintSpVBwpFvyU3/0/*)", + ); let addr = wallet.next_unused_address(KeychainKind::External); let mut builder = wallet.build_tx(); builder @@ -1299,7 +1307,9 @@ fn test_get_psbt_input() { expected = "MissingKeyOrigin(\"tpubDCKxNyM3bLgbEX13Mcd8mYxbVg9ajDkWXMh29hMWBurKfVmBfWAM96QVP3zaUcN51HvkZ3ar4VwP82kC8JZhhux8vFQoJintSpVBwpFvyU3\")" )] fn test_create_tx_global_xpubs_origin_missing() { - let (mut wallet, _) = get_funded_wallet_single("wpkh(tpubDCKxNyM3bLgbEX13Mcd8mYxbVg9ajDkWXMh29hMWBurKfVmBfWAM96QVP3zaUcN51HvkZ3ar4VwP82kC8JZhhux8vFQoJintSpVBwpFvyU3/0/*)"); + let (mut wallet, _) = get_funded_wallet_single( + "wpkh(tpubDCKxNyM3bLgbEX13Mcd8mYxbVg9ajDkWXMh29hMWBurKfVmBfWAM96QVP3zaUcN51HvkZ3ar4VwP82kC8JZhhux8vFQoJintSpVBwpFvyU3/0/*)", + ); let addr = wallet.next_unused_address(KeychainKind::External); let mut builder = wallet.build_tx(); builder @@ -1311,7 +1321,9 @@ fn test_create_tx_global_xpubs_origin_missing() { #[test] fn test_create_tx_global_xpubs_master_without_origin() { use bitcoin::bip32; - let (mut wallet, _) = get_funded_wallet_single("wpkh(tpubD6NzVbkrYhZ4Y55A58Gv9RSNF5hy84b5AJqYy7sCcjFrkcLpPre8kmgfit6kY1Zs3BLgeypTDBZJM222guPpdz7Cup5yzaMu62u7mYGbwFL/0/*)"); + let (mut wallet, _) = get_funded_wallet_single( + "wpkh(tpubD6NzVbkrYhZ4Y55A58Gv9RSNF5hy84b5AJqYy7sCcjFrkcLpPre8kmgfit6kY1Zs3BLgeypTDBZJM222guPpdz7Cup5yzaMu62u7mYGbwFL/0/*)", + ); let addr = wallet.next_unused_address(KeychainKind::External); let mut builder = wallet.build_tx(); builder @@ -1361,7 +1373,9 @@ fn test_fee_amount_negative_drain_val() { #[test] fn test_sign_single_xprv() { - let (mut wallet, _) = get_funded_wallet_single("wpkh(tprv8ZgxMBicQKsPd3EupYiPRhaMooHKUHJxNsTfYuScep13go8QFfHdtkG9nRkFGb7busX4isf6X9dURGCoKgitaApQ6MupRhZMcELAxTBRJgS/*)"); + let (mut wallet, _) = get_funded_wallet_single( + "wpkh(tprv8ZgxMBicQKsPd3EupYiPRhaMooHKUHJxNsTfYuScep13go8QFfHdtkG9nRkFGb7busX4isf6X9dURGCoKgitaApQ6MupRhZMcELAxTBRJgS/*)", + ); let addr = wallet.next_unused_address(KeychainKind::External); let mut builder = wallet.build_tx(); builder.drain_to(addr.script_pubkey()).drain_wallet(); @@ -1376,7 +1390,9 @@ fn test_sign_single_xprv() { #[test] fn test_sign_single_xprv_with_master_fingerprint_and_path() { - let (mut wallet, _) = get_funded_wallet_single("wpkh([d34db33f/84h/1h/0h]tprv8ZgxMBicQKsPd3EupYiPRhaMooHKUHJxNsTfYuScep13go8QFfHdtkG9nRkFGb7busX4isf6X9dURGCoKgitaApQ6MupRhZMcELAxTBRJgS/*)"); + let (mut wallet, _) = get_funded_wallet_single( + "wpkh([d34db33f/84h/1h/0h]tprv8ZgxMBicQKsPd3EupYiPRhaMooHKUHJxNsTfYuScep13go8QFfHdtkG9nRkFGb7busX4isf6X9dURGCoKgitaApQ6MupRhZMcELAxTBRJgS/*)", + ); let addr = wallet.next_unused_address(KeychainKind::External); let mut builder = wallet.build_tx(); builder.drain_to(addr.script_pubkey()).drain_wallet(); @@ -1391,7 +1407,9 @@ fn test_sign_single_xprv_with_master_fingerprint_and_path() { #[test] fn test_sign_single_xprv_bip44_path() { - let (mut wallet, _) = get_funded_wallet_single("wpkh(tprv8ZgxMBicQKsPd3EupYiPRhaMooHKUHJxNsTfYuScep13go8QFfHdtkG9nRkFGb7busX4isf6X9dURGCoKgitaApQ6MupRhZMcELAxTBRJgS/44'/0'/0'/0/*)"); + let (mut wallet, _) = get_funded_wallet_single( + "wpkh(tprv8ZgxMBicQKsPd3EupYiPRhaMooHKUHJxNsTfYuScep13go8QFfHdtkG9nRkFGb7busX4isf6X9dURGCoKgitaApQ6MupRhZMcELAxTBRJgS/44'/0'/0'/0/*)", + ); let addr = wallet.next_unused_address(KeychainKind::External); let mut builder = wallet.build_tx(); builder.drain_to(addr.script_pubkey()).drain_wallet(); @@ -1406,7 +1424,9 @@ fn test_sign_single_xprv_bip44_path() { #[test] fn test_sign_single_xprv_sh_wpkh() { - let (mut wallet, _) = get_funded_wallet_single("sh(wpkh(tprv8ZgxMBicQKsPd3EupYiPRhaMooHKUHJxNsTfYuScep13go8QFfHdtkG9nRkFGb7busX4isf6X9dURGCoKgitaApQ6MupRhZMcELAxTBRJgS/*))"); + let (mut wallet, _) = get_funded_wallet_single( + "sh(wpkh(tprv8ZgxMBicQKsPd3EupYiPRhaMooHKUHJxNsTfYuScep13go8QFfHdtkG9nRkFGb7busX4isf6X9dURGCoKgitaApQ6MupRhZMcELAxTBRJgS/*))", + ); let addr = wallet.next_unused_address(KeychainKind::External); let mut builder = wallet.build_tx(); builder.drain_to(addr.script_pubkey()).drain_wallet(); @@ -1437,7 +1457,9 @@ fn test_sign_single_wif() { #[test] fn test_sign_single_xprv_no_hd_keypaths() { - let (mut wallet, _) = get_funded_wallet_single("wpkh(tprv8ZgxMBicQKsPd3EupYiPRhaMooHKUHJxNsTfYuScep13go8QFfHdtkG9nRkFGb7busX4isf6X9dURGCoKgitaApQ6MupRhZMcELAxTBRJgS/*)"); + let (mut wallet, _) = get_funded_wallet_single( + "wpkh(tprv8ZgxMBicQKsPd3EupYiPRhaMooHKUHJxNsTfYuScep13go8QFfHdtkG9nRkFGb7busX4isf6X9dURGCoKgitaApQ6MupRhZMcELAxTBRJgS/*)", + ); let addr = wallet.next_unused_address(KeychainKind::External); let mut builder = wallet.build_tx(); builder.drain_to(addr.script_pubkey()).drain_wallet(); @@ -1528,7 +1550,9 @@ fn test_signing_only_one_of_multiple_inputs() { #[test] fn test_try_finalize_sign_option() { - let (mut wallet, _) = get_funded_wallet_single("wpkh(tprv8ZgxMBicQKsPd3EupYiPRhaMooHKUHJxNsTfYuScep13go8QFfHdtkG9nRkFGb7busX4isf6X9dURGCoKgitaApQ6MupRhZMcELAxTBRJgS/*)"); + let (mut wallet, _) = get_funded_wallet_single( + "wpkh(tprv8ZgxMBicQKsPd3EupYiPRhaMooHKUHJxNsTfYuScep13go8QFfHdtkG9nRkFGb7busX4isf6X9dURGCoKgitaApQ6MupRhZMcELAxTBRJgS/*)", + ); for try_finalize in &[true, false] { let addr = wallet.next_unused_address(KeychainKind::External); @@ -1613,7 +1637,9 @@ fn test_taproot_try_finalize_sign_option() { fn test_sign_nonstandard_sighash() { let sighash = EcdsaSighashType::NonePlusAnyoneCanPay; - let (mut wallet, _) = get_funded_wallet_single("wpkh(tprv8ZgxMBicQKsPd3EupYiPRhaMooHKUHJxNsTfYuScep13go8QFfHdtkG9nRkFGb7busX4isf6X9dURGCoKgitaApQ6MupRhZMcELAxTBRJgS/*)"); + let (mut wallet, _) = get_funded_wallet_single( + "wpkh(tprv8ZgxMBicQKsPd3EupYiPRhaMooHKUHJxNsTfYuScep13go8QFfHdtkG9nRkFGb7busX4isf6X9dURGCoKgitaApQ6MupRhZMcELAxTBRJgS/*)", + ); let addr = wallet.next_unused_address(KeychainKind::External); let mut builder = wallet.build_tx(); builder @@ -1665,10 +1691,12 @@ fn test_unused_address() { .expect("wallet"); // `list_unused_addresses` should be empty if we haven't revealed any - assert!(wallet - .list_unused_addresses(KeychainKind::External) - .next() - .is_none()); + assert!( + wallet + .list_unused_addresses(KeychainKind::External) + .next() + .is_none() + ); assert_eq!( wallet @@ -1802,8 +1830,7 @@ fn test_peek_address_at_index_not_derivable() { #[test] fn test_returns_index_and_address() { - let descriptor = - "wpkh(tpubEBr4i6yk5nf5DAaJpsi9N2pPYBeJ7fZ5Z9rmN4977iYLCGco1VyjB9tvvuvYtfZzjD5A8igzgw3HeWeeKFmanHYqksqZXYXGsw5zjnj7KM9/*)"; + let descriptor = "wpkh(tpubEBr4i6yk5nf5DAaJpsi9N2pPYBeJ7fZ5Z9rmN4977iYLCGco1VyjB9tvvuvYtfZzjD5A8igzgw3HeWeeKFmanHYqksqZXYXGsw5zjnj7KM9/*)"; let mut wallet = Wallet::create(descriptor, get_test_wpkh()) .network(Network::Testnet) .create_wallet_no_persist() @@ -2240,10 +2267,11 @@ fn test_taproot_script_spend_sign_all_leaves() { "Unable to finalize tx" ); - assert!(psbt - .inputs - .iter() - .all(|i| i.tap_script_sigs.len() == i.tap_scripts.len())); + assert!( + psbt.inputs + .iter() + .all(|i| i.tap_script_sigs.len() == i.tap_scripts.len()) + ); } #[test] @@ -2279,11 +2307,9 @@ fn test_taproot_script_spend_sign_include_some_leaves() { "Unable to finalize tx" ); - assert!(psbt.inputs[0] - .tap_script_sigs - .iter() - .all(|s| included_script_leaves.contains(&s.0 .1) - && !excluded_script_leaves.contains(&s.0 .1))); + assert!(psbt.inputs[0].tap_script_sigs.iter().all( + |s| included_script_leaves.contains(&s.0.1) && !excluded_script_leaves.contains(&s.0.1) + )); } #[test] @@ -2319,11 +2345,9 @@ fn test_taproot_script_spend_sign_exclude_some_leaves() { "Unable to finalize tx" ); - assert!(psbt.inputs[0] - .tap_script_sigs - .iter() - .all(|s| included_script_leaves.contains(&s.0 .1) - && !excluded_script_leaves.contains(&s.0 .1))); + assert!(psbt.inputs[0].tap_script_sigs.iter().all( + |s| included_script_leaves.contains(&s.0.1) && !excluded_script_leaves.contains(&s.0.1) + )); } #[test] @@ -2616,7 +2640,9 @@ fn test_fee_rate_sign_no_grinding_high_r() { // Our goal is to obtain a transaction with a signature with high-R (71 bytes // instead of 70). We then check that our fee rate and fee calculation is // alright. - let (mut wallet, _) = get_funded_wallet_single("wpkh(tprv8ZgxMBicQKsPd3EupYiPRhaMooHKUHJxNsTfYuScep13go8QFfHdtkG9nRkFGb7busX4isf6X9dURGCoKgitaApQ6MupRhZMcELAxTBRJgS/*)"); + let (mut wallet, _) = get_funded_wallet_single( + "wpkh(tprv8ZgxMBicQKsPd3EupYiPRhaMooHKUHJxNsTfYuScep13go8QFfHdtkG9nRkFGb7busX4isf6X9dURGCoKgitaApQ6MupRhZMcELAxTBRJgS/*)", + ); let addr = wallet.next_unused_address(KeychainKind::External); let fee_rate = FeeRate::from_sat_per_vb_unchecked(1); let mut builder = wallet.build_tx(); @@ -2683,7 +2709,9 @@ fn test_fee_rate_sign_grinding_low_r() { // by setting the `allow_grinding` signing option as true. // We then check that our fee rate and fee calculation is alright and that our // signature is 70 bytes. - let (mut wallet, _) = get_funded_wallet_single("wpkh(tprv8ZgxMBicQKsPd3EupYiPRhaMooHKUHJxNsTfYuScep13go8QFfHdtkG9nRkFGb7busX4isf6X9dURGCoKgitaApQ6MupRhZMcELAxTBRJgS/*)"); + let (mut wallet, _) = get_funded_wallet_single( + "wpkh(tprv8ZgxMBicQKsPd3EupYiPRhaMooHKUHJxNsTfYuScep13go8QFfHdtkG9nRkFGb7busX4isf6X9dURGCoKgitaApQ6MupRhZMcELAxTBRJgS/*)", + ); let addr = wallet.next_unused_address(KeychainKind::External); let fee_rate = FeeRate::from_sat_per_vb_unchecked(1); let mut builder = wallet.build_tx(); @@ -2865,17 +2893,21 @@ fn test_wallet_transactions_relevant() { .count(); assert_eq!(relevant_tx_count_before, relevant_tx_count_after); - assert!(!test_wallet - .transactions() - .any(|wallet_tx| wallet_tx.tx_node.txid == other_txid)); - assert!(test_wallet - .tx_graph() - .list_canonical_txs( - test_wallet.local_chain(), - chain_tip, - CanonicalizationParams::default() - ) - .any(|wallet_tx| wallet_tx.tx_node.txid == other_txid)); + assert!( + !test_wallet + .transactions() + .any(|wallet_tx| wallet_tx.tx_node.txid == other_txid) + ); + assert!( + test_wallet + .tx_graph() + .list_canonical_txs( + test_wallet.local_chain(), + chain_tip, + CanonicalizationParams::default() + ) + .any(|wallet_tx| wallet_tx.tx_node.txid == other_txid) + ); assert!(full_tx_count_before < full_tx_count_after); assert!(canonical_tx_count_before < canonical_tx_count_after); } diff --git a/tests/wallet_event.rs b/tests/wallet_event.rs index e19db201..f4b395e7 100644 --- a/tests/wallet_event.rs +++ b/tests/wallet_event.rs @@ -1,7 +1,7 @@ use bdk_chain::{BlockId, CheckPoint, ConfirmationBlockTime}; -use bdk_wallet::test_utils::{get_test_wpkh_and_change_desc, new_wallet_and_funding_update}; use bdk_wallet::Update; use bdk_wallet::WalletEvent; +use bdk_wallet::test_utils::{get_test_wpkh_and_change_desc, new_wallet_and_funding_update}; use bitcoin::block::Header; use bitcoin::hashes::Hash; use bitcoin::{Address, Amount, Block, BlockHash, FeeRate, Transaction, TxMerkleNode};