Use an explicit handle when spawning RPC calls
[ldk-sample] / src / bitcoind_client.rs
1 use crate::convert::{BlockchainInfo, FeeResponse, FundedTx, NewAddress, RawTx, SignedTx};
2 use base64;
3 use bitcoin::blockdata::block::Block;
4 use bitcoin::blockdata::transaction::Transaction;
5 use bitcoin::consensus::encode;
6 use bitcoin::hash_types::{BlockHash, Txid};
7 use bitcoin::util::address::Address;
8 use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
9 use lightning_block_sync::http::HttpEndpoint;
10 use lightning_block_sync::rpc::RpcClient;
11 use lightning_block_sync::{AsyncBlockSourceResult, BlockHeaderData, BlockSource};
12 use serde_json;
13 use std::collections::HashMap;
14 use std::str::FromStr;
15 use std::sync::atomic::{AtomicU32, Ordering};
16 use std::sync::Arc;
17 use std::time::Duration;
18 use tokio::sync::Mutex;
19
20 pub struct BitcoindClient {
21         bitcoind_rpc_client: Arc<Mutex<RpcClient>>,
22         host: String,
23         port: u16,
24         rpc_user: String,
25         rpc_password: String,
26         fees: Arc<HashMap<Target, AtomicU32>>,
27         handle: tokio::runtime::Handle,
28 }
29
30 #[derive(Clone, Eq, Hash, PartialEq)]
31 pub enum Target {
32         Background,
33         Normal,
34         HighPriority,
35 }
36
37 impl BlockSource for &BitcoindClient {
38         fn get_header<'a>(
39                 &'a mut self, header_hash: &'a BlockHash, height_hint: Option<u32>,
40         ) -> AsyncBlockSourceResult<'a, BlockHeaderData> {
41                 Box::pin(async move {
42                         let mut rpc = self.bitcoind_rpc_client.lock().await;
43                         rpc.get_header(header_hash, height_hint).await
44                 })
45         }
46
47         fn get_block<'a>(
48                 &'a mut self, header_hash: &'a BlockHash,
49         ) -> AsyncBlockSourceResult<'a, Block> {
50                 Box::pin(async move {
51                         let mut rpc = self.bitcoind_rpc_client.lock().await;
52                         rpc.get_block(header_hash).await
53                 })
54         }
55
56         fn get_best_block<'a>(&'a mut self) -> AsyncBlockSourceResult<(BlockHash, Option<u32>)> {
57                 Box::pin(async move {
58                         let mut rpc = self.bitcoind_rpc_client.lock().await;
59                         rpc.get_best_block().await
60                 })
61         }
62 }
63
64 /// The minimum feerate we are allowed to send, as specify by LDK.
65 const MIN_FEERATE: u32 = 253;
66
67 impl BitcoindClient {
68         pub async fn new(
69                 host: String, port: u16, rpc_user: String, rpc_password: String,
70                 handle: tokio::runtime::Handle,
71         ) -> std::io::Result<Self> {
72                 let http_endpoint = HttpEndpoint::for_host(host.clone()).with_port(port);
73                 let rpc_credentials =
74                         base64::encode(format!("{}:{}", rpc_user.clone(), rpc_password.clone()));
75                 let mut bitcoind_rpc_client = RpcClient::new(&rpc_credentials, http_endpoint)?;
76                 let _dummy = bitcoind_rpc_client
77                         .call_method::<BlockchainInfo>("getblockchaininfo", &vec![])
78                         .await
79                         .map_err(|_| {
80                                 std::io::Error::new(std::io::ErrorKind::PermissionDenied,
81                                 "Failed to make initial call to bitcoind - please check your RPC user/password and access settings")
82                         })?;
83                 let mut fees: HashMap<Target, AtomicU32> = HashMap::new();
84                 fees.insert(Target::Background, AtomicU32::new(MIN_FEERATE));
85                 fees.insert(Target::Normal, AtomicU32::new(2000));
86                 fees.insert(Target::HighPriority, AtomicU32::new(5000));
87                 let client = Self {
88                         bitcoind_rpc_client: Arc::new(Mutex::new(bitcoind_rpc_client)),
89                         host,
90                         port,
91                         rpc_user,
92                         rpc_password,
93                         fees: Arc::new(fees),
94                         handle: handle.clone(),
95                 };
96                 BitcoindClient::poll_for_fee_estimates(
97                         client.fees.clone(),
98                         client.bitcoind_rpc_client.clone(),
99                         handle,
100                 );
101                 Ok(client)
102         }
103
104         fn poll_for_fee_estimates(
105                 fees: Arc<HashMap<Target, AtomicU32>>, rpc_client: Arc<Mutex<RpcClient>>,
106                 handle: tokio::runtime::Handle,
107         ) {
108                 handle.spawn(async move {
109                         loop {
110                                 let background_estimate = {
111                                         let mut rpc = rpc_client.lock().await;
112                                         let background_conf_target = serde_json::json!(144);
113                                         let background_estimate_mode = serde_json::json!("ECONOMICAL");
114                                         let resp = rpc
115                                                 .call_method::<FeeResponse>(
116                                                         "estimatesmartfee",
117                                                         &vec![background_conf_target, background_estimate_mode],
118                                                 )
119                                                 .await
120                                                 .unwrap();
121                                         match resp.feerate_sat_per_kw {
122                                                 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
123                                                 None => MIN_FEERATE,
124                                         }
125                                 };
126
127                                 let normal_estimate = {
128                                         let mut rpc = rpc_client.lock().await;
129                                         let normal_conf_target = serde_json::json!(18);
130                                         let normal_estimate_mode = serde_json::json!("ECONOMICAL");
131                                         let resp = rpc
132                                                 .call_method::<FeeResponse>(
133                                                         "estimatesmartfee",
134                                                         &vec![normal_conf_target, normal_estimate_mode],
135                                                 )
136                                                 .await
137                                                 .unwrap();
138                                         match resp.feerate_sat_per_kw {
139                                                 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
140                                                 None => 2000,
141                                         }
142                                 };
143
144                                 let high_prio_estimate = {
145                                         let mut rpc = rpc_client.lock().await;
146                                         let high_prio_conf_target = serde_json::json!(6);
147                                         let high_prio_estimate_mode = serde_json::json!("CONSERVATIVE");
148                                         let resp = rpc
149                                                 .call_method::<FeeResponse>(
150                                                         "estimatesmartfee",
151                                                         &vec![high_prio_conf_target, high_prio_estimate_mode],
152                                                 )
153                                                 .await
154                                                 .unwrap();
155
156                                         match resp.feerate_sat_per_kw {
157                                                 Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
158                                                 None => 5000,
159                                         }
160                                 };
161
162                                 fees.get(&Target::Background)
163                                         .unwrap()
164                                         .store(background_estimate, Ordering::Release);
165                                 fees.get(&Target::Normal).unwrap().store(normal_estimate, Ordering::Release);
166                                 fees.get(&Target::HighPriority)
167                                         .unwrap()
168                                         .store(high_prio_estimate, Ordering::Release);
169                                 tokio::time::sleep(Duration::from_secs(60)).await;
170                         }
171                 });
172         }
173
174         pub fn get_new_rpc_client(&self) -> std::io::Result<RpcClient> {
175                 let http_endpoint = HttpEndpoint::for_host(self.host.clone()).with_port(self.port);
176                 let rpc_credentials =
177                         base64::encode(format!("{}:{}", self.rpc_user.clone(), self.rpc_password.clone()));
178                 RpcClient::new(&rpc_credentials, http_endpoint)
179         }
180
181         pub async fn create_raw_transaction(&self, outputs: Vec<HashMap<String, f64>>) -> RawTx {
182                 let mut rpc = self.bitcoind_rpc_client.lock().await;
183
184                 let outputs_json = serde_json::json!(outputs);
185                 rpc.call_method::<RawTx>("createrawtransaction", &vec![serde_json::json!([]), outputs_json])
186                         .await
187                         .unwrap()
188         }
189
190         pub async fn fund_raw_transaction(&self, raw_tx: RawTx) -> FundedTx {
191                 let mut rpc = self.bitcoind_rpc_client.lock().await;
192
193                 let raw_tx_json = serde_json::json!(raw_tx.0);
194                 let options = serde_json::json!({
195                         // LDK gives us feerates in satoshis per KW but Bitcoin Core here expects fees
196                         // denominated in satoshis per vB. First we need to multiply by 4 to convert weight
197                         // units to virtual bytes, then divide by 1000 to convert KvB to vB.
198                         "fee_rate": self.get_est_sat_per_1000_weight(ConfirmationTarget::Normal) as f64 / 250.0,
199                         // While users could "cancel" a channel open by RBF-bumping and paying back to
200                         // themselves, we don't allow it here as its easy to have users accidentally RBF bump
201                         // and pay to the channel funding address, which results in loss of funds. Real
202                         // LDK-based applications should enable RBF bumping and RBF bump either to a local
203                         // change address or to a new channel output negotiated with the same node.
204                         "replaceable": false,
205                 });
206                 rpc.call_method("fundrawtransaction", &[raw_tx_json, options]).await.unwrap()
207         }
208
209         pub async fn send_raw_transaction(&self, raw_tx: RawTx) {
210                 let mut rpc = self.bitcoind_rpc_client.lock().await;
211
212                 let raw_tx_json = serde_json::json!(raw_tx.0);
213                 rpc.call_method::<Txid>("sendrawtransaction", &[raw_tx_json]).await.unwrap();
214         }
215
216         pub async fn sign_raw_transaction_with_wallet(&self, tx_hex: String) -> SignedTx {
217                 let mut rpc = self.bitcoind_rpc_client.lock().await;
218
219                 let tx_hex_json = serde_json::json!(tx_hex);
220                 rpc.call_method("signrawtransactionwithwallet", &vec![tx_hex_json]).await.unwrap()
221         }
222
223         pub async fn get_new_address(&self) -> Address {
224                 let mut rpc = self.bitcoind_rpc_client.lock().await;
225
226                 let addr_args = vec![serde_json::json!("LDK output address")];
227                 let addr = rpc.call_method::<NewAddress>("getnewaddress", &addr_args).await.unwrap();
228                 Address::from_str(addr.0.as_str()).unwrap()
229         }
230
231         pub async fn get_blockchain_info(&self) -> BlockchainInfo {
232                 let mut rpc = self.bitcoind_rpc_client.lock().await;
233                 rpc.call_method::<BlockchainInfo>("getblockchaininfo", &vec![]).await.unwrap()
234         }
235 }
236
237 impl FeeEstimator for BitcoindClient {
238         fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u32 {
239                 match confirmation_target {
240                         ConfirmationTarget::Background => {
241                                 self.fees.get(&Target::Background).unwrap().load(Ordering::Acquire)
242                         }
243                         ConfirmationTarget::Normal => {
244                                 self.fees.get(&Target::Normal).unwrap().load(Ordering::Acquire)
245                         }
246                         ConfirmationTarget::HighPriority => {
247                                 self.fees.get(&Target::HighPriority).unwrap().load(Ordering::Acquire)
248                         }
249                 }
250         }
251 }
252
253 impl BroadcasterInterface for BitcoindClient {
254         fn broadcast_transaction(&self, tx: &Transaction) {
255                 let bitcoind_rpc_client = self.bitcoind_rpc_client.clone();
256                 let tx_serialized = serde_json::json!(encode::serialize_hex(tx));
257                 self.handle.spawn(async move {
258                         let mut rpc = bitcoind_rpc_client.lock().await;
259                         // This may error due to RL calling `broadcast_transaction` with the same transaction
260                         // multiple times, but the error is safe to ignore.
261                         match rpc.call_method::<Txid>("sendrawtransaction", &vec![tx_serialized]).await {
262                                 Ok(_) => {}
263                                 Err(e) => {
264                                         let err_str = e.get_ref().unwrap().to_string();
265                                         if !err_str.contains("Transaction already in block chain")
266                                                 && !err_str.contains("Inputs missing or spent")
267                                                 && !err_str.contains("bad-txns-inputs-missingorspent")
268                                                 && !err_str.contains("non-BIP68-final")
269                                                 && !err_str.contains("insufficient fee, rejecting replacement ")
270                                         {
271                                                 panic!("{}", e);
272                                         }
273                                 }
274                         }
275                 });
276         }
277 }