2 BlockchainInfo, FeeResponse, FundedTx, ListUnspentResponse, MempoolMinFeeResponse, NewAddress,
5 use crate::disk::FilesystemLogger;
8 use bitcoin::address::{Address, Payload, WitnessVersion};
9 use bitcoin::blockdata::constants::WITNESS_SCALE_FACTOR;
10 use bitcoin::blockdata::script::ScriptBuf;
11 use bitcoin::blockdata::transaction::Transaction;
12 use bitcoin::consensus::{encode, Decodable, Encodable};
13 use bitcoin::hash_types::{BlockHash, Txid};
14 use bitcoin::hashes::Hash;
15 use bitcoin::key::XOnlyPublicKey;
16 use bitcoin::psbt::PartiallySignedTransaction;
17 use bitcoin::{Network, OutPoint, TxOut, WPubkeyHash};
18 use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
19 use lightning::events::bump_transaction::{Utxo, WalletSource};
20 use lightning::log_error;
21 use lightning::util::logger::Logger;
22 use lightning_block_sync::http::HttpEndpoint;
23 use lightning_block_sync::rpc::RpcClient;
24 use lightning_block_sync::{AsyncBlockSourceResult, BlockData, BlockHeaderData, BlockSource};
26 use std::collections::HashMap;
27 use std::str::FromStr;
28 use std::sync::atomic::{AtomicU32, Ordering};
30 use std::time::Duration;
32 pub struct BitcoindClient {
33 pub(crate) bitcoind_rpc_client: Arc<RpcClient>,
39 fees: Arc<HashMap<ConfirmationTarget, AtomicU32>>,
40 handle: tokio::runtime::Handle,
41 logger: Arc<FilesystemLogger>,
44 impl BlockSource for BitcoindClient {
46 &'a self, header_hash: &'a BlockHash, height_hint: Option<u32>,
47 ) -> AsyncBlockSourceResult<'a, BlockHeaderData> {
48 Box::pin(async move { self.bitcoind_rpc_client.get_header(header_hash, height_hint).await })
52 &'a self, header_hash: &'a BlockHash,
53 ) -> AsyncBlockSourceResult<'a, BlockData> {
54 Box::pin(async move { self.bitcoind_rpc_client.get_block(header_hash).await })
57 fn get_best_block<'a>(&'a self) -> AsyncBlockSourceResult<(BlockHash, Option<u32>)> {
58 Box::pin(async move { self.bitcoind_rpc_client.get_best_block().await })
62 /// The minimum feerate we are allowed to send, as specify by LDK.
63 const MIN_FEERATE: u32 = 253;
66 pub(crate) async fn new(
67 host: String, port: u16, rpc_user: String, rpc_password: String, network: Network,
68 handle: tokio::runtime::Handle, logger: Arc<FilesystemLogger>,
69 ) -> std::io::Result<Self> {
70 let http_endpoint = HttpEndpoint::for_host(host.clone()).with_port(port);
72 base64::encode(format!("{}:{}", rpc_user.clone(), rpc_password.clone()));
73 let bitcoind_rpc_client = RpcClient::new(&rpc_credentials, http_endpoint)?;
74 let _dummy = bitcoind_rpc_client
75 .call_method::<BlockchainInfo>("getblockchaininfo", &vec![])
78 std::io::Error::new(std::io::ErrorKind::PermissionDenied,
79 "Failed to make initial call to bitcoind - please check your RPC user/password and access settings")
81 let mut fees: HashMap<ConfirmationTarget, AtomicU32> = HashMap::new();
82 fees.insert(ConfirmationTarget::OnChainSweep, AtomicU32::new(5000));
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),
102 fees: Arc::new(fees),
103 handle: handle.clone(),
106 BitcoindClient::poll_for_fee_estimates(
108 client.bitcoind_rpc_client.clone(),
114 fn poll_for_fee_estimates(
115 fees: Arc<HashMap<ConfirmationTarget, AtomicU32>>, rpc_client: Arc<RpcClient>,
116 handle: tokio::runtime::Handle,
118 handle.spawn(async move {
120 let mempoolmin_estimate = {
121 let resp = rpc_client
122 .call_method::<MempoolMinFeeResponse>("getmempoolinfo", &vec![])
125 match resp.feerate_sat_per_kw {
126 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
130 let background_estimate = {
131 let background_conf_target = serde_json::json!(144);
132 let background_estimate_mode = serde_json::json!("ECONOMICAL");
133 let resp = rpc_client
134 .call_method::<FeeResponse>(
136 &vec![background_conf_target, background_estimate_mode],
140 match resp.feerate_sat_per_kw {
141 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
146 let normal_estimate = {
147 let normal_conf_target = serde_json::json!(18);
148 let normal_estimate_mode = serde_json::json!("ECONOMICAL");
149 let resp = rpc_client
150 .call_method::<FeeResponse>(
152 &vec![normal_conf_target, normal_estimate_mode],
156 match resp.feerate_sat_per_kw {
157 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
162 let high_prio_estimate = {
163 let high_prio_conf_target = serde_json::json!(6);
164 let high_prio_estimate_mode = serde_json::json!("CONSERVATIVE");
165 let resp = rpc_client
166 .call_method::<FeeResponse>(
168 &vec![high_prio_conf_target, high_prio_estimate_mode],
173 match resp.feerate_sat_per_kw {
174 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
179 fees.get(&ConfirmationTarget::OnChainSweep)
181 .store(high_prio_estimate, Ordering::Release);
182 fees.get(&ConfirmationTarget::MinAllowedAnchorChannelRemoteFee)
184 .store(mempoolmin_estimate, Ordering::Release);
185 fees.get(&ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee)
187 .store(background_estimate - 250, Ordering::Release);
188 fees.get(&ConfirmationTarget::AnchorChannelFee)
190 .store(background_estimate, Ordering::Release);
191 fees.get(&ConfirmationTarget::NonAnchorChannelFee)
193 .store(normal_estimate, Ordering::Release);
194 fees.get(&ConfirmationTarget::ChannelCloseMinimum)
196 .store(background_estimate, Ordering::Release);
198 tokio::time::sleep(Duration::from_secs(60)).await;
203 pub fn get_new_rpc_client(&self) -> std::io::Result<RpcClient> {
204 let http_endpoint = HttpEndpoint::for_host(self.host.clone()).with_port(self.port);
205 let rpc_credentials =
206 base64::encode(format!("{}:{}", self.rpc_user.clone(), self.rpc_password.clone()));
207 RpcClient::new(&rpc_credentials, http_endpoint)
210 pub async fn create_raw_transaction(&self, outputs: Vec<HashMap<String, f64>>) -> RawTx {
211 let outputs_json = serde_json::json!(outputs);
212 self.bitcoind_rpc_client
213 .call_method::<RawTx>(
214 "createrawtransaction",
215 &vec![serde_json::json!([]), outputs_json],
221 pub async fn fund_raw_transaction(&self, raw_tx: RawTx) -> FundedTx {
222 let raw_tx_json = serde_json::json!(raw_tx.0);
223 let options = serde_json::json!({
224 // LDK gives us feerates in satoshis per KW but Bitcoin Core here expects fees
225 // denominated in satoshis per vB. First we need to multiply by 4 to convert weight
226 // units to virtual bytes, then divide by 1000 to convert KvB to vB.
228 .get_est_sat_per_1000_weight(ConfirmationTarget::NonAnchorChannelFee) as f64 / 250.0,
229 // While users could "cancel" a channel open by RBF-bumping and paying back to
230 // themselves, we don't allow it here as its easy to have users accidentally RBF bump
231 // and pay to the channel funding address, which results in loss of funds. Real
232 // LDK-based applications should enable RBF bumping and RBF bump either to a local
233 // change address or to a new channel output negotiated with the same node.
234 "replaceable": false,
236 self.bitcoind_rpc_client
237 .call_method("fundrawtransaction", &[raw_tx_json, options])
242 pub async fn send_raw_transaction(&self, raw_tx: RawTx) {
243 let raw_tx_json = serde_json::json!(raw_tx.0);
244 self.bitcoind_rpc_client
245 .call_method::<Txid>("sendrawtransaction", &[raw_tx_json])
250 pub async fn sign_raw_transaction_with_wallet(&self, tx_hex: String) -> SignedTx {
251 let tx_hex_json = serde_json::json!(tx_hex);
252 self.bitcoind_rpc_client
253 .call_method("signrawtransactionwithwallet", &vec![tx_hex_json])
258 pub async fn get_new_address(&self) -> Address {
259 let addr_args = vec![serde_json::json!("LDK output address")];
262 .call_method::<NewAddress>("getnewaddress", &addr_args)
265 Address::from_str(addr.0.as_str()).unwrap().require_network(self.network).unwrap()
268 pub async fn get_blockchain_info(&self) -> BlockchainInfo {
269 self.bitcoind_rpc_client
270 .call_method::<BlockchainInfo>("getblockchaininfo", &vec![])
275 pub async fn list_unspent(&self) -> ListUnspentResponse {
276 self.bitcoind_rpc_client
277 .call_method::<ListUnspentResponse>("listunspent", &vec![])
283 impl FeeEstimator for BitcoindClient {
284 fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u32 {
285 self.fees.get(&confirmation_target).unwrap().load(Ordering::Acquire)
289 impl BroadcasterInterface for BitcoindClient {
290 fn broadcast_transactions(&self, txs: &[&Transaction]) {
291 // TODO: Rather than calling `sendrawtransaction` in a a loop, we should probably use
292 // `submitpackage` once it becomes available.
294 let bitcoind_rpc_client = Arc::clone(&self.bitcoind_rpc_client);
295 let tx_serialized = encode::serialize_hex(tx);
296 let tx_json = serde_json::json!(tx_serialized);
297 let logger = Arc::clone(&self.logger);
298 self.handle.spawn(async move {
299 // This may error due to RL calling `broadcast_transactions` with the same transaction
300 // multiple times, but the error is safe to ignore.
301 match bitcoind_rpc_client
302 .call_method::<Txid>("sendrawtransaction", &vec![tx_json])
307 let err_str = e.get_ref().unwrap().to_string();
309 "Warning, failed to broadcast a transaction, this is likely okay but may indicate an error: {}\nTransaction: {}",
312 print!("Warning, failed to broadcast a transaction, this is likely okay but may indicate an error: {}\n> ", err_str);
320 impl WalletSource for BitcoindClient {
321 fn list_confirmed_utxos(&self) -> Result<Vec<Utxo>, ()> {
322 let utxos = tokio::task::block_in_place(move || {
323 self.handle.block_on(async move { self.list_unspent().await }).0
328 let outpoint = OutPoint { txid: utxo.txid, vout: utxo.vout };
329 match utxo.address.payload.clone() {
330 Payload::WitnessProgram(wp) => match wp.version() {
331 WitnessVersion::V0 => WPubkeyHash::from_slice(wp.program().as_bytes())
332 .map(|wpkh| Utxo::new_v0_p2wpkh(outpoint, utxo.amount, &wpkh))
334 // TODO: Add `Utxo::new_v1_p2tr` upstream.
335 WitnessVersion::V1 => XOnlyPublicKey::from_slice(wp.program().as_bytes())
340 script_pubkey: ScriptBuf::new_witness_program(&wp),
342 satisfaction_weight: 1 /* empty script_sig */ * WITNESS_SCALE_FACTOR as u64 +
343 1 /* witness items */ + 1 /* schnorr sig len */ + 64, /* schnorr sig */
354 fn get_change_script(&self) -> Result<ScriptBuf, ()> {
355 tokio::task::block_in_place(move || {
356 Ok(self.handle.block_on(async move { self.get_new_address().await.script_pubkey() }))
360 fn sign_psbt(&self, tx: PartiallySignedTransaction) -> Result<Transaction, ()> {
361 let mut tx_bytes = Vec::new();
362 let _ = tx.unsigned_tx.consensus_encode(&mut tx_bytes).map_err(|_| ());
363 let tx_hex = hex_utils::hex_str(&tx_bytes);
364 let signed_tx = tokio::task::block_in_place(move || {
365 self.handle.block_on(async move { self.sign_raw_transaction_with_wallet(tx_hex).await })
367 let signed_tx_bytes = hex_utils::to_vec(&signed_tx.hex).ok_or(())?;
368 Transaction::consensus_decode(&mut signed_tx_bytes.as_slice()).map_err(|_| ())