2 BlockchainInfo, FeeResponse, FundedTx, MempoolMinFeeResponse, NewAddress, RawTx, SignedTx,
4 use crate::disk::FilesystemLogger;
6 use bitcoin::blockdata::transaction::Transaction;
7 use bitcoin::consensus::encode;
8 use bitcoin::hash_types::{BlockHash, Txid};
9 use bitcoin::util::address::Address;
10 use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
11 use lightning::log_error;
12 use lightning::routing::utxo::{UtxoLookup, UtxoResult};
13 use lightning::util::logger::Logger;
14 use lightning_block_sync::http::HttpEndpoint;
15 use lightning_block_sync::rpc::RpcClient;
16 use lightning_block_sync::{AsyncBlockSourceResult, BlockData, BlockHeaderData, BlockSource};
18 use std::collections::HashMap;
19 use std::str::FromStr;
20 use std::sync::atomic::{AtomicU32, Ordering};
22 use std::time::Duration;
24 pub struct BitcoindClient {
25 bitcoind_rpc_client: Arc<RpcClient>,
30 fees: Arc<HashMap<Target, AtomicU32>>,
31 handle: tokio::runtime::Handle,
32 logger: Arc<FilesystemLogger>,
35 #[derive(Clone, Eq, Hash, PartialEq)]
43 impl BlockSource for BitcoindClient {
45 &'a self, header_hash: &'a BlockHash, height_hint: Option<u32>,
46 ) -> AsyncBlockSourceResult<'a, BlockHeaderData> {
47 Box::pin(async move { self.bitcoind_rpc_client.get_header(header_hash, height_hint).await })
51 &'a self, header_hash: &'a BlockHash,
52 ) -> AsyncBlockSourceResult<'a, BlockData> {
53 Box::pin(async move { self.bitcoind_rpc_client.get_block(header_hash).await })
56 fn get_best_block<'a>(&'a self) -> AsyncBlockSourceResult<(BlockHash, Option<u32>)> {
57 Box::pin(async move { self.bitcoind_rpc_client.get_best_block().await })
61 /// The minimum feerate we are allowed to send, as specify by LDK.
62 const MIN_FEERATE: u32 = 253;
65 pub(crate) async fn new(
66 host: String, port: u16, rpc_user: String, rpc_password: String,
67 handle: tokio::runtime::Handle, logger: Arc<FilesystemLogger>,
68 ) -> std::io::Result<Self> {
69 let http_endpoint = HttpEndpoint::for_host(host.clone()).with_port(port);
71 base64::encode(format!("{}:{}", rpc_user.clone(), rpc_password.clone()));
72 let bitcoind_rpc_client = RpcClient::new(&rpc_credentials, http_endpoint)?;
73 let _dummy = bitcoind_rpc_client
74 .call_method::<BlockchainInfo>("getblockchaininfo", &vec![])
77 std::io::Error::new(std::io::ErrorKind::PermissionDenied,
78 "Failed to make initial call to bitcoind - please check your RPC user/password and access settings")
80 let mut fees: HashMap<Target, AtomicU32> = HashMap::new();
81 fees.insert(Target::MempoolMinimum, AtomicU32::new(MIN_FEERATE));
82 fees.insert(Target::Background, AtomicU32::new(MIN_FEERATE));
83 fees.insert(Target::Normal, AtomicU32::new(2000));
84 fees.insert(Target::HighPriority, AtomicU32::new(5000));
86 bitcoind_rpc_client: Arc::new(bitcoind_rpc_client),
92 handle: handle.clone(),
95 BitcoindClient::poll_for_fee_estimates(
97 client.bitcoind_rpc_client.clone(),
103 fn poll_for_fee_estimates(
104 fees: Arc<HashMap<Target, AtomicU32>>, rpc_client: Arc<RpcClient>,
105 handle: tokio::runtime::Handle,
107 handle.spawn(async move {
109 let mempoolmin_estimate = {
110 let resp = rpc_client
111 .call_method::<MempoolMinFeeResponse>("getmempoolinfo", &vec![])
114 match resp.feerate_sat_per_kw {
115 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
119 let background_estimate = {
120 let background_conf_target = serde_json::json!(144);
121 let background_estimate_mode = serde_json::json!("ECONOMICAL");
122 let resp = rpc_client
123 .call_method::<FeeResponse>(
125 &vec![background_conf_target, background_estimate_mode],
129 match resp.feerate_sat_per_kw {
130 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
135 let normal_estimate = {
136 let normal_conf_target = serde_json::json!(18);
137 let normal_estimate_mode = serde_json::json!("ECONOMICAL");
138 let resp = rpc_client
139 .call_method::<FeeResponse>(
141 &vec![normal_conf_target, normal_estimate_mode],
145 match resp.feerate_sat_per_kw {
146 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
151 let high_prio_estimate = {
152 let high_prio_conf_target = serde_json::json!(6);
153 let high_prio_estimate_mode = serde_json::json!("CONSERVATIVE");
154 let resp = rpc_client
155 .call_method::<FeeResponse>(
157 &vec![high_prio_conf_target, high_prio_estimate_mode],
162 match resp.feerate_sat_per_kw {
163 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
168 fees.get(&Target::MempoolMinimum)
170 .store(mempoolmin_estimate, Ordering::Release);
171 fees.get(&Target::Background)
173 .store(background_estimate, Ordering::Release);
174 fees.get(&Target::Normal).unwrap().store(normal_estimate, Ordering::Release);
175 fees.get(&Target::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![])
255 impl FeeEstimator for BitcoindClient {
256 fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u32 {
257 match confirmation_target {
258 ConfirmationTarget::MempoolMinimum => {
259 self.fees.get(&Target::MempoolMinimum).unwrap().load(Ordering::Acquire)
261 ConfirmationTarget::Background => {
262 self.fees.get(&Target::Background).unwrap().load(Ordering::Acquire)
264 ConfirmationTarget::Normal => {
265 self.fees.get(&Target::Normal).unwrap().load(Ordering::Acquire)
267 ConfirmationTarget::HighPriority => {
268 self.fees.get(&Target::HighPriority).unwrap().load(Ordering::Acquire)
274 impl BroadcasterInterface for BitcoindClient {
275 fn broadcast_transactions(&self, txs: &[&Transaction]) {
276 // TODO: Rather than calling `sendrawtransaction` in a a loop, we should probably use
277 // `submitpackage` once it becomes available.
279 let bitcoind_rpc_client = Arc::clone(&self.bitcoind_rpc_client);
280 let tx_serialized = encode::serialize_hex(tx);
281 let tx_json = serde_json::json!(tx_serialized);
282 let logger = Arc::clone(&self.logger);
283 self.handle.spawn(async move {
284 // This may error due to RL calling `broadcast_transactions` with the same transaction
285 // multiple times, but the error is safe to ignore.
286 match bitcoind_rpc_client
287 .call_method::<Txid>("sendrawtransaction", &vec![tx_json])
292 let err_str = e.get_ref().unwrap().to_string();
294 "Warning, failed to broadcast a transaction, this is likely okay but may indicate an error: {}\nTransaction: {}",
297 print!("Warning, failed to broadcast a transaction, this is likely okay but may indicate an error: {}\n> ", err_str);
305 impl UtxoLookup for BitcoindClient {
306 fn get_utxo(&self, _genesis_hash: &BlockHash, _short_channel_id: u64) -> UtxoResult {
307 // P2PGossipSync takes None for a UtxoLookup, so this will never be called.