Skip to content

Commit 112bb0c

Browse files
feat: add RPC wallet example
1 parent 8afe8d3 commit 112bb0c

File tree

3 files changed

+111
-2
lines changed

3 files changed

+111
-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: 95 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,96 @@
1-
fn main() {
2-
println!("Hello, world!");
1+
use bdk::{
2+
bitcoin::{Address, Network},
3+
wallet::{AddressIndex, 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+
if args.len() < 6 {
25+
println!("Usage: wallet_rpc <RPC_URL> <RPC_USER> <RPC_PASS> <LOOKAHEAD> <FALLBACK_HEIGHT>");
26+
std::process::exit(1);
27+
}
28+
29+
let mut wallet = Wallet::new(
30+
external_descriptor,
31+
Some(internal_descriptor),
32+
db,
33+
Network::Testnet,
34+
)?;
35+
36+
let address = wallet.get_address(AddressIndex::New);
37+
println!("Generated Address: {}", address);
38+
39+
let balance = wallet.get_balance();
40+
println!("Wallet balance before syncing: {} sats", balance.total());
41+
42+
let rpc_client = Client::new(&args[1], Auth::UserPass(args[2].clone(), args[3].clone()))?;
43+
44+
println!(
45+
"Connected to Bitcoin Core RPC at {:?}",
46+
rpc_client.get_blockchain_info().unwrap()
47+
);
48+
49+
wallet.set_lookahead_for_all(args[4].parse::<u32>()?)?;
50+
51+
let chain_tip = wallet.latest_checkpoint();
52+
let mut emitter = match chain_tip {
53+
Some(cp) => Emitter::from_checkpoint(&rpc_client, cp),
54+
None => Emitter::from_height(&rpc_client, args[5].parse::<u32>()?),
55+
};
56+
57+
while let Some((height, block)) = emitter.next_block()? {
58+
println!("Applying block {} at height {}", block.block_hash(), height);
59+
wallet.apply_block_relevant(block, height)?;
60+
wallet.commit()?;
61+
}
62+
63+
let unconfirmed_txs = emitter.mempool()?;
64+
println!("Applying unconfirmed transactions: ...");
65+
wallet.batch_insert_relevant_unconfirmed(unconfirmed_txs.iter().map(|(tx, time)| (tx, *time)));
66+
wallet.commit()?;
67+
68+
let balance = wallet.get_balance();
69+
println!("Wallet balance after syncing: {} sats", balance.total());
70+
71+
if balance.total() < SEND_AMOUNT {
72+
println!(
73+
"Please send at least {} sats to the receiving address",
74+
SEND_AMOUNT
75+
);
76+
std::process::exit(1);
77+
}
78+
79+
let faucet_address = Address::from_str("tb1qw2c3lxufxqe2x9s4rdzh65tpf4d7fssjgh8nv6")?
80+
.require_network(Network::Testnet)?;
81+
82+
let mut tx_builder = wallet.build_tx();
83+
tx_builder
84+
.add_recipient(faucet_address.script_pubkey(), SEND_AMOUNT)
85+
.enable_rbf();
86+
87+
let mut psbt = tx_builder.finish()?;
88+
let finalized = wallet.sign(&mut psbt, SignOptions::default())?;
89+
assert!(finalized);
90+
91+
let tx = psbt.extract_tx();
92+
rpc_client.send_raw_transaction(&tx)?;
93+
println!("Tx broadcasted! Txid: {}", tx.txid());
94+
95+
Ok(())
396
}

0 commit comments

Comments
 (0)