2 BlockchainInfo, FeeResponse, FundedTx, ListUnspentResponse, MempoolMinFeeResponse, NewAddress,
5 use crate::disk::FilesystemLogger;
8 use bitcoin::blockdata::constants::WITNESS_SCALE_FACTOR;
9 use bitcoin::blockdata::transaction::Transaction;
10 use bitcoin::consensus::{encode, Decodable, Encodable};
11 use bitcoin::hash_types::{BlockHash, Txid};
12 use bitcoin::hashes::Hash;
13 use bitcoin::util::address::{Address, Payload, WitnessVersion};
14 use bitcoin::{OutPoint, Script, TxOut, WPubkeyHash, XOnlyPublicKey};
15 use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
16 use lightning::events::bump_transaction::{Utxo, WalletSource};
17 use lightning::log_error;
18 use lightning::util::logger::Logger;
19 use lightning_block_sync::http::HttpEndpoint;
20 use lightning_block_sync::rpc::RpcClient;
21 use lightning_block_sync::{AsyncBlockSourceResult, BlockData, BlockHeaderData, BlockSource};
23 use std::collections::HashMap;
24 use std::str::FromStr;
25 use std::sync::atomic::{AtomicU32, Ordering};
27 use std::time::Duration;
29 pub struct BitcoindClient {
30 pub(crate) bitcoind_rpc_client: Arc<RpcClient>,
35 fees: Arc<HashMap<ConfirmationTarget, AtomicU32>>,
36 handle: tokio::runtime::Handle,
37 logger: Arc<FilesystemLogger>,
40 impl BlockSource for BitcoindClient {
42 &'a self, header_hash: &'a BlockHash, height_hint: Option<u32>,
43 ) -> AsyncBlockSourceResult<'a, BlockHeaderData> {
44 Box::pin(async move { self.bitcoind_rpc_client.get_header(header_hash, height_hint).await })
48 &'a self, header_hash: &'a BlockHash,
49 ) -> AsyncBlockSourceResult<'a, BlockData> {
50 Box::pin(async move { self.bitcoind_rpc_client.get_block(header_hash).await })
53 fn get_best_block<'a>(&'a self) -> AsyncBlockSourceResult<(BlockHash, Option<u32>)> {
54 Box::pin(async move { self.bitcoind_rpc_client.get_best_block().await })
58 /// The minimum feerate we are allowed to send, as specify by LDK.
59 const MIN_FEERATE: u32 = 253;
62 pub(crate) async fn new(
63 host: String, port: u16, rpc_user: String, rpc_password: String,
64 handle: tokio::runtime::Handle, logger: Arc<FilesystemLogger>,
65 ) -> std::io::Result<Self> {
66 let http_endpoint = HttpEndpoint::for_host(host.clone()).with_port(port);
68 base64::encode(format!("{}:{}", rpc_user.clone(), rpc_password.clone()));
69 let bitcoind_rpc_client = RpcClient::new(&rpc_credentials, http_endpoint)?;
70 let _dummy = bitcoind_rpc_client
71 .call_method::<BlockchainInfo>("getblockchaininfo", &vec![])
74 std::io::Error::new(std::io::ErrorKind::PermissionDenied,
75 "Failed to make initial call to bitcoind - please check your RPC user/password and access settings")
77 let mut fees: HashMap<ConfirmationTarget, AtomicU32> = HashMap::new();
78 fees.insert(ConfirmationTarget::MempoolMinimum, AtomicU32::new(MIN_FEERATE));
79 fees.insert(ConfirmationTarget::Background, AtomicU32::new(MIN_FEERATE));
80 fees.insert(ConfirmationTarget::Normal, AtomicU32::new(2000));
81 fees.insert(ConfirmationTarget::HighPriority, AtomicU32::new(5000));
83 bitcoind_rpc_client: Arc::new(bitcoind_rpc_client),
89 handle: handle.clone(),
92 BitcoindClient::poll_for_fee_estimates(
94 client.bitcoind_rpc_client.clone(),
100 fn poll_for_fee_estimates(
101 fees: Arc<HashMap<ConfirmationTarget, AtomicU32>>, rpc_client: Arc<RpcClient>,
102 handle: tokio::runtime::Handle,
104 handle.spawn(async move {
106 let mempoolmin_estimate = {
107 let resp = rpc_client
108 .call_method::<MempoolMinFeeResponse>("getmempoolinfo", &vec![])
111 match resp.feerate_sat_per_kw {
112 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
116 let background_estimate = {
117 let background_conf_target = serde_json::json!(144);
118 let background_estimate_mode = serde_json::json!("ECONOMICAL");
119 let resp = rpc_client
120 .call_method::<FeeResponse>(
122 &vec![background_conf_target, background_estimate_mode],
126 match resp.feerate_sat_per_kw {
127 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
132 let normal_estimate = {
133 let normal_conf_target = serde_json::json!(18);
134 let normal_estimate_mode = serde_json::json!("ECONOMICAL");
135 let resp = rpc_client
136 .call_method::<FeeResponse>(
138 &vec![normal_conf_target, normal_estimate_mode],
142 match resp.feerate_sat_per_kw {
143 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
148 let high_prio_estimate = {
149 let high_prio_conf_target = serde_json::json!(6);
150 let high_prio_estimate_mode = serde_json::json!("CONSERVATIVE");
151 let resp = rpc_client
152 .call_method::<FeeResponse>(
154 &vec![high_prio_conf_target, high_prio_estimate_mode],
159 match resp.feerate_sat_per_kw {
160 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
165 fees.get(&ConfirmationTarget::MempoolMinimum)
167 .store(mempoolmin_estimate, Ordering::Release);
168 fees.get(&ConfirmationTarget::Background)
170 .store(background_estimate, Ordering::Release);
171 fees.get(&ConfirmationTarget::Normal)
173 .store(normal_estimate, Ordering::Release);
174 fees.get(&ConfirmationTarget::HighPriority)
176 .store(high_prio_estimate, Ordering::Release);
177 tokio::time::sleep(Duration::from_secs(60)).await;
182 pub fn get_new_rpc_client(&self) -> std::io::Result<RpcClient> {
183 let http_endpoint = HttpEndpoint::for_host(self.host.clone()).with_port(self.port);
184 let rpc_credentials =
185 base64::encode(format!("{}:{}", self.rpc_user.clone(), self.rpc_password.clone()));
186 RpcClient::new(&rpc_credentials, http_endpoint)
189 pub async fn create_raw_transaction(&self, outputs: Vec<HashMap<String, f64>>) -> RawTx {
190 let outputs_json = serde_json::json!(outputs);
191 self.bitcoind_rpc_client
192 .call_method::<RawTx>(
193 "createrawtransaction",
194 &vec![serde_json::json!([]), outputs_json],
200 pub async fn fund_raw_transaction(&self, raw_tx: RawTx) -> FundedTx {
201 let raw_tx_json = serde_json::json!(raw_tx.0);
202 let options = serde_json::json!({
203 // LDK gives us feerates in satoshis per KW but Bitcoin Core here expects fees
204 // denominated in satoshis per vB. First we need to multiply by 4 to convert weight
205 // units to virtual bytes, then divide by 1000 to convert KvB to vB.
206 "fee_rate": self.get_est_sat_per_1000_weight(ConfirmationTarget::Normal) as f64 / 250.0,
207 // While users could "cancel" a channel open by RBF-bumping and paying back to
208 // themselves, we don't allow it here as its easy to have users accidentally RBF bump
209 // and pay to the channel funding address, which results in loss of funds. Real
210 // LDK-based applications should enable RBF bumping and RBF bump either to a local
211 // change address or to a new channel output negotiated with the same node.
212 "replaceable": false,
214 self.bitcoind_rpc_client
215 .call_method("fundrawtransaction", &[raw_tx_json, options])
220 pub async fn send_raw_transaction(&self, raw_tx: RawTx) {
221 let raw_tx_json = serde_json::json!(raw_tx.0);
222 self.bitcoind_rpc_client
223 .call_method::<Txid>("sendrawtransaction", &[raw_tx_json])
228 pub async fn sign_raw_transaction_with_wallet(&self, tx_hex: String) -> SignedTx {
229 let tx_hex_json = serde_json::json!(tx_hex);
230 self.bitcoind_rpc_client
231 .call_method("signrawtransactionwithwallet", &vec![tx_hex_json])
236 pub async fn get_new_address(&self) -> Address {
237 let addr_args = vec![serde_json::json!("LDK output address")];
240 .call_method::<NewAddress>("getnewaddress", &addr_args)
243 Address::from_str(addr.0.as_str()).unwrap()
246 pub async fn get_blockchain_info(&self) -> BlockchainInfo {
247 self.bitcoind_rpc_client
248 .call_method::<BlockchainInfo>("getblockchaininfo", &vec![])
253 pub async fn list_unspent(&self) -> ListUnspentResponse {
254 self.bitcoind_rpc_client
255 .call_method::<ListUnspentResponse>("listunspent", &vec![])
261 impl FeeEstimator for BitcoindClient {
262 fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u32 {
263 self.fees.get(&confirmation_target).unwrap().load(Ordering::Acquire)
267 impl BroadcasterInterface for BitcoindClient {
268 fn broadcast_transactions(&self, txs: &[&Transaction]) {
269 // TODO: Rather than calling `sendrawtransaction` in a a loop, we should probably use
270 // `submitpackage` once it becomes available.
272 let bitcoind_rpc_client = Arc::clone(&self.bitcoind_rpc_client);
273 let tx_serialized = encode::serialize_hex(tx);
274 let tx_json = serde_json::json!(tx_serialized);
275 let logger = Arc::clone(&self.logger);
276 self.handle.spawn(async move {
277 // This may error due to RL calling `broadcast_transactions` with the same transaction
278 // multiple times, but the error is safe to ignore.
279 match bitcoind_rpc_client
280 .call_method::<Txid>("sendrawtransaction", &vec![tx_json])
285 let err_str = e.get_ref().unwrap().to_string();
287 "Warning, failed to broadcast a transaction, this is likely okay but may indicate an error: {}\nTransaction: {}",
290 print!("Warning, failed to broadcast a transaction, this is likely okay but may indicate an error: {}\n> ", err_str);
298 impl WalletSource for BitcoindClient {
299 fn list_confirmed_utxos(&self) -> Result<Vec<Utxo>, ()> {
300 let utxos = tokio::task::block_in_place(move || {
301 self.handle.block_on(async move { self.list_unspent().await }).0
306 let outpoint = OutPoint { txid: utxo.txid, vout: utxo.vout };
307 match utxo.address.payload {
308 Payload::WitnessProgram { version, ref program } => match version {
309 WitnessVersion::V0 => WPubkeyHash::from_slice(program)
310 .map(|wpkh| Utxo::new_v0_p2wpkh(outpoint, utxo.amount, &wpkh))
312 // TODO: Add `Utxo::new_v1_p2tr` upstream.
313 WitnessVersion::V1 => XOnlyPublicKey::from_slice(program)
318 script_pubkey: Script::new_witness_program(version, program),
320 satisfaction_weight: 1 /* empty script_sig */ * WITNESS_SCALE_FACTOR as u64 +
321 1 /* witness items */ + 1 /* schnorr sig len */ + 64, /* schnorr sig */
332 fn get_change_script(&self) -> Result<Script, ()> {
333 tokio::task::block_in_place(move || {
334 Ok(self.handle.block_on(async move { self.get_new_address().await.script_pubkey() }))
338 fn sign_tx(&self, tx: Transaction) -> Result<Transaction, ()> {
339 let mut tx_bytes = Vec::new();
340 let _ = tx.consensus_encode(&mut tx_bytes).map_err(|_| ());
341 let tx_hex = hex_utils::hex_str(&tx_bytes);
342 let signed_tx = tokio::task::block_in_place(move || {
343 self.handle.block_on(async move { self.sign_raw_transaction_with_wallet(tx_hex).await })
345 let signed_tx_bytes = hex_utils::to_vec(&signed_tx.hex).ok_or(())?;
346 Transaction::consensus_decode(&mut signed_tx_bytes.as_slice()).map_err(|_| ())