Skip to content

Commit 974f31f

Browse files
committed
example: Add keyring example
1 parent 3afb324 commit 974f31f

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

wallet/Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,3 +58,7 @@ required-features = ["all-keys"]
5858
name = "miniscriptc"
5959
path = "examples/compiler.rs"
6060
required-features = ["compiler"]
61+
62+
[[example]]
63+
name = "keyring"
64+
required-features = ["rusqlite"]

wallet/examples/keyring.rs

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
#![allow(unused)]
2+
#![allow(clippy::print_stdout)]
3+
4+
use bdk_chain::DescriptorExt;
5+
use bdk_chain::DescriptorId;
6+
use bitcoin::secp256k1::Secp256k1;
7+
use bitcoin::Network;
8+
use miniscript::{Descriptor, DescriptorPublicKey};
9+
10+
use bdk_wallet::chain as bdk_chain;
11+
use bdk_wallet::multi_keychain::{KeyRing, Wallet};
12+
use bdk_wallet::rusqlite;
13+
14+
// This example shows how to create a BDK wallet from a `KeyRing`.
15+
16+
fn main() -> anyhow::Result<()> {
17+
let path = ".bdk_example_keyring.sqlite";
18+
let mut conn = rusqlite::Connection::open(path)?;
19+
20+
let network = Network::Signet;
21+
22+
let desc = "wpkh([83737d5e/84'/1'/1']tpubDCzuCBKnZA5TNKhiJnASku7kq8Q4iqcVF82JV7mHo2NxWpXkLRbrJaGA5ToE7LCuWpcPErBbpDzbdWKN8aTdJzmRy1jQPmZvnqpwwDwCdy7/<0;1>/*)";
23+
let desc2 = "tr([83737d5e/86'/1'/1']tpubDDR5GgtoxS8fNuSTJU6huqQKGzWshPaemb3UwFDoAXCsyakcQoRcFDMiGUVRX43Lofd7ZB82RcUvu1xnZ5oGZhbr43dRkY8xm2KGhpcq93o/<0;1>/*)";
24+
25+
let default_did: DescriptorId =
26+
"6f3ba87443e825675b2b1cb8da505831422a7d214c515070570885180a1b2733".parse()?;
27+
28+
let mut wallet = match Wallet::from_sqlite(&mut conn)? {
29+
Some(w) => w,
30+
None => {
31+
let mut keyring = KeyRing::new(network);
32+
for multipath_desc in [desc, desc2] {
33+
for (did, desc) in label_descriptors(multipath_desc) {
34+
keyring.add_descriptor(did, desc);
35+
}
36+
}
37+
let mut wallet = Wallet::new(keyring);
38+
wallet.persist_to_sqlite(&mut conn)?;
39+
wallet
40+
}
41+
};
42+
43+
let (indexed, addr) = wallet.reveal_next_address(default_did).unwrap();
44+
println!("Address: {:?} {}", indexed, addr);
45+
46+
let changeset = wallet.persist_to_sqlite(&mut conn)?;
47+
println!("Change persisted: {}", changeset.is_some());
48+
49+
Ok(())
50+
}
51+
52+
/// Helper method to label descriptors by descriptor ID!
53+
fn label_descriptors(
54+
s: &str,
55+
) -> impl Iterator<Item = (DescriptorId, Descriptor<DescriptorPublicKey>)> {
56+
let desc = Descriptor::parse_descriptor(&Secp256k1::new(), s)
57+
.expect("failed to parse descriptor")
58+
.0;
59+
desc.into_single_descriptors()
60+
.expect("inavlid descriptor")
61+
.into_iter()
62+
.map(|desc| (desc.descriptor_id(), desc))
63+
}

0 commit comments

Comments
 (0)