1 use crate::convert::{BlockchainInfo, FeeResponse, FundedTx, NewAddress, RawTx, SignedTx};
2 use crate::disk::FilesystemLogger;
4 use bitcoin::blockdata::transaction::Transaction;
5 use bitcoin::consensus::encode;
6 use bitcoin::hash_types::{BlockHash, Txid};
7 use bitcoin::util::address::Address;
8 use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
9 use lightning::log_error;
10 use lightning::routing::utxo::{UtxoLookup, UtxoResult};
11 use lightning::util::logger::Logger;
12 use lightning_block_sync::http::HttpEndpoint;
13 use lightning_block_sync::rpc::RpcClient;
14 use lightning_block_sync::{AsyncBlockSourceResult, BlockData, BlockHeaderData, BlockSource};
16 use std::collections::HashMap;
17 use std::str::FromStr;
18 use std::sync::atomic::{AtomicU32, Ordering};
20 use std::time::Duration;
22 pub struct BitcoindClient {
23 bitcoind_rpc_client: Arc<RpcClient>,
28 fees: Arc<HashMap<Target, AtomicU32>>,
29 handle: tokio::runtime::Handle,
30 logger: Arc<FilesystemLogger>,
33 #[derive(Clone, Eq, Hash, PartialEq)]
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<Target, AtomicU32> = HashMap::new();
78 fees.insert(Target::Background, AtomicU32::new(MIN_FEERATE));
79 fees.insert(Target::Normal, AtomicU32::new(2000));
80 fees.insert(Target::HighPriority, AtomicU32::new(5000));
82 bitcoind_rpc_client: Arc::new(bitcoind_rpc_client),
88 handle: handle.clone(),
91 BitcoindClient::poll_for_fee_estimates(
93 client.bitcoind_rpc_client.clone(),
99 fn poll_for_fee_estimates(
100 fees: Arc<HashMap<Target, AtomicU32>>, rpc_client: Arc<RpcClient>,
101 handle: tokio::runtime::Handle,
103 handle.spawn(async move {
105 let background_estimate = {
106 let background_conf_target = serde_json::json!(144);
107 let background_estimate_mode = serde_json::json!("ECONOMICAL");
108 let resp = rpc_client
109 .call_method::<FeeResponse>(
111 &vec![background_conf_target, background_estimate_mode],
115 match resp.feerate_sat_per_kw {
116 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
121 let normal_estimate = {
122 let normal_conf_target = serde_json::json!(18);
123 let normal_estimate_mode = serde_json::json!("ECONOMICAL");
124 let resp = rpc_client
125 .call_method::<FeeResponse>(
127 &vec![normal_conf_target, normal_estimate_mode],
131 match resp.feerate_sat_per_kw {
132 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
137 let high_prio_estimate = {
138 let high_prio_conf_target = serde_json::json!(6);
139 let high_prio_estimate_mode = serde_json::json!("CONSERVATIVE");
140 let resp = rpc_client
141 .call_method::<FeeResponse>(
143 &vec![high_prio_conf_target, high_prio_estimate_mode],
148 match resp.feerate_sat_per_kw {
149 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
154 fees.get(&Target::Background)
156 .store(background_estimate, Ordering::Release);
157 fees.get(&Target::Normal).unwrap().store(normal_estimate, Ordering::Release);
158 fees.get(&Target::HighPriority)
160 .store(high_prio_estimate, Ordering::Release);
161 tokio::time::sleep(Duration::from_secs(60)).await;
166 pub fn get_new_rpc_client(&self) -> std::io::Result<RpcClient> {
167 let http_endpoint = HttpEndpoint::for_host(self.host.clone()).with_port(self.port);
168 let rpc_credentials =
169 base64::encode(format!("{}:{}", self.rpc_user.clone(), self.rpc_password.clone()));
170 RpcClient::new(&rpc_credentials, http_endpoint)
173 pub async fn create_raw_transaction(&self, outputs: Vec<HashMap<String, f64>>) -> RawTx {
174 let outputs_json = serde_json::json!(outputs);
175 self.bitcoind_rpc_client
176 .call_method::<RawTx>(
177 "createrawtransaction",
178 &vec![serde_json::json!([]), outputs_json],
184 pub async fn fund_raw_transaction(&self, raw_tx: RawTx) -> FundedTx {
185 let raw_tx_json = serde_json::json!(raw_tx.0);
186 let options = serde_json::json!({
187 // LDK gives us feerates in satoshis per KW but Bitcoin Core here expects fees
188 // denominated in satoshis per vB. First we need to multiply by 4 to convert weight
189 // units to virtual bytes, then divide by 1000 to convert KvB to vB.
190 "fee_rate": self.get_est_sat_per_1000_weight(ConfirmationTarget::Normal) as f64 / 250.0,
191 // While users could "cancel" a channel open by RBF-bumping and paying back to
192 // themselves, we don't allow it here as its easy to have users accidentally RBF bump
193 // and pay to the channel funding address, which results in loss of funds. Real
194 // LDK-based applications should enable RBF bumping and RBF bump either to a local
195 // change address or to a new channel output negotiated with the same node.
196 "replaceable": false,
198 self.bitcoind_rpc_client
199 .call_method("fundrawtransaction", &[raw_tx_json, options])
204 pub async fn send_raw_transaction(&self, raw_tx: RawTx) {
205 let raw_tx_json = serde_json::json!(raw_tx.0);
206 self.bitcoind_rpc_client
207 .call_method::<Txid>("sendrawtransaction", &[raw_tx_json])
212 pub async fn sign_raw_transaction_with_wallet(&self, tx_hex: String) -> SignedTx {
213 let tx_hex_json = serde_json::json!(tx_hex);
214 self.bitcoind_rpc_client
215 .call_method("signrawtransactionwithwallet", &vec![tx_hex_json])
220 pub async fn get_new_address(&self) -> Address {
221 let addr_args = vec![serde_json::json!("LDK output address")];
224 .call_method::<NewAddress>("getnewaddress", &addr_args)
227 Address::from_str(addr.0.as_str()).unwrap()
230 pub async fn get_blockchain_info(&self) -> BlockchainInfo {
231 self.bitcoind_rpc_client
232 .call_method::<BlockchainInfo>("getblockchaininfo", &vec![])
238 impl FeeEstimator for BitcoindClient {
239 fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u32 {
240 match confirmation_target {
241 ConfirmationTarget::Background => {
242 self.fees.get(&Target::Background).unwrap().load(Ordering::Acquire)
244 ConfirmationTarget::Normal => {
245 self.fees.get(&Target::Normal).unwrap().load(Ordering::Acquire)
247 ConfirmationTarget::HighPriority => {
248 self.fees.get(&Target::HighPriority).unwrap().load(Ordering::Acquire)
254 impl BroadcasterInterface for BitcoindClient {
255 fn broadcast_transaction(&self, tx: &Transaction) {
256 let bitcoind_rpc_client = self.bitcoind_rpc_client.clone();
257 let tx_serialized = serde_json::json!(encode::serialize_hex(tx));
258 let logger = Arc::clone(&self.logger);
259 self.handle.spawn(async move {
260 // This may error due to RL calling `broadcast_transaction` with the same transaction
261 // multiple times, but the error is safe to ignore.
262 match bitcoind_rpc_client
263 .call_method::<Txid>("sendrawtransaction", &vec![tx_serialized])
268 let err_str = e.get_ref().unwrap().to_string();
269 if !err_str.contains("Transaction already in block chain")
270 && !err_str.contains("Inputs missing or spent")
271 && !err_str.contains("bad-txns-inputs-missingorspent")
272 && !err_str.contains("txn-mempool-conflict")
273 && !err_str.contains("non-BIP68-final")
274 && !err_str.contains("insufficient fee, rejecting replacement ")
284 impl UtxoLookup for BitcoindClient {
285 fn get_utxo(&self, _genesis_hash: &BlockHash, _short_channel_id: u64) -> UtxoResult {
286 // P2PGossipSync takes None for a UtxoLookup, so this will never be called.