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::routing::utxo::{UtxoLookup, UtxoResult};
19 use lightning::util::logger::Logger;
20 use lightning_block_sync::http::HttpEndpoint;
21 use lightning_block_sync::rpc::RpcClient;
22 use lightning_block_sync::{AsyncBlockSourceResult, BlockData, BlockHeaderData, BlockSource};
24 use std::collections::HashMap;
25 use std::str::FromStr;
26 use std::sync::atomic::{AtomicU32, Ordering};
28 use std::time::Duration;
30 pub struct BitcoindClient {
31 bitcoind_rpc_client: Arc<RpcClient>,
36 fees: Arc<HashMap<Target, AtomicU32>>,
37 handle: tokio::runtime::Handle,
38 logger: Arc<FilesystemLogger>,
41 #[derive(Clone, Eq, Hash, PartialEq)]
49 impl BlockSource for BitcoindClient {
51 &'a self, header_hash: &'a BlockHash, height_hint: Option<u32>,
52 ) -> AsyncBlockSourceResult<'a, BlockHeaderData> {
53 Box::pin(async move { self.bitcoind_rpc_client.get_header(header_hash, height_hint).await })
57 &'a self, header_hash: &'a BlockHash,
58 ) -> AsyncBlockSourceResult<'a, BlockData> {
59 Box::pin(async move { self.bitcoind_rpc_client.get_block(header_hash).await })
62 fn get_best_block<'a>(&'a self) -> AsyncBlockSourceResult<(BlockHash, Option<u32>)> {
63 Box::pin(async move { self.bitcoind_rpc_client.get_best_block().await })
67 /// The minimum feerate we are allowed to send, as specify by LDK.
68 const MIN_FEERATE: u32 = 253;
71 pub(crate) async fn new(
72 host: String, port: u16, rpc_user: String, rpc_password: String,
73 handle: tokio::runtime::Handle, logger: Arc<FilesystemLogger>,
74 ) -> std::io::Result<Self> {
75 let http_endpoint = HttpEndpoint::for_host(host.clone()).with_port(port);
77 base64::encode(format!("{}:{}", rpc_user.clone(), rpc_password.clone()));
78 let bitcoind_rpc_client = RpcClient::new(&rpc_credentials, http_endpoint)?;
79 let _dummy = bitcoind_rpc_client
80 .call_method::<BlockchainInfo>("getblockchaininfo", &vec![])
83 std::io::Error::new(std::io::ErrorKind::PermissionDenied,
84 "Failed to make initial call to bitcoind - please check your RPC user/password and access settings")
86 let mut fees: HashMap<Target, AtomicU32> = HashMap::new();
87 fees.insert(Target::MempoolMinimum, AtomicU32::new(MIN_FEERATE));
88 fees.insert(Target::Background, AtomicU32::new(MIN_FEERATE));
89 fees.insert(Target::Normal, AtomicU32::new(2000));
90 fees.insert(Target::HighPriority, AtomicU32::new(5000));
92 bitcoind_rpc_client: Arc::new(bitcoind_rpc_client),
98 handle: handle.clone(),
101 BitcoindClient::poll_for_fee_estimates(
103 client.bitcoind_rpc_client.clone(),
109 fn poll_for_fee_estimates(
110 fees: Arc<HashMap<Target, AtomicU32>>, rpc_client: Arc<RpcClient>,
111 handle: tokio::runtime::Handle,
113 handle.spawn(async move {
115 let mempoolmin_estimate = {
116 let resp = rpc_client
117 .call_method::<MempoolMinFeeResponse>("getmempoolinfo", &vec![])
120 match resp.feerate_sat_per_kw {
121 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
125 let background_estimate = {
126 let background_conf_target = serde_json::json!(144);
127 let background_estimate_mode = serde_json::json!("ECONOMICAL");
128 let resp = rpc_client
129 .call_method::<FeeResponse>(
131 &vec![background_conf_target, background_estimate_mode],
135 match resp.feerate_sat_per_kw {
136 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
141 let normal_estimate = {
142 let normal_conf_target = serde_json::json!(18);
143 let normal_estimate_mode = serde_json::json!("ECONOMICAL");
144 let resp = rpc_client
145 .call_method::<FeeResponse>(
147 &vec![normal_conf_target, normal_estimate_mode],
151 match resp.feerate_sat_per_kw {
152 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
157 let high_prio_estimate = {
158 let high_prio_conf_target = serde_json::json!(6);
159 let high_prio_estimate_mode = serde_json::json!("CONSERVATIVE");
160 let resp = rpc_client
161 .call_method::<FeeResponse>(
163 &vec![high_prio_conf_target, high_prio_estimate_mode],
168 match resp.feerate_sat_per_kw {
169 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
174 fees.get(&Target::MempoolMinimum)
176 .store(mempoolmin_estimate, Ordering::Release);
177 fees.get(&Target::Background)
179 .store(background_estimate, Ordering::Release);
180 fees.get(&Target::Normal).unwrap().store(normal_estimate, Ordering::Release);
181 fees.get(&Target::HighPriority)
183 .store(high_prio_estimate, Ordering::Release);
184 tokio::time::sleep(Duration::from_secs(60)).await;
189 pub fn get_new_rpc_client(&self) -> std::io::Result<RpcClient> {
190 let http_endpoint = HttpEndpoint::for_host(self.host.clone()).with_port(self.port);
191 let rpc_credentials =
192 base64::encode(format!("{}:{}", self.rpc_user.clone(), self.rpc_password.clone()));
193 RpcClient::new(&rpc_credentials, http_endpoint)
196 pub async fn create_raw_transaction(&self, outputs: Vec<HashMap<String, f64>>) -> RawTx {
197 let outputs_json = serde_json::json!(outputs);
198 self.bitcoind_rpc_client
199 .call_method::<RawTx>(
200 "createrawtransaction",
201 &vec![serde_json::json!([]), outputs_json],
207 pub async fn fund_raw_transaction(&self, raw_tx: RawTx) -> FundedTx {
208 let raw_tx_json = serde_json::json!(raw_tx.0);
209 let options = serde_json::json!({
210 // LDK gives us feerates in satoshis per KW but Bitcoin Core here expects fees
211 // denominated in satoshis per vB. First we need to multiply by 4 to convert weight
212 // units to virtual bytes, then divide by 1000 to convert KvB to vB.
213 "fee_rate": self.get_est_sat_per_1000_weight(ConfirmationTarget::Normal) as f64 / 250.0,
214 // While users could "cancel" a channel open by RBF-bumping and paying back to
215 // themselves, we don't allow it here as its easy to have users accidentally RBF bump
216 // and pay to the channel funding address, which results in loss of funds. Real
217 // LDK-based applications should enable RBF bumping and RBF bump either to a local
218 // change address or to a new channel output negotiated with the same node.
219 "replaceable": false,
221 self.bitcoind_rpc_client
222 .call_method("fundrawtransaction", &[raw_tx_json, options])
227 pub async fn send_raw_transaction(&self, raw_tx: RawTx) {
228 let raw_tx_json = serde_json::json!(raw_tx.0);
229 self.bitcoind_rpc_client
230 .call_method::<Txid>("sendrawtransaction", &[raw_tx_json])
235 pub async fn sign_raw_transaction_with_wallet(&self, tx_hex: String) -> SignedTx {
236 let tx_hex_json = serde_json::json!(tx_hex);
237 self.bitcoind_rpc_client
238 .call_method("signrawtransactionwithwallet", &vec![tx_hex_json])
243 pub async fn get_new_address(&self) -> Address {
244 let addr_args = vec![serde_json::json!("LDK output address")];
247 .call_method::<NewAddress>("getnewaddress", &addr_args)
250 Address::from_str(addr.0.as_str()).unwrap()
253 pub async fn get_blockchain_info(&self) -> BlockchainInfo {
254 self.bitcoind_rpc_client
255 .call_method::<BlockchainInfo>("getblockchaininfo", &vec![])
260 pub async fn list_unspent(&self) -> ListUnspentResponse {
261 self.bitcoind_rpc_client
262 .call_method::<ListUnspentResponse>("listunspent", &vec![])
268 impl FeeEstimator for BitcoindClient {
269 fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u32 {
270 match confirmation_target {
271 ConfirmationTarget::MempoolMinimum => {
272 self.fees.get(&Target::MempoolMinimum).unwrap().load(Ordering::Acquire)
274 ConfirmationTarget::Background => {
275 self.fees.get(&Target::Background).unwrap().load(Ordering::Acquire)
277 ConfirmationTarget::Normal => {
278 self.fees.get(&Target::Normal).unwrap().load(Ordering::Acquire)
280 ConfirmationTarget::HighPriority => {
281 self.fees.get(&Target::HighPriority).unwrap().load(Ordering::Acquire)
287 impl BroadcasterInterface for BitcoindClient {
288 fn broadcast_transactions(&self, txs: &[&Transaction]) {
289 // TODO: Rather than calling `sendrawtransaction` in a a loop, we should probably use
290 // `submitpackage` once it becomes available.
292 let bitcoind_rpc_client = Arc::clone(&self.bitcoind_rpc_client);
293 let tx_serialized = encode::serialize_hex(tx);
294 let tx_json = serde_json::json!(tx_serialized);
295 let logger = Arc::clone(&self.logger);
296 self.handle.spawn(async move {
297 // This may error due to RL calling `broadcast_transactions` with the same transaction
298 // multiple times, but the error is safe to ignore.
299 match bitcoind_rpc_client
300 .call_method::<Txid>("sendrawtransaction", &vec![tx_json])
305 let err_str = e.get_ref().unwrap().to_string();
307 "Warning, failed to broadcast a transaction, this is likely okay but may indicate an error: {}\nTransaction: {}",
310 print!("Warning, failed to broadcast a transaction, this is likely okay but may indicate an error: {}\n> ", err_str);
318 impl UtxoLookup for BitcoindClient {
319 fn get_utxo(&self, _genesis_hash: &BlockHash, _short_channel_id: u64) -> UtxoResult {
320 // P2PGossipSync takes None for a UtxoLookup, so this will never be called.
325 impl WalletSource for BitcoindClient {
326 fn list_confirmed_utxos(&self) -> Result<Vec<Utxo>, ()> {
327 let utxos = tokio::task::block_in_place(move || {
328 self.handle.block_on(async move { self.list_unspent().await }).0
333 let outpoint = OutPoint { txid: utxo.txid, vout: utxo.vout };
334 match utxo.address.payload {
335 Payload::WitnessProgram { version, ref program } => match version {
336 WitnessVersion::V0 => WPubkeyHash::from_slice(program)
337 .map(|wpkh| Utxo::new_v0_p2wpkh(outpoint, utxo.amount, &wpkh))
339 // TODO: Add `Utxo::new_v1_p2tr` upstream.
340 WitnessVersion::V1 => XOnlyPublicKey::from_slice(program)
345 script_pubkey: Script::new_witness_program(version, program),
347 satisfaction_weight: 1 /* empty script_sig */ * WITNESS_SCALE_FACTOR as u64 +
348 1 /* witness items */ + 1 /* schnorr sig len */ + 64, /* schnorr sig */
359 fn get_change_script(&self) -> Result<Script, ()> {
360 tokio::task::block_in_place(move || {
361 Ok(self.handle.block_on(async move { self.get_new_address().await.script_pubkey() }))
365 fn sign_tx(&self, tx: Transaction) -> Result<Transaction, ()> {
366 let mut tx_bytes = Vec::new();
367 let _ = tx.consensus_encode(&mut tx_bytes).map_err(|_| ());
368 let tx_hex = hex_utils::hex_str(&tx_bytes);
369 let signed_tx = tokio::task::block_in_place(move || {
370 self.handle.block_on(async move { self.sign_raw_transaction_with_wallet(tx_hex).await })
372 let signed_tx_bytes = hex_utils::to_vec(&signed_tx.hex).ok_or(())?;
373 Transaction::consensus_decode(&mut signed_tx_bytes.as_slice()).map_err(|_| ())