Skip to content

Commit e81670e

Browse files
feat: add RPC wallet example
1 parent 0a2efa6 commit e81670e

File tree

3 files changed

+106
-2
lines changed

3 files changed

+106
-2
lines changed

example-crates/wallet_rpc/Cargo.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,6 @@ edition = "2021"
66
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
77

88
[dependencies]
9+
bdk = { path = "../../crates/bdk" }
10+
bdk_file_store = { path = "../../crates/file_store" }
11+
bdk_bitcoind_rpc = { path = "../../crates/bitcoind_rpc" }
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# Wallet RPC Example
2+
3+
# To run the wallet example, execute the following code (replace arguments with values that match your setup)
4+
5+
```
6+
cargo run -- <RPC_URL> <RPC_USER> <RPC_PASS> <LOOKAHEAD> <FALLBACK_HEIGHT>
7+
```
8+
9+
Here is the command we used during testing
10+
11+
```
12+
cargo run -- 127.0.0.1:18332 bitcoin password 20 2532323
13+
```
Lines changed: 90 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,91 @@
1-
fn main() {
2-
println!("Hello, world!");
1+
use bdk::{
2+
bitcoin::{Address, Network},
3+
wallet::{AddressIndex, ChangeSet, Wallet},
4+
SignOptions,
5+
};
6+
use bdk_bitcoind_rpc::{
7+
bitcoincore_rpc::{Auth, Client, RpcApi},
8+
Emitter,
9+
};
10+
use bdk_file_store::Store;
11+
use std::str::FromStr;
12+
13+
const DB_MAGIC: &str = "bdk-rpc-wallet-example";
14+
const SEND_AMOUNT: u64 = 5000;
15+
16+
fn main() -> Result<(), Box<dyn std::error::Error>> {
17+
let args = std::env::args().collect::<Vec<_>>();
18+
let db_path = std::env::temp_dir().join("bdk-rpc-example");
19+
let db = Store::<bdk::wallet::ChangeSet>::new_from_path(DB_MAGIC.as_bytes(), db_path)?;
20+
21+
let external_descriptor = "wpkh(tprv8ZgxMBicQKsPdy6LMhUtFHAgpocR8GC6QmwMSFpZs7h6Eziw3SpThFfczTDh5rW2krkqffa11UpX3XkeTTB2FvzZKWXqPY54Y6Rq4AQ5R8L/84'/1'/0'/0/*)";
22+
let internal_descriptor = "wpkh(tprv8ZgxMBicQKsPdy6LMhUtFHAgpocR8GC6QmwMSFpZs7h6Eziw3SpThFfczTDh5rW2krkqffa11UpX3XkeTTB2FvzZKWXqPY54Y6Rq4AQ5R8L/84'/1'/0'/1/*)";
23+
24+
let mut wallet = Wallet::new(
25+
external_descriptor,
26+
Some(internal_descriptor),
27+
db,
28+
Network::Testnet,
29+
)?;
30+
31+
let address = wallet.get_address(AddressIndex::New);
32+
println!("Generated Address: {}", address);
33+
34+
let balance = wallet.get_balance();
35+
println!("Wallet balance before syncing: {} sats", balance.total());
36+
37+
let rpc_client = Client::new(&args[0], Auth::UserPass(args[1].clone(), args[2].clone()))?;
38+
39+
println!(
40+
"Connected to Bitcoin Core RPC at {:?}",
41+
rpc_client.get_blockchain_info().unwrap()
42+
);
43+
44+
wallet.set_lookahead_for_all(args[3].parse::<u32>()?);
45+
46+
let chain_tip = wallet.latest_checkpoint();
47+
let mut emitter = match chain_tip {
48+
Some(cp) => Emitter::from_checkpoint(&rpc_client, cp),
49+
None => Emitter::from_height(&rpc_client, args[4].parse::<u32>()?),
50+
};
51+
52+
while let Some((height, block)) = emitter.next_block()? {
53+
println!("Applying block {} at height {}", block.block_hash(), height);
54+
wallet.apply_block_relevant(block, height)?;
55+
wallet.commit()?;
56+
}
57+
58+
let unconfirmed_txs = emitter.mempool()?;
59+
println!("Applying unconfirmed transactions: ...");
60+
wallet.batch_insert_relevant_unconfirmed(unconfirmed_txs.iter().map(|(tx, time)| (tx, *time)));
61+
wallet.commit()?;
62+
63+
let balance = wallet.get_balance();
64+
println!("Wallet balance after syncing: {} sats", balance.total());
65+
66+
if balance.total() < SEND_AMOUNT {
67+
println!(
68+
"Please send at least {} sats to the receiving address",
69+
SEND_AMOUNT
70+
);
71+
std::process::exit(0);
72+
}
73+
74+
let faucet_address = Address::from_str("tb1qw2c3lxufxqe2x9s4rdzh65tpf4d7fssjgh8nv6")?
75+
.require_network(Network::Testnet)?;
76+
77+
let mut tx_builder = wallet.build_tx();
78+
tx_builder
79+
.add_recipient(faucet_address.script_pubkey(), SEND_AMOUNT)
80+
.enable_rbf();
81+
82+
let mut psbt = tx_builder.finish()?;
83+
let finalized = wallet.sign(&mut psbt, SignOptions::default())?;
84+
assert!(finalized);
85+
86+
let tx = psbt.extract_tx();
87+
rpc_client.send_raw_transaction(&tx)?;
88+
println!("Tx broadcasted! Txid: {}", tx.txid());
89+
90+
Ok(())
391
}

0 commit comments

Comments
 (0)