Skip to content

Commit 8215494

Browse files
committed
add electrum_backend example.
1 parent 06310f1 commit 8215494

File tree

3 files changed

+122
-0
lines changed

3 files changed

+122
-0
lines changed

Cargo.toml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,11 @@ name = "rpcwallet"
119119
path = "examples/rpcwallet.rs"
120120
required-features = ["keys-bip39", "key-value-db", "rpc", "electrsd/bitcoind_22_0"]
121121

122+
[[example]]
123+
name = "electrum_backend"
124+
path = "examples/electrum_backend.rs"
125+
required-features = ["electrum"]
126+
122127
[workspace]
123128
members = ["macros"]
124129
[package.metadata.docs.rs]

examples/electrum_backend.rs

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
use std::str::FromStr;
2+
3+
use bdk::bitcoin::util::bip32::ExtendedPrivKey;
4+
use bdk::bitcoin::Network;
5+
use bdk::blockchain::{Blockchain, ElectrumBlockchain};
6+
use bdk::database::MemoryDatabase;
7+
use bdk::template::Bip84;
8+
use bdk::wallet::export::FullyNodedExport;
9+
use bdk::{KeychainKind, SyncOptions, Wallet};
10+
11+
use bdk::electrum_client::Client;
12+
use bdk::wallet::AddressIndex;
13+
use bitcoin::util::bip32;
14+
15+
pub mod utils;
16+
17+
use crate::utils::tx::build_signed_tx;
18+
19+
/// This will create a wallet from an xpriv and get the balance by connecting to an Electrum server.
20+
/// If enough amount is available, this will send a transaction to an address.
21+
/// Otherwise, this will display a wallet address to receive funds.
22+
///
23+
/// This can be run with `cargo run --features=electrum --example electrum_backend` in the root folder.
24+
fn main() {
25+
let network = Network::Testnet;
26+
27+
let xpriv = "tprv8ZgxMBicQKsPcx5nBGsR63Pe8KnRUqmbJNENAfGftF3yuXoMMoVJJcYeUw5eVkm9WBPjWYt6HMWYJNesB5HaNVBaFc1M6dRjWSYnmewUMYy";
28+
29+
let electrum_url = "ssl://electrum.blockstream.info:60002";
30+
31+
run(&network, electrum_url, xpriv);
32+
}
33+
34+
fn create_wallet(network: &Network, xpriv: &ExtendedPrivKey) -> Wallet<MemoryDatabase> {
35+
Wallet::new(
36+
Bip84(*xpriv, KeychainKind::External),
37+
Some(Bip84(*xpriv, KeychainKind::Internal)),
38+
*network,
39+
MemoryDatabase::default(),
40+
)
41+
.unwrap()
42+
}
43+
44+
fn run(network: &Network, electrum_url: &str, xpriv: &str) {
45+
let xpriv = bip32::ExtendedPrivKey::from_str(xpriv).unwrap();
46+
47+
// Apparently it works only with Electrs (not EletrumX)
48+
let blockchain = ElectrumBlockchain::from(Client::new(electrum_url).unwrap());
49+
50+
let wallet = create_wallet(network, &xpriv);
51+
52+
wallet.sync(&blockchain, SyncOptions::default()).unwrap();
53+
54+
let address = wallet.get_address(AddressIndex::New).unwrap().address;
55+
56+
println!("address: {}", address);
57+
58+
let balance = wallet.get_balance().unwrap();
59+
60+
println!("Available coins in BDK wallet : {} sats", balance);
61+
62+
if balance.confirmed > 6500 {
63+
// the wallet sends the amount to itself.
64+
let recipient_address = wallet
65+
.get_address(AddressIndex::New)
66+
.unwrap()
67+
.address
68+
.to_string();
69+
70+
let amount = 5359;
71+
72+
let tx = build_signed_tx(&wallet, &recipient_address, amount);
73+
74+
blockchain.broadcast(&tx).unwrap();
75+
76+
println!("tx id: {}", tx.txid());
77+
} else {
78+
println!("Insufficient Funds. Fund the wallet with the address above");
79+
}
80+
81+
let export = FullyNodedExport::export_wallet(&wallet, "exported wallet", true)
82+
.map_err(ToString::to_string)
83+
.map_err(bdk::Error::Generic)
84+
.unwrap();
85+
86+
println!("------\nWallet Backup: {}", export.to_string());
87+
}

examples/utils/mod.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
pub(crate) mod tx {
2+
3+
use std::str::FromStr;
4+
5+
use bdk::{database::BatchDatabase, SignOptions, Wallet};
6+
use bitcoin::{Address, Transaction};
7+
8+
pub fn build_signed_tx<D: BatchDatabase>(
9+
wallet: &Wallet<D>,
10+
recipient_address: &str,
11+
amount: u64,
12+
) -> Transaction {
13+
// Create a transaction builder
14+
let mut tx_builder = wallet.build_tx();
15+
16+
let to_address = Address::from_str(recipient_address).unwrap();
17+
18+
// Set recipient of the transaction
19+
tx_builder.set_recipients(vec![(to_address.script_pubkey(), amount)]);
20+
21+
// Finalise the transaction and extract PSBT
22+
let (mut psbt, _) = tx_builder.finish().unwrap();
23+
24+
// Sign the above psbt with signing option
25+
wallet.sign(&mut psbt, SignOptions::default()).unwrap();
26+
27+
// Extract the final transaction
28+
psbt.extract_tx()
29+
}
30+
}

0 commit comments

Comments
 (0)