Merge pull request #107 from tnull/2023-07-upgrade-to-0.0.116
[ldk-sample] / src / bitcoind_client.rs
1 use crate::convert::{
2         BlockchainInfo, FeeResponse, FundedTx, MempoolMinFeeResponse, NewAddress, RawTx, SignedTx,
3 };
4 use crate::disk::FilesystemLogger;
5 use base64;
6 use bitcoin::blockdata::transaction::Transaction;
7 use bitcoin::consensus::encode;
8 use bitcoin::hash_types::{BlockHash, Txid};
9 use bitcoin::util::address::Address;
10 use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
11 use lightning::log_error;
12 use lightning::routing::utxo::{UtxoLookup, UtxoResult};
13 use lightning::util::logger::Logger;
14 use lightning_block_sync::http::HttpEndpoint;
15 use lightning_block_sync::rpc::RpcClient;
16 use lightning_block_sync::{AsyncBlockSourceResult, BlockData, BlockHeaderData, BlockSource};
17 use serde_json;
18 use std::collections::HashMap;
19 use std::str::FromStr;
20 use std::sync::atomic::{AtomicU32, Ordering};
21 use std::sync::Arc;
22 use std::time::Duration;
23
24 pub struct BitcoindClient {
25         bitcoind_rpc_client: Arc<RpcClient>,
26         host: String,
27         port: u16,
28         rpc_user: String,
29         rpc_password: String,
30         fees: Arc<HashMap<Target, AtomicU32>>,
31         handle: tokio::runtime::Handle,
32         logger: Arc<FilesystemLogger>,
33 }
34
35 #[derive(Clone, Eq, Hash, PartialEq)]
36 pub enum Target {
37         MempoolMinimum,
38         Background,
39         Normal,
40         HighPriority,
41 }
42
43 impl BlockSource for BitcoindClient {
44         fn get_header<'a>(
45                 &'a self, header_hash: &'a BlockHash, height_hint: Option<u32>,
46         ) -> AsyncBlockSourceResult<'a, BlockHeaderData> {
47                 Box::pin(async move { self.bitcoind_rpc_client.get_header(header_hash, height_hint).await })
48         }
49
50         fn get_block<'a>(
51                 &'a self, header_hash: &'a BlockHash,
52         ) -> AsyncBlockSourceResult<'a, BlockData> {
53                 Box::pin(async move { self.bitcoind_rpc_client.get_block(header_hash).await })
54         }
55
56         fn get_best_block<'a>(&'a self) -> AsyncBlockSourceResult<(BlockHash, Option<u32>)> {
57                 Box::pin(async move { self.bitcoind_rpc_client.get_best_block().await })
58         }
59 }
60
61 /// The minimum feerate we are allowed to send, as specify by LDK.
62 const MIN_FEERATE: u32 = 253;
63
64 impl BitcoindClient {
65         pub(crate) async fn new(
66                 host: String, port: u16, rpc_user: String, rpc_password: String,
67                 handle: tokio::runtime::Handle, logger: Arc<FilesystemLogger>,
68         ) -> std::io::Result<Self> {
69                 let http_endpoint = HttpEndpoint::for_host(host.clone()).with_port(port);
70                 let rpc_credentials =
71                         base64::encode(format!("{}:{}", rpc_user.clone(), rpc_password.clone()));
72                 let bitcoind_rpc_client = RpcClient::new(&rpc_credentials, http_endpoint)?;
73                 let _dummy = bitcoind_rpc_client
74                         .call_method::<BlockchainInfo>("getblockchaininfo", &vec![])
75                         .await
76                         .map_err(|_| {
77                                 std::io::Error::new(std::io::ErrorKind::PermissionDenied,
78                                 "Failed to make initial call to bitcoind - please check your RPC user/password and access settings")
79                         })?;
80                 let mut fees: HashMap<Target, AtomicU32> = HashMap::new();
81                 fees.insert(Target::MempoolMinimum, AtomicU32::new(MIN_FEERATE));
82                 fees.insert(Target::Background, AtomicU32::new(MIN_FEERATE));
83                 fees.insert(Target::Normal, AtomicU32::new(2000));
84                 fees.insert(Target::HighPriority, AtomicU32::new(5000));
85                 let client = Self {
86                         bitcoind_rpc_client: Arc::new(bitcoind_rpc_client),
87                         host,
88                         port,
89                         rpc_user,
90                         rpc_password,
91                         fees: Arc::new(fees),
92                         handle: handle.clone(),
93                         logger,
94                 };
95                 BitcoindClient::poll_for_fee_estimates(
96                         client.fees.clone(),
97                         client.bitcoind_rpc_client.clone(),
98                         handle,
99                 );
100                 Ok(client)
101         }
102
103         fn poll_for_fee_estimates(
104                 fees: Arc<HashMap<Target, AtomicU32>>, rpc_client: Arc<RpcClient>,
105                 handle: tokio::runtime::Handle,
106         ) {
107                 handle.spawn(async move {
108                         loop {
109                                 let mempoolmin_estimate = {
110                                         let resp = rpc_client
111                                                 .call_method::<MempoolMinFeeResponse>("getmempoolinfo", &vec![])
112                                                 .await
113                                                 .unwrap();
114                                         match resp.feerate_sat_per_kw {
115                                                 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
116                                                 None => MIN_FEERATE,
117                                         }
118                                 };
119                                 let background_estimate = {
120                                         let background_conf_target = serde_json::json!(144);
121                                         let background_estimate_mode = serde_json::json!("ECONOMICAL");
122                                         let resp = rpc_client
123                                                 .call_method::<FeeResponse>(
124                                                         "estimatesmartfee",
125                                                         &vec![background_conf_target, background_estimate_mode],
126                                                 )
127                                                 .await
128                                                 .unwrap();
129                                         match resp.feerate_sat_per_kw {
130                                                 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
131                                                 None => MIN_FEERATE,
132                                         }
133                                 };
134
135                                 let normal_estimate = {
136                                         let normal_conf_target = serde_json::json!(18);
137                                         let normal_estimate_mode = serde_json::json!("ECONOMICAL");
138                                         let resp = rpc_client
139                                                 .call_method::<FeeResponse>(
140                                                         "estimatesmartfee",
141                                                         &vec![normal_conf_target, normal_estimate_mode],
142                                                 )
143                                                 .await
144                                                 .unwrap();
145                                         match resp.feerate_sat_per_kw {
146                                                 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
147                                                 None => 2000,
148                                         }
149                                 };
150
151                                 let high_prio_estimate = {
152                                         let high_prio_conf_target = serde_json::json!(6);
153                                         let high_prio_estimate_mode = serde_json::json!("CONSERVATIVE");
154                                         let resp = rpc_client
155                                                 .call_method::<FeeResponse>(
156                                                         "estimatesmartfee",
157                                                         &vec![high_prio_conf_target, high_prio_estimate_mode],
158                                                 )
159                                                 .await
160                                                 .unwrap();
161
162                                         match resp.feerate_sat_per_kw {
163                                                 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
164                                                 None => 5000,
165                                         }
166                                 };
167
168                                 fees.get(&Target::MempoolMinimum)
169                                         .unwrap()
170                                         .store(mempoolmin_estimate, Ordering::Release);
171                                 fees.get(&Target::Background)
172                                         .unwrap()
173                                         .store(background_estimate, Ordering::Release);
174                                 fees.get(&Target::Normal).unwrap().store(normal_estimate, Ordering::Release);
175                                 fees.get(&Target::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
255 impl FeeEstimator for BitcoindClient {
256         fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u32 {
257                 match confirmation_target {
258                         ConfirmationTarget::MempoolMinimum => {
259                                 self.fees.get(&Target::MempoolMinimum).unwrap().load(Ordering::Acquire)
260                         }
261                         ConfirmationTarget::Background => {
262                                 self.fees.get(&Target::Background).unwrap().load(Ordering::Acquire)
263                         }
264                         ConfirmationTarget::Normal => {
265                                 self.fees.get(&Target::Normal).unwrap().load(Ordering::Acquire)
266                         }
267                         ConfirmationTarget::HighPriority => {
268                                 self.fees.get(&Target::HighPriority).unwrap().load(Ordering::Acquire)
269                         }
270                 }
271         }
272 }
273
274 impl BroadcasterInterface for BitcoindClient {
275         fn broadcast_transactions(&self, txs: &[&Transaction]) {
276                 // TODO: Rather than calling `sendrawtransaction` in a a loop, we should probably use
277                 // `submitpackage` once it becomes available.
278                 for tx in txs {
279                         let bitcoind_rpc_client = Arc::clone(&self.bitcoind_rpc_client);
280                         let tx_serialized = encode::serialize_hex(tx);
281                         let tx_json = serde_json::json!(tx_serialized);
282                         let logger = Arc::clone(&self.logger);
283                         self.handle.spawn(async move {
284                                 // This may error due to RL calling `broadcast_transactions` with the same transaction
285                                 // multiple times, but the error is safe to ignore.
286                                 match bitcoind_rpc_client
287                                         .call_method::<Txid>("sendrawtransaction", &vec![tx_json])
288                                         .await
289                                         {
290                                                 Ok(_) => {}
291                                                 Err(e) => {
292                                                         let err_str = e.get_ref().unwrap().to_string();
293                                                         log_error!(logger,
294                                                                            "Warning, failed to broadcast a transaction, this is likely okay but may indicate an error: {}\nTransaction: {}",
295                                                                            err_str,
296                                                                            tx_serialized);
297                                                         print!("Warning, failed to broadcast a transaction, this is likely okay but may indicate an error: {}\n> ", err_str);
298                                                 }
299                                         }
300                         });
301                 }
302         }
303 }
304
305 impl UtxoLookup for BitcoindClient {
306         fn get_utxo(&self, _genesis_hash: &BlockHash, _short_channel_id: u64) -> UtxoResult {
307                 // P2PGossipSync takes None for a UtxoLookup, so this will never be called.
308                 todo!();
309         }
310 }