9f28015cf5ed0326190ac88b79b67f736c8de4a0
[ldk-sample] / src / bitcoind_client.rs
1 use crate::convert::{
2         BlockchainInfo, FeeResponse, FundedTx, ListUnspentResponse, MempoolMinFeeResponse, NewAddress,
3         RawTx, SignedTx,
4 };
5 use crate::disk::FilesystemLogger;
6 use crate::hex_utils;
7 use base64;
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};
23 use serde_json;
24 use std::collections::HashMap;
25 use std::str::FromStr;
26 use std::sync::atomic::{AtomicU32, Ordering};
27 use std::sync::Arc;
28 use std::time::Duration;
29
30 pub struct BitcoindClient {
31         pub(crate) bitcoind_rpc_client: Arc<RpcClient>,
32         host: String,
33         port: u16,
34         rpc_user: String,
35         rpc_password: String,
36         fees: Arc<HashMap<ConfirmationTarget, AtomicU32>>,
37         handle: tokio::runtime::Handle,
38         logger: Arc<FilesystemLogger>,
39 }
40
41 impl BlockSource for BitcoindClient {
42         fn get_header<'a>(
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 })
46         }
47
48         fn get_block<'a>(
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 })
52         }
53
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 })
56         }
57 }
58
59 /// The minimum feerate we are allowed to send, as specify by LDK.
60 const MIN_FEERATE: u32 = 253;
61
62 impl BitcoindClient {
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);
68                 let rpc_credentials =
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![])
73                         .await
74                         .map_err(|_| {
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")
77                         })?;
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));
83                 let client = Self {
84                         bitcoind_rpc_client: Arc::new(bitcoind_rpc_client),
85                         host,
86                         port,
87                         rpc_user,
88                         rpc_password,
89                         fees: Arc::new(fees),
90                         handle: handle.clone(),
91                         logger,
92                 };
93                 BitcoindClient::poll_for_fee_estimates(
94                         client.fees.clone(),
95                         client.bitcoind_rpc_client.clone(),
96                         handle,
97                 );
98                 Ok(client)
99         }
100
101         fn poll_for_fee_estimates(
102                 fees: Arc<HashMap<ConfirmationTarget, AtomicU32>>, rpc_client: Arc<RpcClient>,
103                 handle: tokio::runtime::Handle,
104         ) {
105                 handle.spawn(async move {
106                         loop {
107                                 let mempoolmin_estimate = {
108                                         let resp = rpc_client
109                                                 .call_method::<MempoolMinFeeResponse>("getmempoolinfo", &vec![])
110                                                 .await
111                                                 .unwrap();
112                                         match resp.feerate_sat_per_kw {
113                                                 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
114                                                 None => MIN_FEERATE,
115                                         }
116                                 };
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>(
122                                                         "estimatesmartfee",
123                                                         &vec![background_conf_target, background_estimate_mode],
124                                                 )
125                                                 .await
126                                                 .unwrap();
127                                         match resp.feerate_sat_per_kw {
128                                                 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
129                                                 None => MIN_FEERATE,
130                                         }
131                                 };
132
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>(
138                                                         "estimatesmartfee",
139                                                         &vec![normal_conf_target, normal_estimate_mode],
140                                                 )
141                                                 .await
142                                                 .unwrap();
143                                         match resp.feerate_sat_per_kw {
144                                                 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
145                                                 None => 2000,
146                                         }
147                                 };
148
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>(
154                                                         "estimatesmartfee",
155                                                         &vec![high_prio_conf_target, high_prio_estimate_mode],
156                                                 )
157                                                 .await
158                                                 .unwrap();
159
160                                         match resp.feerate_sat_per_kw {
161                                                 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
162                                                 None => 5000,
163                                         }
164                                 };
165
166                                 fees.get(&ConfirmationTarget::MempoolMinimum)
167                                         .unwrap()
168                                         .store(mempoolmin_estimate, Ordering::Release);
169                                 fees.get(&ConfirmationTarget::Background)
170                                         .unwrap()
171                                         .store(background_estimate, Ordering::Release);
172                                 fees.get(&ConfirmationTarget::Normal)
173                                         .unwrap()
174                                         .store(normal_estimate, Ordering::Release);
175                                 fees.get(&ConfirmationTarget::HighPriority)
176                                         .unwrap()
177                                         .store(high_prio_estimate, Ordering::Release);
178                                 tokio::time::sleep(Duration::from_secs(60)).await;
179                         }
180                 });
181         }
182
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)
188         }
189
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],
196                         )
197                         .await
198                         .unwrap()
199         }
200
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,
214                 });
215                 self.bitcoind_rpc_client
216                         .call_method("fundrawtransaction", &[raw_tx_json, options])
217                         .await
218                         .unwrap()
219         }
220
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])
225                         .await
226                         .unwrap();
227         }
228
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])
233                         .await
234                         .unwrap()
235         }
236
237         pub async fn get_new_address(&self) -> Address {
238                 let addr_args = vec![serde_json::json!("LDK output address")];
239                 let addr = self
240                         .bitcoind_rpc_client
241                         .call_method::<NewAddress>("getnewaddress", &addr_args)
242                         .await
243                         .unwrap();
244                 Address::from_str(addr.0.as_str()).unwrap()
245         }
246
247         pub async fn get_blockchain_info(&self) -> BlockchainInfo {
248                 self.bitcoind_rpc_client
249                         .call_method::<BlockchainInfo>("getblockchaininfo", &vec![])
250                         .await
251                         .unwrap()
252         }
253
254         pub async fn list_unspent(&self) -> ListUnspentResponse {
255                 self.bitcoind_rpc_client
256                         .call_method::<ListUnspentResponse>("listunspent", &vec![])
257                         .await
258                         .unwrap()
259         }
260 }
261
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)
265         }
266 }
267
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.
272                 for tx in txs {
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])
282                                         .await
283                                         {
284                                                 Ok(_) => {}
285                                                 Err(e) => {
286                                                         let err_str = e.get_ref().unwrap().to_string();
287                                                         log_error!(logger,
288                                                                            "Warning, failed to broadcast a transaction, this is likely okay but may indicate an error: {}\nTransaction: {}",
289                                                                            err_str,
290                                                                            tx_serialized);
291                                                         print!("Warning, failed to broadcast a transaction, this is likely okay but may indicate an error: {}\n> ", err_str);
292                                                 }
293                                         }
294                         });
295                 }
296         }
297 }
298
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.
302                 todo!();
303         }
304 }
305
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
310                 });
311                 Ok(utxos
312                         .into_iter()
313                         .filter_map(|utxo| {
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))
319                                                         .ok(),
320                                                 // TODO: Add `Utxo::new_v1_p2tr` upstream.
321                                                 WitnessVersion::V1 => XOnlyPublicKey::from_slice(program)
322                                                         .map(|_| Utxo {
323                                                                 outpoint,
324                                                                 output: TxOut {
325                                                                         value: utxo.amount,
326                                                                         script_pubkey: Script::new_witness_program(version, program),
327                                                                 },
328                                                                 satisfaction_weight: 1 /* empty script_sig */ * WITNESS_SCALE_FACTOR as u64 +
329                                                                         1 /* witness items */ + 1 /* schnorr sig len */ + 64, /* schnorr sig */
330                                                         })
331                                                         .ok(),
332                                                 _ => None,
333                                         },
334                                         _ => None,
335                                 }
336                         })
337                         .collect())
338         }
339
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() }))
343                 })
344         }
345
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 })
352                 });
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(|_| ())
355         }
356 }