c00f52fb752cdd033e69c9cc60085a213db6fec2
[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::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};
25 use serde_json;
26 use std::collections::HashMap;
27 use std::str::FromStr;
28 use std::sync::atomic::{AtomicU32, Ordering};
29 use std::sync::Arc;
30 use std::time::Duration;
31
32 pub struct BitcoindClient {
33         pub(crate) bitcoind_rpc_client: Arc<RpcClient>,
34         network: Network,
35         host: String,
36         port: u16,
37         rpc_user: String,
38         rpc_password: String,
39         fees: Arc<HashMap<ConfirmationTarget, AtomicU32>>,
40         handle: tokio::runtime::Handle,
41         logger: Arc<FilesystemLogger>,
42 }
43
44 impl BlockSource for BitcoindClient {
45         fn get_header<'a>(
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 })
49         }
50
51         fn get_block<'a>(
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 })
55         }
56
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 })
59         }
60 }
61
62 /// The minimum feerate we are allowed to send, as specify by LDK.
63 const MIN_FEERATE: u32 = 253;
64
65 impl BitcoindClient {
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);
71                 let rpc_credentials =
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![])
76                         .await
77                         .map_err(|_| {
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")
80                         })?;
81                 let mut fees: HashMap<ConfirmationTarget, AtomicU32> = HashMap::new();
82                 fees.insert(ConfirmationTarget::OnChainSweep, AtomicU32::new(5000));
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                         network,
102                         fees: Arc::new(fees),
103                         handle: handle.clone(),
104                         logger,
105                 };
106                 BitcoindClient::poll_for_fee_estimates(
107                         client.fees.clone(),
108                         client.bitcoind_rpc_client.clone(),
109                         handle,
110                 );
111                 Ok(client)
112         }
113
114         fn poll_for_fee_estimates(
115                 fees: Arc<HashMap<ConfirmationTarget, AtomicU32>>, rpc_client: Arc<RpcClient>,
116                 handle: tokio::runtime::Handle,
117         ) {
118                 handle.spawn(async move {
119                         loop {
120                                 let mempoolmin_estimate = {
121                                         let resp = rpc_client
122                                                 .call_method::<MempoolMinFeeResponse>("getmempoolinfo", &vec![])
123                                                 .await
124                                                 .unwrap();
125                                         match resp.feerate_sat_per_kw {
126                                                 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
127                                                 None => MIN_FEERATE,
128                                         }
129                                 };
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>(
135                                                         "estimatesmartfee",
136                                                         &vec![background_conf_target, background_estimate_mode],
137                                                 )
138                                                 .await
139                                                 .unwrap();
140                                         match resp.feerate_sat_per_kw {
141                                                 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
142                                                 None => MIN_FEERATE,
143                                         }
144                                 };
145
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>(
151                                                         "estimatesmartfee",
152                                                         &vec![normal_conf_target, normal_estimate_mode],
153                                                 )
154                                                 .await
155                                                 .unwrap();
156                                         match resp.feerate_sat_per_kw {
157                                                 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
158                                                 None => 2000,
159                                         }
160                                 };
161
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>(
167                                                         "estimatesmartfee",
168                                                         &vec![high_prio_conf_target, high_prio_estimate_mode],
169                                                 )
170                                                 .await
171                                                 .unwrap();
172
173                                         match resp.feerate_sat_per_kw {
174                                                 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
175                                                 None => 5000,
176                                         }
177                                 };
178
179                                 fees.get(&ConfirmationTarget::OnChainSweep)
180                                         .unwrap()
181                                         .store(high_prio_estimate, Ordering::Release);
182                                 fees.get(&ConfirmationTarget::MinAllowedAnchorChannelRemoteFee)
183                                         .unwrap()
184                                         .store(mempoolmin_estimate, Ordering::Release);
185                                 fees.get(&ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee)
186                                         .unwrap()
187                                         .store(background_estimate - 250, Ordering::Release);
188                                 fees.get(&ConfirmationTarget::AnchorChannelFee)
189                                         .unwrap()
190                                         .store(background_estimate, Ordering::Release);
191                                 fees.get(&ConfirmationTarget::NonAnchorChannelFee)
192                                         .unwrap()
193                                         .store(normal_estimate, Ordering::Release);
194                                 fees.get(&ConfirmationTarget::ChannelCloseMinimum)
195                                         .unwrap()
196                                         .store(background_estimate, Ordering::Release);
197
198                                 tokio::time::sleep(Duration::from_secs(60)).await;
199                         }
200                 });
201         }
202
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)
208         }
209
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],
216                         )
217                         .await
218                         .unwrap()
219         }
220
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.
227                         "fee_rate": self
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,
235                 });
236                 self.bitcoind_rpc_client
237                         .call_method("fundrawtransaction", &[raw_tx_json, options])
238                         .await
239                         .unwrap()
240         }
241
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])
246                         .await
247                         .unwrap();
248         }
249
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])
254                         .await
255                         .unwrap()
256         }
257
258         pub async fn get_new_address(&self) -> Address {
259                 let addr_args = vec![serde_json::json!("LDK output address")];
260                 let addr = self
261                         .bitcoind_rpc_client
262                         .call_method::<NewAddress>("getnewaddress", &addr_args)
263                         .await
264                         .unwrap();
265                 Address::from_str(addr.0.as_str()).unwrap().require_network(self.network).unwrap()
266         }
267
268         pub async fn get_blockchain_info(&self) -> BlockchainInfo {
269                 self.bitcoind_rpc_client
270                         .call_method::<BlockchainInfo>("getblockchaininfo", &vec![])
271                         .await
272                         .unwrap()
273         }
274
275         pub async fn list_unspent(&self) -> ListUnspentResponse {
276                 self.bitcoind_rpc_client
277                         .call_method::<ListUnspentResponse>("listunspent", &vec![])
278                         .await
279                         .unwrap()
280         }
281 }
282
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)
286         }
287 }
288
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.
293                 for tx in txs {
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])
303                                         .await
304                                         {
305                                                 Ok(_) => {}
306                                                 Err(e) => {
307                                                         let err_str = e.get_ref().unwrap().to_string();
308                                                         log_error!(logger,
309                                                                            "Warning, failed to broadcast a transaction, this is likely okay but may indicate an error: {}\nTransaction: {}",
310                                                                            err_str,
311                                                                            tx_serialized);
312                                                         print!("Warning, failed to broadcast a transaction, this is likely okay but may indicate an error: {}\n> ", err_str);
313                                                 }
314                                         }
315                         });
316                 }
317         }
318 }
319
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
324                 });
325                 Ok(utxos
326                         .into_iter()
327                         .filter_map(|utxo| {
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))
333                                                         .ok(),
334                                                 // TODO: Add `Utxo::new_v1_p2tr` upstream.
335                                                 WitnessVersion::V1 => XOnlyPublicKey::from_slice(wp.program().as_bytes())
336                                                         .map(|_| Utxo {
337                                                                 outpoint,
338                                                                 output: TxOut {
339                                                                         value: utxo.amount,
340                                                                         script_pubkey: ScriptBuf::new_witness_program(&wp),
341                                                                 },
342                                                                 satisfaction_weight: 1 /* empty script_sig */ * WITNESS_SCALE_FACTOR as u64 +
343                                                                         1 /* witness items */ + 1 /* schnorr sig len */ + 64, /* schnorr sig */
344                                                         })
345                                                         .ok(),
346                                                 _ => None,
347                                         },
348                                         _ => None,
349                                 }
350                         })
351                         .collect())
352         }
353
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() }))
357                 })
358         }
359
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 })
366                 });
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(|_| ())
369         }
370 }