67b42ef6c5a82b69aad12e10110ed8d4f989a2d4
[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::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};
22 use serde_json;
23 use std::collections::HashMap;
24 use std::str::FromStr;
25 use std::sync::atomic::{AtomicU32, Ordering};
26 use std::sync::Arc;
27 use std::time::Duration;
28
29 pub struct BitcoindClient {
30         pub(crate) bitcoind_rpc_client: Arc<RpcClient>,
31         host: String,
32         port: u16,
33         rpc_user: String,
34         rpc_password: String,
35         fees: Arc<HashMap<ConfirmationTarget, AtomicU32>>,
36         handle: tokio::runtime::Handle,
37         logger: Arc<FilesystemLogger>,
38 }
39
40 impl BlockSource for BitcoindClient {
41         fn get_header<'a>(
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 })
45         }
46
47         fn get_block<'a>(
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 })
51         }
52
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 })
55         }
56 }
57
58 /// The minimum feerate we are allowed to send, as specify by LDK.
59 const MIN_FEERATE: u32 = 253;
60
61 impl BitcoindClient {
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);
67                 let rpc_credentials =
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![])
72                         .await
73                         .map_err(|_| {
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")
76                         })?;
77                 let mut fees: HashMap<ConfirmationTarget, AtomicU32> = HashMap::new();
78                 fees.insert(ConfirmationTarget::MempoolMinimum, AtomicU32::new(MIN_FEERATE));
79                 fees.insert(ConfirmationTarget::Background, AtomicU32::new(MIN_FEERATE));
80                 fees.insert(ConfirmationTarget::Normal, AtomicU32::new(2000));
81                 fees.insert(ConfirmationTarget::HighPriority, AtomicU32::new(5000));
82                 let client = Self {
83                         bitcoind_rpc_client: Arc::new(bitcoind_rpc_client),
84                         host,
85                         port,
86                         rpc_user,
87                         rpc_password,
88                         fees: Arc::new(fees),
89                         handle: handle.clone(),
90                         logger,
91                 };
92                 BitcoindClient::poll_for_fee_estimates(
93                         client.fees.clone(),
94                         client.bitcoind_rpc_client.clone(),
95                         handle,
96                 );
97                 Ok(client)
98         }
99
100         fn poll_for_fee_estimates(
101                 fees: Arc<HashMap<ConfirmationTarget, AtomicU32>>, rpc_client: Arc<RpcClient>,
102                 handle: tokio::runtime::Handle,
103         ) {
104                 handle.spawn(async move {
105                         loop {
106                                 let mempoolmin_estimate = {
107                                         let resp = rpc_client
108                                                 .call_method::<MempoolMinFeeResponse>("getmempoolinfo", &vec![])
109                                                 .await
110                                                 .unwrap();
111                                         match resp.feerate_sat_per_kw {
112                                                 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
113                                                 None => MIN_FEERATE,
114                                         }
115                                 };
116                                 let background_estimate = {
117                                         let background_conf_target = serde_json::json!(144);
118                                         let background_estimate_mode = serde_json::json!("ECONOMICAL");
119                                         let resp = rpc_client
120                                                 .call_method::<FeeResponse>(
121                                                         "estimatesmartfee",
122                                                         &vec![background_conf_target, background_estimate_mode],
123                                                 )
124                                                 .await
125                                                 .unwrap();
126                                         match resp.feerate_sat_per_kw {
127                                                 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
128                                                 None => MIN_FEERATE,
129                                         }
130                                 };
131
132                                 let normal_estimate = {
133                                         let normal_conf_target = serde_json::json!(18);
134                                         let normal_estimate_mode = serde_json::json!("ECONOMICAL");
135                                         let resp = rpc_client
136                                                 .call_method::<FeeResponse>(
137                                                         "estimatesmartfee",
138                                                         &vec![normal_conf_target, normal_estimate_mode],
139                                                 )
140                                                 .await
141                                                 .unwrap();
142                                         match resp.feerate_sat_per_kw {
143                                                 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
144                                                 None => 2000,
145                                         }
146                                 };
147
148                                 let high_prio_estimate = {
149                                         let high_prio_conf_target = serde_json::json!(6);
150                                         let high_prio_estimate_mode = serde_json::json!("CONSERVATIVE");
151                                         let resp = rpc_client
152                                                 .call_method::<FeeResponse>(
153                                                         "estimatesmartfee",
154                                                         &vec![high_prio_conf_target, high_prio_estimate_mode],
155                                                 )
156                                                 .await
157                                                 .unwrap();
158
159                                         match resp.feerate_sat_per_kw {
160                                                 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
161                                                 None => 5000,
162                                         }
163                                 };
164
165                                 fees.get(&ConfirmationTarget::MempoolMinimum)
166                                         .unwrap()
167                                         .store(mempoolmin_estimate, Ordering::Release);
168                                 fees.get(&ConfirmationTarget::Background)
169                                         .unwrap()
170                                         .store(background_estimate, Ordering::Release);
171                                 fees.get(&ConfirmationTarget::Normal)
172                                         .unwrap()
173                                         .store(normal_estimate, Ordering::Release);
174                                 fees.get(&ConfirmationTarget::HighPriority)
175                                         .unwrap()
176                                         .store(high_prio_estimate, Ordering::Release);
177                                 tokio::time::sleep(Duration::from_secs(60)).await;
178                         }
179                 });
180         }
181
182         pub fn get_new_rpc_client(&self) -> std::io::Result<RpcClient> {
183                 let http_endpoint = HttpEndpoint::for_host(self.host.clone()).with_port(self.port);
184                 let rpc_credentials =
185                         base64::encode(format!("{}:{}", self.rpc_user.clone(), self.rpc_password.clone()));
186                 RpcClient::new(&rpc_credentials, http_endpoint)
187         }
188
189         pub async fn create_raw_transaction(&self, outputs: Vec<HashMap<String, f64>>) -> RawTx {
190                 let outputs_json = serde_json::json!(outputs);
191                 self.bitcoind_rpc_client
192                         .call_method::<RawTx>(
193                                 "createrawtransaction",
194                                 &vec![serde_json::json!([]), outputs_json],
195                         )
196                         .await
197                         .unwrap()
198         }
199
200         pub async fn fund_raw_transaction(&self, raw_tx: RawTx) -> FundedTx {
201                 let raw_tx_json = serde_json::json!(raw_tx.0);
202                 let options = serde_json::json!({
203                         // LDK gives us feerates in satoshis per KW but Bitcoin Core here expects fees
204                         // denominated in satoshis per vB. First we need to multiply by 4 to convert weight
205                         // units to virtual bytes, then divide by 1000 to convert KvB to vB.
206                         "fee_rate": self.get_est_sat_per_1000_weight(ConfirmationTarget::Normal) as f64 / 250.0,
207                         // While users could "cancel" a channel open by RBF-bumping and paying back to
208                         // themselves, we don't allow it here as its easy to have users accidentally RBF bump
209                         // and pay to the channel funding address, which results in loss of funds. Real
210                         // LDK-based applications should enable RBF bumping and RBF bump either to a local
211                         // change address or to a new channel output negotiated with the same node.
212                         "replaceable": false,
213                 });
214                 self.bitcoind_rpc_client
215                         .call_method("fundrawtransaction", &[raw_tx_json, options])
216                         .await
217                         .unwrap()
218         }
219
220         pub async fn send_raw_transaction(&self, raw_tx: RawTx) {
221                 let raw_tx_json = serde_json::json!(raw_tx.0);
222                 self.bitcoind_rpc_client
223                         .call_method::<Txid>("sendrawtransaction", &[raw_tx_json])
224                         .await
225                         .unwrap();
226         }
227
228         pub async fn sign_raw_transaction_with_wallet(&self, tx_hex: String) -> SignedTx {
229                 let tx_hex_json = serde_json::json!(tx_hex);
230                 self.bitcoind_rpc_client
231                         .call_method("signrawtransactionwithwallet", &vec![tx_hex_json])
232                         .await
233                         .unwrap()
234         }
235
236         pub async fn get_new_address(&self) -> Address {
237                 let addr_args = vec![serde_json::json!("LDK output address")];
238                 let addr = self
239                         .bitcoind_rpc_client
240                         .call_method::<NewAddress>("getnewaddress", &addr_args)
241                         .await
242                         .unwrap();
243                 Address::from_str(addr.0.as_str()).unwrap()
244         }
245
246         pub async fn get_blockchain_info(&self) -> BlockchainInfo {
247                 self.bitcoind_rpc_client
248                         .call_method::<BlockchainInfo>("getblockchaininfo", &vec![])
249                         .await
250                         .unwrap()
251         }
252
253         pub async fn list_unspent(&self) -> ListUnspentResponse {
254                 self.bitcoind_rpc_client
255                         .call_method::<ListUnspentResponse>("listunspent", &vec![])
256                         .await
257                         .unwrap()
258         }
259 }
260
261 impl FeeEstimator for BitcoindClient {
262         fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u32 {
263                 self.fees.get(&confirmation_target).unwrap().load(Ordering::Acquire)
264         }
265 }
266
267 impl BroadcasterInterface for BitcoindClient {
268         fn broadcast_transactions(&self, txs: &[&Transaction]) {
269                 // TODO: Rather than calling `sendrawtransaction` in a a loop, we should probably use
270                 // `submitpackage` once it becomes available.
271                 for tx in txs {
272                         let bitcoind_rpc_client = Arc::clone(&self.bitcoind_rpc_client);
273                         let tx_serialized = encode::serialize_hex(tx);
274                         let tx_json = serde_json::json!(tx_serialized);
275                         let logger = Arc::clone(&self.logger);
276                         self.handle.spawn(async move {
277                                 // This may error due to RL calling `broadcast_transactions` with the same transaction
278                                 // multiple times, but the error is safe to ignore.
279                                 match bitcoind_rpc_client
280                                         .call_method::<Txid>("sendrawtransaction", &vec![tx_json])
281                                         .await
282                                         {
283                                                 Ok(_) => {}
284                                                 Err(e) => {
285                                                         let err_str = e.get_ref().unwrap().to_string();
286                                                         log_error!(logger,
287                                                                            "Warning, failed to broadcast a transaction, this is likely okay but may indicate an error: {}\nTransaction: {}",
288                                                                            err_str,
289                                                                            tx_serialized);
290                                                         print!("Warning, failed to broadcast a transaction, this is likely okay but may indicate an error: {}\n> ", err_str);
291                                                 }
292                                         }
293                         });
294                 }
295         }
296 }
297
298 impl WalletSource for BitcoindClient {
299         fn list_confirmed_utxos(&self) -> Result<Vec<Utxo>, ()> {
300                 let utxos = tokio::task::block_in_place(move || {
301                         self.handle.block_on(async move { self.list_unspent().await }).0
302                 });
303                 Ok(utxos
304                         .into_iter()
305                         .filter_map(|utxo| {
306                                 let outpoint = OutPoint { txid: utxo.txid, vout: utxo.vout };
307                                 match utxo.address.payload {
308                                         Payload::WitnessProgram { version, ref program } => match version {
309                                                 WitnessVersion::V0 => WPubkeyHash::from_slice(program)
310                                                         .map(|wpkh| Utxo::new_v0_p2wpkh(outpoint, utxo.amount, &wpkh))
311                                                         .ok(),
312                                                 // TODO: Add `Utxo::new_v1_p2tr` upstream.
313                                                 WitnessVersion::V1 => XOnlyPublicKey::from_slice(program)
314                                                         .map(|_| Utxo {
315                                                                 outpoint,
316                                                                 output: TxOut {
317                                                                         value: utxo.amount,
318                                                                         script_pubkey: Script::new_witness_program(version, program),
319                                                                 },
320                                                                 satisfaction_weight: 1 /* empty script_sig */ * WITNESS_SCALE_FACTOR as u64 +
321                                                                         1 /* witness items */ + 1 /* schnorr sig len */ + 64, /* schnorr sig */
322                                                         })
323                                                         .ok(),
324                                                 _ => None,
325                                         },
326                                         _ => None,
327                                 }
328                         })
329                         .collect())
330         }
331
332         fn get_change_script(&self) -> Result<Script, ()> {
333                 tokio::task::block_in_place(move || {
334                         Ok(self.handle.block_on(async move { self.get_new_address().await.script_pubkey() }))
335                 })
336         }
337
338         fn sign_tx(&self, tx: Transaction) -> Result<Transaction, ()> {
339                 let mut tx_bytes = Vec::new();
340                 let _ = tx.consensus_encode(&mut tx_bytes).map_err(|_| ());
341                 let tx_hex = hex_utils::hex_str(&tx_bytes);
342                 let signed_tx = tokio::task::block_in_place(move || {
343                         self.handle.block_on(async move { self.sign_raw_transaction_with_wallet(tx_hex).await })
344                 });
345                 let signed_tx_bytes = hex_utils::to_vec(&signed_tx.hex).ok_or(())?;
346                 Transaction::consensus_decode(&mut signed_tx_bytes.as_slice()).map_err(|_| ())
347         }
348 }