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 pub(crate) bitcoind_rpc_client: Arc<RpcClient>,
36 fees: Arc<HashMap<ConfirmationTarget, AtomicU32>>,
37 handle: tokio::runtime::Handle,
38 logger: Arc<FilesystemLogger>,
41 impl BlockSource for BitcoindClient {
43 &'a self, header_hash: &'a BlockHash, height_hint: Option<u32>,
44 ) -> AsyncBlockSourceResult<'a, BlockHeaderData> {
45 Box::pin(async move { self.bitcoind_rpc_client.get_header(header_hash, height_hint).await })
49 &'a self, header_hash: &'a BlockHash,
50 ) -> AsyncBlockSourceResult<'a, BlockData> {
51 Box::pin(async move { self.bitcoind_rpc_client.get_block(header_hash).await })
54 fn get_best_block<'a>(&'a self) -> AsyncBlockSourceResult<(BlockHash, Option<u32>)> {
55 Box::pin(async move { self.bitcoind_rpc_client.get_best_block().await })
59 /// The minimum feerate we are allowed to send, as specify by LDK.
60 const MIN_FEERATE: u32 = 253;
63 pub(crate) async fn new(
64 host: String, port: u16, rpc_user: String, rpc_password: String,
65 handle: tokio::runtime::Handle, logger: Arc<FilesystemLogger>,
66 ) -> std::io::Result<Self> {
67 let http_endpoint = HttpEndpoint::for_host(host.clone()).with_port(port);
69 base64::encode(format!("{}:{}", rpc_user.clone(), rpc_password.clone()));
70 let bitcoind_rpc_client = RpcClient::new(&rpc_credentials, http_endpoint)?;
71 let _dummy = bitcoind_rpc_client
72 .call_method::<BlockchainInfo>("getblockchaininfo", &vec![])
75 std::io::Error::new(std::io::ErrorKind::PermissionDenied,
76 "Failed to make initial call to bitcoind - please check your RPC user/password and access settings")
78 let mut fees: HashMap<ConfirmationTarget, AtomicU32> = HashMap::new();
79 fees.insert(ConfirmationTarget::MempoolMinimum, AtomicU32::new(MIN_FEERATE));
80 fees.insert(ConfirmationTarget::Background, AtomicU32::new(MIN_FEERATE));
81 fees.insert(ConfirmationTarget::Normal, AtomicU32::new(2000));
82 fees.insert(ConfirmationTarget::HighPriority, AtomicU32::new(5000));
84 bitcoind_rpc_client: Arc::new(bitcoind_rpc_client),
90 handle: handle.clone(),
93 BitcoindClient::poll_for_fee_estimates(
95 client.bitcoind_rpc_client.clone(),
101 fn poll_for_fee_estimates(
102 fees: Arc<HashMap<ConfirmationTarget, AtomicU32>>, rpc_client: Arc<RpcClient>,
103 handle: tokio::runtime::Handle,
105 handle.spawn(async move {
107 let mempoolmin_estimate = {
108 let resp = rpc_client
109 .call_method::<MempoolMinFeeResponse>("getmempoolinfo", &vec![])
112 match resp.feerate_sat_per_kw {
113 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
117 let background_estimate = {
118 let background_conf_target = serde_json::json!(144);
119 let background_estimate_mode = serde_json::json!("ECONOMICAL");
120 let resp = rpc_client
121 .call_method::<FeeResponse>(
123 &vec![background_conf_target, background_estimate_mode],
127 match resp.feerate_sat_per_kw {
128 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
133 let normal_estimate = {
134 let normal_conf_target = serde_json::json!(18);
135 let normal_estimate_mode = serde_json::json!("ECONOMICAL");
136 let resp = rpc_client
137 .call_method::<FeeResponse>(
139 &vec![normal_conf_target, normal_estimate_mode],
143 match resp.feerate_sat_per_kw {
144 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
149 let high_prio_estimate = {
150 let high_prio_conf_target = serde_json::json!(6);
151 let high_prio_estimate_mode = serde_json::json!("CONSERVATIVE");
152 let resp = rpc_client
153 .call_method::<FeeResponse>(
155 &vec![high_prio_conf_target, high_prio_estimate_mode],
160 match resp.feerate_sat_per_kw {
161 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
166 fees.get(&ConfirmationTarget::MempoolMinimum)
168 .store(mempoolmin_estimate, Ordering::Release);
169 fees.get(&ConfirmationTarget::Background)
171 .store(background_estimate, Ordering::Release);
172 fees.get(&ConfirmationTarget::Normal)
174 .store(normal_estimate, Ordering::Release);
175 fees.get(&ConfirmationTarget::HighPriority)
177 .store(high_prio_estimate, Ordering::Release);
178 tokio::time::sleep(Duration::from_secs(60)).await;
183 pub fn get_new_rpc_client(&self) -> std::io::Result<RpcClient> {
184 let http_endpoint = HttpEndpoint::for_host(self.host.clone()).with_port(self.port);
185 let rpc_credentials =
186 base64::encode(format!("{}:{}", self.rpc_user.clone(), self.rpc_password.clone()));
187 RpcClient::new(&rpc_credentials, http_endpoint)
190 pub async fn create_raw_transaction(&self, outputs: Vec<HashMap<String, f64>>) -> RawTx {
191 let outputs_json = serde_json::json!(outputs);
192 self.bitcoind_rpc_client
193 .call_method::<RawTx>(
194 "createrawtransaction",
195 &vec![serde_json::json!([]), outputs_json],
201 pub async fn fund_raw_transaction(&self, raw_tx: RawTx) -> FundedTx {
202 let raw_tx_json = serde_json::json!(raw_tx.0);
203 let options = serde_json::json!({
204 // LDK gives us feerates in satoshis per KW but Bitcoin Core here expects fees
205 // denominated in satoshis per vB. First we need to multiply by 4 to convert weight
206 // units to virtual bytes, then divide by 1000 to convert KvB to vB.
207 "fee_rate": self.get_est_sat_per_1000_weight(ConfirmationTarget::Normal) as f64 / 250.0,
208 // While users could "cancel" a channel open by RBF-bumping and paying back to
209 // themselves, we don't allow it here as its easy to have users accidentally RBF bump
210 // and pay to the channel funding address, which results in loss of funds. Real
211 // LDK-based applications should enable RBF bumping and RBF bump either to a local
212 // change address or to a new channel output negotiated with the same node.
213 "replaceable": false,
215 self.bitcoind_rpc_client
216 .call_method("fundrawtransaction", &[raw_tx_json, options])
221 pub async fn send_raw_transaction(&self, raw_tx: RawTx) {
222 let raw_tx_json = serde_json::json!(raw_tx.0);
223 self.bitcoind_rpc_client
224 .call_method::<Txid>("sendrawtransaction", &[raw_tx_json])
229 pub async fn sign_raw_transaction_with_wallet(&self, tx_hex: String) -> SignedTx {
230 let tx_hex_json = serde_json::json!(tx_hex);
231 self.bitcoind_rpc_client
232 .call_method("signrawtransactionwithwallet", &vec![tx_hex_json])
237 pub async fn get_new_address(&self) -> Address {
238 let addr_args = vec![serde_json::json!("LDK output address")];
241 .call_method::<NewAddress>("getnewaddress", &addr_args)
244 Address::from_str(addr.0.as_str()).unwrap()
247 pub async fn get_blockchain_info(&self) -> BlockchainInfo {
248 self.bitcoind_rpc_client
249 .call_method::<BlockchainInfo>("getblockchaininfo", &vec![])
254 pub async fn list_unspent(&self) -> ListUnspentResponse {
255 self.bitcoind_rpc_client
256 .call_method::<ListUnspentResponse>("listunspent", &vec![])
262 impl FeeEstimator for BitcoindClient {
263 fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u32 {
264 self.fees.get(&confirmation_target).unwrap().load(Ordering::Acquire)
268 impl BroadcasterInterface for BitcoindClient {
269 fn broadcast_transactions(&self, txs: &[&Transaction]) {
270 // TODO: Rather than calling `sendrawtransaction` in a a loop, we should probably use
271 // `submitpackage` once it becomes available.
273 let bitcoind_rpc_client = Arc::clone(&self.bitcoind_rpc_client);
274 let tx_serialized = encode::serialize_hex(tx);
275 let tx_json = serde_json::json!(tx_serialized);
276 let logger = Arc::clone(&self.logger);
277 self.handle.spawn(async move {
278 // This may error due to RL calling `broadcast_transactions` with the same transaction
279 // multiple times, but the error is safe to ignore.
280 match bitcoind_rpc_client
281 .call_method::<Txid>("sendrawtransaction", &vec![tx_json])
286 let err_str = e.get_ref().unwrap().to_string();
288 "Warning, failed to broadcast a transaction, this is likely okay but may indicate an error: {}\nTransaction: {}",
291 print!("Warning, failed to broadcast a transaction, this is likely okay but may indicate an error: {}\n> ", err_str);
299 impl UtxoLookup for BitcoindClient {
300 fn get_utxo(&self, _genesis_hash: &BlockHash, _short_channel_id: u64) -> UtxoResult {
301 // P2PGossipSync takes None for a UtxoLookup, so this will never be called.
306 impl WalletSource for BitcoindClient {
307 fn list_confirmed_utxos(&self) -> Result<Vec<Utxo>, ()> {
308 let utxos = tokio::task::block_in_place(move || {
309 self.handle.block_on(async move { self.list_unspent().await }).0
314 let outpoint = OutPoint { txid: utxo.txid, vout: utxo.vout };
315 match utxo.address.payload {
316 Payload::WitnessProgram { version, ref program } => match version {
317 WitnessVersion::V0 => WPubkeyHash::from_slice(program)
318 .map(|wpkh| Utxo::new_v0_p2wpkh(outpoint, utxo.amount, &wpkh))
320 // TODO: Add `Utxo::new_v1_p2tr` upstream.
321 WitnessVersion::V1 => XOnlyPublicKey::from_slice(program)
326 script_pubkey: Script::new_witness_program(version, program),
328 satisfaction_weight: 1 /* empty script_sig */ * WITNESS_SCALE_FACTOR as u64 +
329 1 /* witness items */ + 1 /* schnorr sig len */ + 64, /* schnorr sig */
340 fn get_change_script(&self) -> Result<Script, ()> {
341 tokio::task::block_in_place(move || {
342 Ok(self.handle.block_on(async move { self.get_new_address().await.script_pubkey() }))
346 fn sign_tx(&self, tx: Transaction) -> Result<Transaction, ()> {
347 let mut tx_bytes = Vec::new();
348 let _ = tx.consensus_encode(&mut tx_bytes).map_err(|_| ());
349 let tx_hex = hex_utils::hex_str(&tx_bytes);
350 let signed_tx = tokio::task::block_in_place(move || {
351 self.handle.block_on(async move { self.sign_raw_transaction_with_wallet(tx_hex).await })
353 let signed_tx_bytes = hex_utils::to_vec(&signed_tx.hex).ok_or(())?;
354 Transaction::consensus_decode(&mut signed_tx_bytes.as_slice()).map_err(|_| ())