|
| 1 | +use bdk::{ |
| 2 | + bitcoin::{Block, Network, Transaction}, |
| 3 | + wallet::Wallet, |
| 4 | +}; |
| 5 | +use bdk_bitcoind_rpc::{ |
| 6 | + bitcoincore_rpc::{Auth, Client, RpcApi}, |
| 7 | + Emitter, |
| 8 | +}; |
| 9 | +use bdk_file_store::Store; |
| 10 | +use clap::{self, Parser}; |
| 11 | +use std::{path::PathBuf, sync::mpsc::sync_channel, thread::spawn, time::Instant}; |
| 12 | + |
| 13 | +const DB_MAGIC: &str = "bdk-rpc-wallet-example"; |
| 14 | + |
| 15 | +/// Bitcoind RPC example usign `bdk::Wallet`. |
| 16 | +/// |
| 17 | +/// This syncs the chain block-by-block and prints the current balance, transaction count and UTXO |
| 18 | +/// count. |
| 19 | +#[derive(Parser, Debug)] |
| 20 | +#[clap(author, version, about, long_about = None)] |
| 21 | +#[clap(propagate_version = true)] |
| 22 | +pub struct Args { |
| 23 | + /// Wallet descriptor |
| 24 | + #[clap(env = "DESCRIPTOR")] |
| 25 | + pub descriptor: String, |
| 26 | + /// Wallet change descriptor |
| 27 | + #[clap(env = "CHANGE_DESCRIPTOR")] |
| 28 | + pub change_descriptor: Option<String>, |
| 29 | + /// Earliest block height to start sync from |
| 30 | + #[clap(env = "START_HEIGHT", long, default_value = "481824")] |
| 31 | + pub start_height: u32, |
| 32 | + /// Bitcoin network to connect to |
| 33 | + #[clap(env = "BITCOIN_NETWORK", long, default_value = "testnet")] |
| 34 | + pub network: Network, |
| 35 | + /// Where to store wallet data |
| 36 | + #[clap( |
| 37 | + env = "BDK_DB_PATH", |
| 38 | + long, |
| 39 | + default_value = ".bdk_wallet_rpc_example.db" |
| 40 | + )] |
| 41 | + pub db_path: PathBuf, |
| 42 | + |
| 43 | + /// RPC URL |
| 44 | + #[clap(env = "RPC_URL", long, default_value = "127.0.0.1:8332")] |
| 45 | + pub url: String, |
| 46 | + /// RPC auth cookie file |
| 47 | + #[clap(env = "RPC_COOKIE", long)] |
| 48 | + pub rpc_cookie: Option<PathBuf>, |
| 49 | + /// RPC auth username |
| 50 | + #[clap(env = "RPC_USER", long)] |
| 51 | + pub rpc_user: Option<String>, |
| 52 | + /// RPC auth password |
| 53 | + #[clap(env = "RPC_PASS", long)] |
| 54 | + pub rpc_pass: Option<String>, |
| 55 | +} |
| 56 | + |
| 57 | +impl Args { |
| 58 | + fn client(&self) -> anyhow::Result<Client> { |
| 59 | + Ok(Client::new( |
| 60 | + &self.url, |
| 61 | + match (&self.rpc_cookie, &self.rpc_user, &self.rpc_pass) { |
| 62 | + (None, None, None) => Auth::None, |
| 63 | + (Some(path), _, _) => Auth::CookieFile(path.clone()), |
| 64 | + (_, Some(user), Some(pass)) => Auth::UserPass(user.clone(), pass.clone()), |
| 65 | + (_, Some(_), None) => panic!("rpc auth: missing rpc_pass"), |
| 66 | + (_, None, Some(_)) => panic!("rpc auth: missing rpc_user"), |
| 67 | + }, |
| 68 | + )?) |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +#[derive(Debug)] |
| 73 | +enum Emission { |
| 74 | + SigTerm, |
| 75 | + Block(bdk_bitcoind_rpc::BlockEvent<Block>), |
| 76 | + Mempool(Vec<(Transaction, u64)>), |
| 77 | +} |
| 78 | + |
| 79 | +fn main() -> anyhow::Result<()> { |
| 80 | + let args = Args::parse(); |
| 81 | + |
| 82 | + let rpc_client = args.client()?; |
| 83 | + println!( |
| 84 | + "Connected to Bitcoin Core RPC at {:?}", |
| 85 | + rpc_client.get_blockchain_info().unwrap() |
| 86 | + ); |
| 87 | + |
| 88 | + let start_load_wallet = Instant::now(); |
| 89 | + let mut wallet = Wallet::new_or_load( |
| 90 | + &args.descriptor, |
| 91 | + args.change_descriptor.as_ref(), |
| 92 | + Store::<bdk::wallet::ChangeSet>::open_or_create_new(DB_MAGIC.as_bytes(), args.db_path)?, |
| 93 | + args.network, |
| 94 | + )?; |
| 95 | + println!( |
| 96 | + "Loaded wallet in {}s", |
| 97 | + start_load_wallet.elapsed().as_secs_f32() |
| 98 | + ); |
| 99 | + |
| 100 | + let balance = wallet.get_balance(); |
| 101 | + println!("Wallet balance before syncing: {} sats", balance.total()); |
| 102 | + |
| 103 | + let wallet_tip = wallet.latest_checkpoint(); |
| 104 | + println!( |
| 105 | + "Wallet tip: {} at height {}", |
| 106 | + wallet_tip.hash(), |
| 107 | + wallet_tip.height() |
| 108 | + ); |
| 109 | + |
| 110 | + let (sender, receiver) = sync_channel::<Emission>(21); |
| 111 | + |
| 112 | + let signal_sender = sender.clone(); |
| 113 | + ctrlc::set_handler(move || { |
| 114 | + signal_sender |
| 115 | + .send(Emission::SigTerm) |
| 116 | + .expect("failed to send sigterm") |
| 117 | + }); |
| 118 | + |
| 119 | + let emitter_tip = wallet_tip.clone(); |
| 120 | + spawn(move || -> Result<(), anyhow::Error> { |
| 121 | + let mut emitter = Emitter::new(&rpc_client, emitter_tip, args.start_height); |
| 122 | + while let Some(emission) = emitter.next_block()? { |
| 123 | + sender.send(Emission::Block(emission))?; |
| 124 | + } |
| 125 | + sender.send(Emission::Mempool(emitter.mempool()?))?; |
| 126 | + Ok(()) |
| 127 | + }); |
| 128 | + |
| 129 | + let mut blocks_received = 0_usize; |
| 130 | + for emission in receiver { |
| 131 | + match emission { |
| 132 | + Emission::SigTerm => { |
| 133 | + println!("Sigterm received, exiting..."); |
| 134 | + break; |
| 135 | + } |
| 136 | + Emission::Block(block_emission) => { |
| 137 | + blocks_received += 1; |
| 138 | + let height = block_emission.block_height(); |
| 139 | + let hash = block_emission.block_hash(); |
| 140 | + let connected_to = block_emission.connected_to(); |
| 141 | + let start_apply_block = Instant::now(); |
| 142 | + wallet.apply_block_connected_to(&block_emission.block, height, connected_to)?; |
| 143 | + wallet.commit()?; |
| 144 | + let elapsed = start_apply_block.elapsed().as_secs_f32(); |
| 145 | + println!( |
| 146 | + "Applied block {} at height {} in {}s", |
| 147 | + hash, height, elapsed |
| 148 | + ); |
| 149 | + } |
| 150 | + Emission::Mempool(mempool_emission) => { |
| 151 | + let start_apply_mempool = Instant::now(); |
| 152 | + wallet.apply_unconfirmed_txs(mempool_emission.iter().map(|(tx, time)| (tx, *time))); |
| 153 | + wallet.commit()?; |
| 154 | + println!( |
| 155 | + "Applied unconfirmed transactions in {}s", |
| 156 | + start_apply_mempool.elapsed().as_secs_f32() |
| 157 | + ); |
| 158 | + break; |
| 159 | + } |
| 160 | + } |
| 161 | + } |
| 162 | + let wallet_tip_end = wallet.latest_checkpoint(); |
| 163 | + let balance = wallet.get_balance(); |
| 164 | + println!( |
| 165 | + "Synced {} blocks in {}s", |
| 166 | + blocks_received, |
| 167 | + start_load_wallet.elapsed().as_secs_f32(), |
| 168 | + ); |
| 169 | + println!( |
| 170 | + "Wallet tip is '{}:{}'", |
| 171 | + wallet_tip_end.height(), |
| 172 | + wallet_tip_end.hash() |
| 173 | + ); |
| 174 | + println!("Wallet balance is {} sats", balance.total()); |
| 175 | + println!( |
| 176 | + "Wallet has {} transactions and {} utxos", |
| 177 | + wallet.transactions().count(), |
| 178 | + wallet.list_unspent().count() |
| 179 | + ); |
| 180 | + |
| 181 | + Ok(()) |
| 182 | +} |
0 commit comments