17ea74c1e4e8b644487a7ecd12c84a141d81f609
[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::OnChainSweep, AtomicU32::new(5000));
79                 fees.insert(
80                         ConfirmationTarget::MaxAllowedNonAnchorChannelRemoteFee,
81                         AtomicU32::new(25 * 250),
82                 );
83                 fees.insert(
84                         ConfirmationTarget::MinAllowedAnchorChannelRemoteFee,
85                         AtomicU32::new(MIN_FEERATE),
86                 );
87                 fees.insert(
88                         ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee,
89                         AtomicU32::new(MIN_FEERATE),
90                 );
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));
94
95                 let client = Self {
96                         bitcoind_rpc_client: Arc::new(bitcoind_rpc_client),
97                         host,
98                         port,
99                         rpc_user,
100                         rpc_password,
101                         fees: Arc::new(fees),
102                         handle: handle.clone(),
103                         logger,
104                 };
105                 BitcoindClient::poll_for_fee_estimates(
106                         client.fees.clone(),
107                         client.bitcoind_rpc_client.clone(),
108                         handle,
109                 );
110                 Ok(client)
111         }
112
113         fn poll_for_fee_estimates(
114                 fees: Arc<HashMap<ConfirmationTarget, AtomicU32>>, rpc_client: Arc<RpcClient>,
115                 handle: tokio::runtime::Handle,
116         ) {
117                 handle.spawn(async move {
118                         loop {
119                                 let mempoolmin_estimate = {
120                                         let resp = rpc_client
121                                                 .call_method::<MempoolMinFeeResponse>("getmempoolinfo", &vec![])
122                                                 .await
123                                                 .unwrap();
124                                         match resp.feerate_sat_per_kw {
125                                                 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
126                                                 None => MIN_FEERATE,
127                                         }
128                                 };
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>(
134                                                         "estimatesmartfee",
135                                                         &vec![background_conf_target, background_estimate_mode],
136                                                 )
137                                                 .await
138                                                 .unwrap();
139                                         match resp.feerate_sat_per_kw {
140                                                 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
141                                                 None => MIN_FEERATE,
142                                         }
143                                 };
144
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>(
150                                                         "estimatesmartfee",
151                                                         &vec![normal_conf_target, normal_estimate_mode],
152                                                 )
153                                                 .await
154                                                 .unwrap();
155                                         match resp.feerate_sat_per_kw {
156                                                 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
157                                                 None => 2000,
158                                         }
159                                 };
160
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>(
166                                                         "estimatesmartfee",
167                                                         &vec![high_prio_conf_target, high_prio_estimate_mode],
168                                                 )
169                                                 .await
170                                                 .unwrap();
171
172                                         match resp.feerate_sat_per_kw {
173                                                 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
174                                                 None => 5000,
175                                         }
176                                 };
177
178                                 fees.get(&ConfirmationTarget::OnChainSweep)
179                                         .unwrap()
180                                         .store(high_prio_estimate, Ordering::Release);
181                                 fees.get(&ConfirmationTarget::MaxAllowedNonAnchorChannelRemoteFee)
182                                         .unwrap()
183                                         .store(std::cmp::max(25 * 250, high_prio_estimate * 10), Ordering::Release);
184                                 fees.get(&ConfirmationTarget::MinAllowedAnchorChannelRemoteFee)
185                                         .unwrap()
186                                         .store(mempoolmin_estimate, Ordering::Release);
187                                 fees.get(&ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee)
188                                         .unwrap()
189                                         .store(background_estimate - 250, Ordering::Release);
190                                 fees.get(&ConfirmationTarget::AnchorChannelFee)
191                                         .unwrap()
192                                         .store(background_estimate, Ordering::Release);
193                                 fees.get(&ConfirmationTarget::NonAnchorChannelFee)
194                                         .unwrap()
195                                         .store(normal_estimate, Ordering::Release);
196                                 fees.get(&ConfirmationTarget::ChannelCloseMinimum)
197                                         .unwrap()
198                                         .store(background_estimate, Ordering::Release);
199
200                                 tokio::time::sleep(Duration::from_secs(60)).await;
201                         }
202                 });
203         }
204
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)
210         }
211
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],
218                         )
219                         .await
220                         .unwrap()
221         }
222
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.
229                         "fee_rate": self
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,
237                 });
238                 self.bitcoind_rpc_client
239                         .call_method("fundrawtransaction", &[raw_tx_json, options])
240                         .await
241                         .unwrap()
242         }
243
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])
248                         .await
249                         .unwrap();
250         }
251
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])
256                         .await
257                         .unwrap()
258         }
259
260         pub async fn get_new_address(&self) -> Address {
261                 let addr_args = vec![serde_json::json!("LDK output address")];
262                 let addr = self
263                         .bitcoind_rpc_client
264                         .call_method::<NewAddress>("getnewaddress", &addr_args)
265                         .await
266                         .unwrap();
267                 Address::from_str(addr.0.as_str()).unwrap()
268         }
269
270         pub async fn get_blockchain_info(&self) -> BlockchainInfo {
271                 self.bitcoind_rpc_client
272                         .call_method::<BlockchainInfo>("getblockchaininfo", &vec![])
273                         .await
274                         .unwrap()
275         }
276
277         pub async fn list_unspent(&self) -> ListUnspentResponse {
278                 self.bitcoind_rpc_client
279                         .call_method::<ListUnspentResponse>("listunspent", &vec![])
280                         .await
281                         .unwrap()
282         }
283 }
284
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)
288         }
289 }
290
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.
295                 for tx in txs {
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])
305                                         .await
306                                         {
307                                                 Ok(_) => {}
308                                                 Err(e) => {
309                                                         let err_str = e.get_ref().unwrap().to_string();
310                                                         log_error!(logger,
311                                                                            "Warning, failed to broadcast a transaction, this is likely okay but may indicate an error: {}\nTransaction: {}",
312                                                                            err_str,
313                                                                            tx_serialized);
314                                                         print!("Warning, failed to broadcast a transaction, this is likely okay but may indicate an error: {}\n> ", err_str);
315                                                 }
316                                         }
317                         });
318                 }
319         }
320 }
321
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
326                 });
327                 Ok(utxos
328                         .into_iter()
329                         .filter_map(|utxo| {
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))
335                                                         .ok(),
336                                                 // TODO: Add `Utxo::new_v1_p2tr` upstream.
337                                                 WitnessVersion::V1 => XOnlyPublicKey::from_slice(program)
338                                                         .map(|_| Utxo {
339                                                                 outpoint,
340                                                                 output: TxOut {
341                                                                         value: utxo.amount,
342                                                                         script_pubkey: Script::new_witness_program(version, program),
343                                                                 },
344                                                                 satisfaction_weight: 1 /* empty script_sig */ * WITNESS_SCALE_FACTOR as u64 +
345                                                                         1 /* witness items */ + 1 /* schnorr sig len */ + 64, /* schnorr sig */
346                                                         })
347                                                         .ok(),
348                                                 _ => None,
349                                         },
350                                         _ => None,
351                                 }
352                         })
353                         .collect())
354         }
355
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() }))
359                 })
360         }
361
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 })
368                 });
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(|_| ())
371         }
372 }