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::OnChainSweep, AtomicU32::new(5000));
80 ConfirmationTarget::MaxAllowedNonAnchorChannelRemoteFee,
81 AtomicU32::new(25 * 250),
84 ConfirmationTarget::MinAllowedAnchorChannelRemoteFee,
85 AtomicU32::new(MIN_FEERATE),
88 ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee,
89 AtomicU32::new(MIN_FEERATE),
91 fees.insert(ConfirmationTarget::AnchorChannelFee, AtomicU32::new(MIN_FEERATE));
92 fees.insert(ConfirmationTarget::NonAnchorChannelFee, AtomicU32::new(2000));
93 fees.insert(ConfirmationTarget::ChannelCloseMinimum, AtomicU32::new(MIN_FEERATE));
96 bitcoind_rpc_client: Arc::new(bitcoind_rpc_client),
101 fees: Arc::new(fees),
102 handle: handle.clone(),
105 BitcoindClient::poll_for_fee_estimates(
107 client.bitcoind_rpc_client.clone(),
113 fn poll_for_fee_estimates(
114 fees: Arc<HashMap<ConfirmationTarget, AtomicU32>>, rpc_client: Arc<RpcClient>,
115 handle: tokio::runtime::Handle,
117 handle.spawn(async move {
119 let mempoolmin_estimate = {
120 let resp = rpc_client
121 .call_method::<MempoolMinFeeResponse>("getmempoolinfo", &vec![])
124 match resp.feerate_sat_per_kw {
125 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
129 let background_estimate = {
130 let background_conf_target = serde_json::json!(144);
131 let background_estimate_mode = serde_json::json!("ECONOMICAL");
132 let resp = rpc_client
133 .call_method::<FeeResponse>(
135 &vec![background_conf_target, background_estimate_mode],
139 match resp.feerate_sat_per_kw {
140 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
145 let normal_estimate = {
146 let normal_conf_target = serde_json::json!(18);
147 let normal_estimate_mode = serde_json::json!("ECONOMICAL");
148 let resp = rpc_client
149 .call_method::<FeeResponse>(
151 &vec![normal_conf_target, normal_estimate_mode],
155 match resp.feerate_sat_per_kw {
156 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
161 let high_prio_estimate = {
162 let high_prio_conf_target = serde_json::json!(6);
163 let high_prio_estimate_mode = serde_json::json!("CONSERVATIVE");
164 let resp = rpc_client
165 .call_method::<FeeResponse>(
167 &vec![high_prio_conf_target, high_prio_estimate_mode],
172 match resp.feerate_sat_per_kw {
173 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
178 fees.get(&ConfirmationTarget::OnChainSweep)
180 .store(high_prio_estimate, Ordering::Release);
181 fees.get(&ConfirmationTarget::MaxAllowedNonAnchorChannelRemoteFee)
183 .store(std::cmp::max(25 * 250, high_prio_estimate * 10), Ordering::Release);
184 fees.get(&ConfirmationTarget::MinAllowedAnchorChannelRemoteFee)
186 .store(mempoolmin_estimate, Ordering::Release);
187 fees.get(&ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee)
189 .store(background_estimate - 250, Ordering::Release);
190 fees.get(&ConfirmationTarget::AnchorChannelFee)
192 .store(background_estimate, Ordering::Release);
193 fees.get(&ConfirmationTarget::NonAnchorChannelFee)
195 .store(normal_estimate, Ordering::Release);
196 fees.get(&ConfirmationTarget::ChannelCloseMinimum)
198 .store(background_estimate, Ordering::Release);
200 tokio::time::sleep(Duration::from_secs(60)).await;
205 pub fn get_new_rpc_client(&self) -> std::io::Result<RpcClient> {
206 let http_endpoint = HttpEndpoint::for_host(self.host.clone()).with_port(self.port);
207 let rpc_credentials =
208 base64::encode(format!("{}:{}", self.rpc_user.clone(), self.rpc_password.clone()));
209 RpcClient::new(&rpc_credentials, http_endpoint)
212 pub async fn create_raw_transaction(&self, outputs: Vec<HashMap<String, f64>>) -> RawTx {
213 let outputs_json = serde_json::json!(outputs);
214 self.bitcoind_rpc_client
215 .call_method::<RawTx>(
216 "createrawtransaction",
217 &vec![serde_json::json!([]), outputs_json],
223 pub async fn fund_raw_transaction(&self, raw_tx: RawTx) -> FundedTx {
224 let raw_tx_json = serde_json::json!(raw_tx.0);
225 let options = serde_json::json!({
226 // LDK gives us feerates in satoshis per KW but Bitcoin Core here expects fees
227 // denominated in satoshis per vB. First we need to multiply by 4 to convert weight
228 // units to virtual bytes, then divide by 1000 to convert KvB to vB.
230 .get_est_sat_per_1000_weight(ConfirmationTarget::NonAnchorChannelFee) as f64 / 250.0,
231 // While users could "cancel" a channel open by RBF-bumping and paying back to
232 // themselves, we don't allow it here as its easy to have users accidentally RBF bump
233 // and pay to the channel funding address, which results in loss of funds. Real
234 // LDK-based applications should enable RBF bumping and RBF bump either to a local
235 // change address or to a new channel output negotiated with the same node.
236 "replaceable": false,
238 self.bitcoind_rpc_client
239 .call_method("fundrawtransaction", &[raw_tx_json, options])
244 pub async fn send_raw_transaction(&self, raw_tx: RawTx) {
245 let raw_tx_json = serde_json::json!(raw_tx.0);
246 self.bitcoind_rpc_client
247 .call_method::<Txid>("sendrawtransaction", &[raw_tx_json])
252 pub async fn sign_raw_transaction_with_wallet(&self, tx_hex: String) -> SignedTx {
253 let tx_hex_json = serde_json::json!(tx_hex);
254 self.bitcoind_rpc_client
255 .call_method("signrawtransactionwithwallet", &vec![tx_hex_json])
260 pub async fn get_new_address(&self) -> Address {
261 let addr_args = vec![serde_json::json!("LDK output address")];
264 .call_method::<NewAddress>("getnewaddress", &addr_args)
267 Address::from_str(addr.0.as_str()).unwrap()
270 pub async fn get_blockchain_info(&self) -> BlockchainInfo {
271 self.bitcoind_rpc_client
272 .call_method::<BlockchainInfo>("getblockchaininfo", &vec![])
277 pub async fn list_unspent(&self) -> ListUnspentResponse {
278 self.bitcoind_rpc_client
279 .call_method::<ListUnspentResponse>("listunspent", &vec![])
285 impl FeeEstimator for BitcoindClient {
286 fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u32 {
287 self.fees.get(&confirmation_target).unwrap().load(Ordering::Acquire)
291 impl BroadcasterInterface for BitcoindClient {
292 fn broadcast_transactions(&self, txs: &[&Transaction]) {
293 // TODO: Rather than calling `sendrawtransaction` in a a loop, we should probably use
294 // `submitpackage` once it becomes available.
296 let bitcoind_rpc_client = Arc::clone(&self.bitcoind_rpc_client);
297 let tx_serialized = encode::serialize_hex(tx);
298 let tx_json = serde_json::json!(tx_serialized);
299 let logger = Arc::clone(&self.logger);
300 self.handle.spawn(async move {
301 // This may error due to RL calling `broadcast_transactions` with the same transaction
302 // multiple times, but the error is safe to ignore.
303 match bitcoind_rpc_client
304 .call_method::<Txid>("sendrawtransaction", &vec![tx_json])
309 let err_str = e.get_ref().unwrap().to_string();
311 "Warning, failed to broadcast a transaction, this is likely okay but may indicate an error: {}\nTransaction: {}",
314 print!("Warning, failed to broadcast a transaction, this is likely okay but may indicate an error: {}\n> ", err_str);
322 impl WalletSource for BitcoindClient {
323 fn list_confirmed_utxos(&self) -> Result<Vec<Utxo>, ()> {
324 let utxos = tokio::task::block_in_place(move || {
325 self.handle.block_on(async move { self.list_unspent().await }).0
330 let outpoint = OutPoint { txid: utxo.txid, vout: utxo.vout };
331 match utxo.address.payload {
332 Payload::WitnessProgram { version, ref program } => match version {
333 WitnessVersion::V0 => WPubkeyHash::from_slice(program)
334 .map(|wpkh| Utxo::new_v0_p2wpkh(outpoint, utxo.amount, &wpkh))
336 // TODO: Add `Utxo::new_v1_p2tr` upstream.
337 WitnessVersion::V1 => XOnlyPublicKey::from_slice(program)
342 script_pubkey: Script::new_witness_program(version, program),
344 satisfaction_weight: 1 /* empty script_sig */ * WITNESS_SCALE_FACTOR as u64 +
345 1 /* witness items */ + 1 /* schnorr sig len */ + 64, /* schnorr sig */
356 fn get_change_script(&self) -> Result<Script, ()> {
357 tokio::task::block_in_place(move || {
358 Ok(self.handle.block_on(async move { self.get_new_address().await.script_pubkey() }))
362 fn sign_tx(&self, tx: Transaction) -> Result<Transaction, ()> {
363 let mut tx_bytes = Vec::new();
364 let _ = tx.consensus_encode(&mut tx_bytes).map_err(|_| ());
365 let tx_hex = hex_utils::hex_str(&tx_bytes);
366 let signed_tx = tokio::task::block_in_place(move || {
367 self.handle.block_on(async move { self.sign_raw_transaction_with_wallet(tx_hex).await })
369 let signed_tx_bytes = hex_utils::to_vec(&signed_tx.hex).ok_or(())?;
370 Transaction::consensus_decode(&mut signed_tx_bytes.as_slice()).map_err(|_| ())