Skip to content

wip: Support N keychains #230

New issue

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

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

Already on GitHub? Sign in to your account

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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions examples/example_wallet_electrum/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use bdk_electrum::BdkElectrumClient;
use bdk_wallet::bitcoin::Amount;
use bdk_wallet::bitcoin::Network;
use bdk_wallet::chain::collections::HashSet;
use bdk_wallet::{KeychainKind, SignOptions};
use bdk_wallet::{Keychain, KeychainKind, SignOptions};

const DB_MAGIC: &str = "bdk_wallet_electrum_example";
const SEND_AMOUNT: Amount = Amount::from_sat(5000);
Expand Down Expand Up @@ -53,7 +53,7 @@ fn main() -> Result<(), anyhow::Error> {

let request = wallet.start_full_scan().inspect({
let mut stdout = std::io::stdout();
let mut once = HashSet::<KeychainKind>::new();
let mut once = HashSet::<Keychain>::new();
move |k, spk_i, _| {
if once.insert(k) {
print!("\nScanning keychain [{:?}]", k);
Expand Down
177 changes: 107 additions & 70 deletions examples/example_wallet_esplora_async/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,91 +1,128 @@
#![allow(unused)]
use std::{collections::BTreeSet, io::Write};

use anyhow::Ok;
use bdk_esplora::{esplora_client, EsploraAsyncExt};
use bdk_wallet::{
bitcoin::{Amount, Network},
chain::{DescriptorExt, DescriptorId},
rusqlite::Connection,
KeychainKind, SignOptions, Wallet,
ChangeSet, CreateParams, Keychain, Keyring, SignOptions, Wallet,
};

const SEND_AMOUNT: Amount = Amount::from_sat(5000);
const STOP_GAP: usize = 5;
const PARALLEL_REQUESTS: usize = 5;

const DB_PATH: &str = "bdk-example-esplora-async.sqlite";
// const DB_PATH: &str = "bdk-example-esplora-async.sqlite";
const DB_PATH: &str = ".bdk_example_wallet_esplora_async.sqlite";
const NETWORK: Network = Network::Signet;
const EXTERNAL_DESC: &str = "wpkh(tprv8ZgxMBicQKsPdy6LMhUtFHAgpocR8GC6QmwMSFpZs7h6Eziw3SpThFfczTDh5rW2krkqffa11UpX3XkeTTB2FvzZKWXqPY54Y6Rq4AQ5R8L/84'/1'/0'/0/*)";
const INTERNAL_DESC: &str = "wpkh(tprv8ZgxMBicQKsPdy6LMhUtFHAgpocR8GC6QmwMSFpZs7h6Eziw3SpThFfczTDh5rW2krkqffa11UpX3XkeTTB2FvzZKWXqPY54Y6Rq4AQ5R8L/84'/1'/0'/1/*)";
// const EXTERNAL_DESC: &str = "wpkh(tprv8ZgxMBicQKsPdy6LMhUtFHAgpocR8GC6QmwMSFpZs7h6Eziw3SpThFfczTDh5rW2krkqffa11UpX3XkeTTB2FvzZKWXqPY54Y6Rq4AQ5R8L/84'/1'/0'/0/*)";
// const INTERNAL_DESC: &str = "wpkh(tprv8ZgxMBicQKsPdy6LMhUtFHAgpocR8GC6QmwMSFpZs7h6Eziw3SpThFfczTDh5rW2krkqffa11UpX3XkeTTB2FvzZKWXqPY54Y6Rq4AQ5R8L/84'/1'/0'/1/*)";
const ESPLORA_URL: &str = "http://signet.bitcoindevkit.net";

const MULTIPATH_DESCRIPTOR: &str = "wpkh([e273fe42/84'/1'/0']tpubDCmr3Luq75npLaYmRqqW1rLfSbfpnBXwLwAmUbR333fp95wjCHar3zoc9zSWovZFwrWr53mm3NTVqt6d1Pt6G26uf4etQjc3Pr5Hxe9QEQ2/<0;1>/*)";
const PK_DESCRIPTOR: &str = "tr(b511bd5771e47ee27558b1765e87b541668304ec567721c7b880edc0a010da55)";
// Desc ID of pk descriptor: "ef8a67b77b83797a1ad56504cc79e8c6990408265f1afdce72990b8a5baf7d3b"

#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
let mut conn = Connection::open(DB_PATH)?;

let wallet_opt = Wallet::load()
.descriptor(KeychainKind::External, Some(EXTERNAL_DESC))
.descriptor(KeychainKind::Internal, Some(INTERNAL_DESC))
.extract_keys()
.check_network(NETWORK)
.load_wallet(&mut conn)?;
let mut wallet = match wallet_opt {
Some(wallet) => wallet,
None => Wallet::create(EXTERNAL_DESC, INTERNAL_DESC)
.network(NETWORK)
.create_wallet(&mut conn)?,
};

let address = wallet.next_unused_address(KeychainKind::External);
wallet.persist(&mut conn)?;
println!("Next unused address: ({}) {}", address.index, address);

let balance = wallet.balance();
println!("Wallet balance before syncing: {}", balance.total());

print!("Syncing...");
let client = esplora_client::Builder::new(ESPLORA_URL).build_async()?;

let request = wallet.start_full_scan().inspect({
let mut stdout = std::io::stdout();
let mut once = BTreeSet::<KeychainKind>::new();
move |keychain, spk_i, _| {
if once.insert(keychain) {
print!("\nScanning keychain [{:?}]", keychain);
}
print!(" {:<3}", spk_i);
stdout.flush().expect("must flush")
}
});

let update = client
.full_scan(request, STOP_GAP, PARALLEL_REQUESTS)
.await?;

wallet.apply_update(update)?;
wallet.persist(&mut conn)?;
println!();

let balance = wallet.balance();
println!("Wallet balance after syncing: {}", balance.total());

if balance.total() < SEND_AMOUNT {
println!(
"Please send at least {} to the receiving address",
SEND_AMOUNT
);
std::process::exit(0);
}

let mut tx_builder = wallet.build_tx();
tx_builder.add_recipient(address.script_pubkey(), SEND_AMOUNT);

let mut psbt = tx_builder.finish()?;
let finalized = wallet.sign(&mut psbt, SignOptions::default())?;
assert!(finalized);

let tx = psbt.extract_tx()?;
client.broadcast(&tx).await?;
println!("Tx broadcasted! Txid: {}", tx.compute_txid());
// let mut conn = Connection::open(DB_PATH)?;
let mut conn = Connection::open_in_memory()?;

// Setup: Initialize Keyring from a list of descriptors
let mut keyring = Keyring::new(NETWORK);
let _ = keyring.add_descriptors([MULTIPATH_DESCRIPTOR, PK_DESCRIPTOR])?;

// Test 1: Create wallet with keyring and params
let mut wallet = Wallet::with_keyring(keyring.clone())
.network(NETWORK)
.create_wallet(&mut conn)?;

assert_eq!(wallet.keychains().count(), 3);
let desc_id: DescriptorId =
"ef8a67b77b83797a1ad56504cc79e8c6990408265f1afdce72990b8a5baf7d3b".parse()?;
let (keychain, index, addr) = wallet.new_address(desc_id).expect("should reveal address");
println!("New address: {:?} {}", (keychain, index), addr);

// Test 2: Persist the keyring first and then load wallet from changeset
// let changeset = keyring.initial_changeset();
// let tx = conn.transaction()?;
// ChangeSet::init_sqlite_tables(&tx)?;
// changeset.persist_to_sqlite(&tx)?;
// tx.commit()?;

// let wallet = Wallet::load()
// .load_wallet(&mut conn)?
// .expect("should have persisted wallet");

// assert_eq!(wallet.keychains().count(), 3);

// More example code

// let wallet_opt = Wallet::load()
// .descriptor(0, Some(EXTERNAL_DESC))
// .extract_keys()
// .check_network(NETWORK)
// .load_wallet(&mut conn)?;
// let mut wallet = match wallet_opt {
// Some(wallet) => wallet,
// None => Wallet::create(EXTERNAL_DESC, INTERNAL_DESC)
// .network(NETWORK)
// .create_wallet(&mut conn)?,
// };

// let address = wallet.next_unused_address(Keychain::ZERO);
// wallet.persist(&mut conn)?;
// println!("Next unused address: ({}) {}", address.index, address);

// let balance = wallet.balance();
// println!("Wallet balance before syncing: {}", balance.total());

// print!("Syncing...");
// let client = esplora_client::Builder::new(ESPLORA_URL).build_async()?;

// let request = wallet.start_full_scan().inspect({
// let mut stdout = std::io::stdout();
// let mut once = BTreeSet::<Keychain>::new();
// move |keychain, spk_i, _| {
// if once.insert(keychain) {
// print!("\nScanning keychain [{:?}]", keychain);
// }
// print!(" {:<3}", spk_i);
// stdout.flush().expect("must flush")
// }
// });

// let update = client
// .full_scan(request, STOP_GAP, PARALLEL_REQUESTS)
// .await?;

// wallet.apply_update(update)?;
// wallet.persist(&mut conn)?;
// println!();

// let balance = wallet.balance();
// println!("Wallet balance after syncing: {}", balance.total());

// if balance.total() < SEND_AMOUNT {
// println!(
// "Please send at least {} to the receiving address",
// SEND_AMOUNT
// );
// std::process::exit(0);
// }

// let mut tx_builder = wallet.build_tx();
// tx_builder.add_recipient(address.script_pubkey(), SEND_AMOUNT);

// let mut psbt = tx_builder.finish()?;
// let finalized = wallet.sign(&mut psbt, SignOptions::default())?;
// assert!(finalized);

// let tx = psbt.extract_tx()?;
// client.broadcast(&tx).await?;
// println!("Tx broadcasted! Txid: {}", tx.compute_txid());

Ok(())
}
4 changes: 2 additions & 2 deletions examples/example_wallet_esplora_blocking/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use bdk_esplora::{esplora_client, EsploraExt};
use bdk_wallet::{
bitcoin::{Amount, Network},
file_store::Store,
KeychainKind, SignOptions, Wallet,
Keychain, KeychainKind, SignOptions, Wallet,
};

const DB_MAGIC: &str = "bdk_wallet_esplora_example";
Expand Down Expand Up @@ -49,7 +49,7 @@ fn main() -> Result<(), anyhow::Error> {

let request = wallet.start_full_scan().inspect({
let mut stdout = std::io::stdout();
let mut once = BTreeSet::<KeychainKind>::new();
let mut once = BTreeSet::<Keychain>::new();
move |keychain, spk_i, _| {
if once.insert(keychain) {
print!("\nScanning keychain [{:?}] ", keychain);
Expand Down
16 changes: 8 additions & 8 deletions wallet/src/descriptor/template.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ impl<K: IntoDescriptorKey<Tap>> DescriptorTemplate for P2TR<K> {
/// .create_wallet_no_persist()?;
///
/// assert_eq!(wallet.next_unused_address(KeychainKind::External).to_string(), "mmogjc7HJEZkrLqyQYqJmxUqFaC7i4uf89");
/// assert_eq!(wallet.public_descriptor(KeychainKind::External).to_string(), "pkh([c55b303f/44'/1'/0']tpubDCuorCpzvYS2LCD75BR46KHE8GdDeg1wsAgNZeNr6DaB5gQK1o14uErKwKLuFmeemkQ6N2m3rNgvctdJLyr7nwu2yia7413Hhg8WWE44cgT/0/*)#5wrnv0xt");
/// assert_eq!(wallet.public_descriptor(KeychainKind::External.into()).to_string(), "pkh([c55b303f/44'/1'/0']tpubDCuorCpzvYS2LCD75BR46KHE8GdDeg1wsAgNZeNr6DaB5gQK1o14uErKwKLuFmeemkQ6N2m3rNgvctdJLyr7nwu2yia7413Hhg8WWE44cgT/0/*)#5wrnv0xt");
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone)]
Expand Down Expand Up @@ -267,7 +267,7 @@ impl<K: DerivableKey<Legacy>> DescriptorTemplate for Bip44<K> {
/// .create_wallet_no_persist()?;
///
/// assert_eq!(wallet.next_unused_address(KeychainKind::External).to_string(), "miNG7dJTzJqNbFS19svRdTCisC65dsubtR");
/// assert_eq!(wallet.public_descriptor(KeychainKind::External).to_string(), "pkh([c55b303f/44'/1'/0']tpubDDDzQ31JkZB7VxUr9bjvBivDdqoFLrDPyLWtLapArAi51ftfmCb2DPxwLQzX65iNcXz1DGaVvyvo6JQ6rTU73r2gqdEo8uov9QKRb7nKCSU/0/*)#cfhumdqz");
/// assert_eq!(wallet.public_descriptor(KeychainKind::External.into()).to_string(), "pkh([c55b303f/44'/1'/0']tpubDDDzQ31JkZB7VxUr9bjvBivDdqoFLrDPyLWtLapArAi51ftfmCb2DPxwLQzX65iNcXz1DGaVvyvo6JQ6rTU73r2gqdEo8uov9QKRb7nKCSU/0/*)#cfhumdqz");
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone)]
Expand Down Expand Up @@ -305,7 +305,7 @@ impl<K: DerivableKey<Legacy>> DescriptorTemplate for Bip44Public<K> {
/// .create_wallet_no_persist()?;
///
/// assert_eq!(wallet.next_unused_address(KeychainKind::External).to_string(), "2N4zkWAoGdUv4NXhSsU8DvS5MB36T8nKHEB");
/// assert_eq!(wallet.public_descriptor(KeychainKind::External).to_string(), "sh(wpkh([c55b303f/49'/1'/0']tpubDDYr4kdnZgjjShzYNjZUZXUUtpXaofdkMaipyS8ThEh45qFmhT4hKYways7UXmg6V7het1QiFo9kf4kYUXyDvV4rHEyvSpys9pjCB3pukxi/0/*))#s9vxlc8e");
/// assert_eq!(wallet.public_descriptor(KeychainKind::External.into()).to_string(), "sh(wpkh([c55b303f/49'/1'/0']tpubDDYr4kdnZgjjShzYNjZUZXUUtpXaofdkMaipyS8ThEh45qFmhT4hKYways7UXmg6V7het1QiFo9kf4kYUXyDvV4rHEyvSpys9pjCB3pukxi/0/*))#s9vxlc8e");
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone)]
Expand Down Expand Up @@ -344,7 +344,7 @@ impl<K: DerivableKey<Segwitv0>> DescriptorTemplate for Bip49<K> {
/// .create_wallet_no_persist()?;
///
/// assert_eq!(wallet.next_unused_address(KeychainKind::External).to_string(), "2N3K4xbVAHoiTQSwxkZjWDfKoNC27pLkYnt");
/// assert_eq!(wallet.public_descriptor(KeychainKind::External).to_string(), "sh(wpkh([c55b303f/49'/1'/0']tpubDC49r947KGK52X5rBWS4BLs5m9SRY3pYHnvRrm7HcybZ3BfdEsGFyzCMzayi1u58eT82ZeyFZwH7DD6Q83E3fM9CpfMtmnTygnLfP59jL9L/0/*))#3tka9g0q");
/// assert_eq!(wallet.public_descriptor(KeychainKind::External.into()).to_string(), "sh(wpkh([c55b303f/49'/1'/0']tpubDC49r947KGK52X5rBWS4BLs5m9SRY3pYHnvRrm7HcybZ3BfdEsGFyzCMzayi1u58eT82ZeyFZwH7DD6Q83E3fM9CpfMtmnTygnLfP59jL9L/0/*))#3tka9g0q");
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone)]
Expand Down Expand Up @@ -382,7 +382,7 @@ impl<K: DerivableKey<Segwitv0>> DescriptorTemplate for Bip49Public<K> {
/// .create_wallet_no_persist()?;
///
/// assert_eq!(wallet.next_unused_address(KeychainKind::External).to_string(), "tb1qhl85z42h7r4su5u37rvvw0gk8j2t3n9y7zsg4n");
/// assert_eq!(wallet.public_descriptor(KeychainKind::External).to_string(), "wpkh([c55b303f/84'/1'/0']tpubDDc5mum24DekpNw92t6fHGp8Gr2JjF9J7i4TZBtN6Vp8xpAULG5CFaKsfugWa5imhrQQUZKXe261asP5koDHo5bs3qNTmf3U3o4v9SaB8gg/0/*)#6kfecsmr");
/// assert_eq!(wallet.public_descriptor(KeychainKind::External.into()).to_string(), "wpkh([c55b303f/84'/1'/0']tpubDDc5mum24DekpNw92t6fHGp8Gr2JjF9J7i4TZBtN6Vp8xpAULG5CFaKsfugWa5imhrQQUZKXe261asP5koDHo5bs3qNTmf3U3o4v9SaB8gg/0/*)#6kfecsmr");
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone)]
Expand Down Expand Up @@ -421,7 +421,7 @@ impl<K: DerivableKey<Segwitv0>> DescriptorTemplate for Bip84<K> {
/// .create_wallet_no_persist()?;
///
/// assert_eq!(wallet.next_unused_address(KeychainKind::External).to_string(), "tb1qedg9fdlf8cnnqfd5mks6uz5w4kgpk2pr6y4qc7");
/// assert_eq!(wallet.public_descriptor(KeychainKind::External).to_string(), "wpkh([c55b303f/84'/1'/0']tpubDC2Qwo2TFsaNC4ju8nrUJ9mqVT3eSgdmy1yPqhgkjwmke3PRXutNGRYAUo6RCHTcVQaDR3ohNU9we59brGHuEKPvH1ags2nevW5opEE9Z5Q/0/*)#dhu402yv");
/// assert_eq!(wallet.public_descriptor(KeychainKind::External.into()).to_string(), "wpkh([c55b303f/84'/1'/0']tpubDC2Qwo2TFsaNC4ju8nrUJ9mqVT3eSgdmy1yPqhgkjwmke3PRXutNGRYAUo6RCHTcVQaDR3ohNU9we59brGHuEKPvH1ags2nevW5opEE9Z5Q/0/*)#dhu402yv");
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone)]
Expand Down Expand Up @@ -459,7 +459,7 @@ impl<K: DerivableKey<Segwitv0>> DescriptorTemplate for Bip84Public<K> {
/// .create_wallet_no_persist()?;
///
/// assert_eq!(wallet.next_unused_address(KeychainKind::External).to_string(), "tb1p5unlj09djx8xsjwe97269kqtxqpwpu2epeskgqjfk4lnf69v4tnqpp35qu");
/// assert_eq!(wallet.public_descriptor(KeychainKind::External).to_string(), "tr([c55b303f/86'/1'/0']tpubDCiHofpEs47kx358bPdJmTZHmCDqQ8qw32upCSxHrSEdeeBs2T5Mq6QMB2ukeMqhNBiyhosBvJErteVhfURPGXPv3qLJPw5MVpHUewsbP2m/0/*)#dkgvr5hm");
/// assert_eq!(wallet.public_descriptor(KeychainKind::External.into()).to_string(), "tr([c55b303f/86'/1'/0']tpubDCiHofpEs47kx358bPdJmTZHmCDqQ8qw32upCSxHrSEdeeBs2T5Mq6QMB2ukeMqhNBiyhosBvJErteVhfURPGXPv3qLJPw5MVpHUewsbP2m/0/*)#dkgvr5hm");
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone)]
Expand Down Expand Up @@ -498,7 +498,7 @@ impl<K: DerivableKey<Tap>> DescriptorTemplate for Bip86<K> {
/// .create_wallet_no_persist()?;
///
/// assert_eq!(wallet.next_unused_address(KeychainKind::External).to_string(), "tb1pwjp9f2k5n0xq73ecuu0c5njvgqr3vkh7yaylmpqvsuuaafymh0msvcmh37");
/// assert_eq!(wallet.public_descriptor(KeychainKind::External).to_string(), "tr([c55b303f/86'/1'/0']tpubDC2Qwo2TFsaNC4ju8nrUJ9mqVT3eSgdmy1yPqhgkjwmke3PRXutNGRYAUo6RCHTcVQaDR3ohNU9we59brGHuEKPvH1ags2nevW5opEE9Z5Q/0/*)#2p65srku");
/// assert_eq!(wallet.public_descriptor(KeychainKind::External.into()).to_string(), "tr([c55b303f/86'/1'/0']tpubDC2Qwo2TFsaNC4ju8nrUJ9mqVT3eSgdmy1yPqhgkjwmke3PRXutNGRYAUo6RCHTcVQaDR3ohNU9we59brGHuEKPvH1ags2nevW5opEE9Z5Q/0/*)#2p65srku");
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone)]
Expand Down
2 changes: 2 additions & 0 deletions wallet/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ pub use tx_builder::*;
pub use types::*;
pub use wallet::*;

pub(crate) use bdk_chain::keychain_txout::DEFAULT_LOOKAHEAD;

/// Get the version of [`bdk_wallet`](crate) at runtime.
pub fn version() -> &'static str {
env!("CARGO_PKG_VERSION", "unknown")
Expand Down
13 changes: 13 additions & 0 deletions wallet/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,19 @@ impl AsRef<[u8]> for KeychainKind {
}
}

use crate::Keychain;

impl KeychainKind {
/// From keychain.
pub(crate) fn from_keychain(keychain: Keychain) -> Option<Self> {
match keychain {
Keychain::ZERO => Some(KeychainKind::External),
Keychain::ONE => Some(KeychainKind::Internal),
_ => None,
}
}
}

/// An unspent output owned by a [`Wallet`].
///
/// [`Wallet`]: crate::Wallet
Expand Down
Loading