Initial refactor to add tokio::main and be fully async
[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;
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 }
28
29 #[derive(Clone, Eq, Hash, PartialEq)]
30 pub enum Target {
31         Background,
32         Normal,
33         HighPriority,
34 }
35
36 impl BlockSource for &BitcoindClient {
37         fn get_header<'a>(
38                 &'a mut self, header_hash: &'a BlockHash, height_hint: Option<u32>,
39         ) -> AsyncBlockSourceResult<'a, BlockHeaderData> {
40                 Box::pin(async move {
41                         let mut rpc = self.bitcoind_rpc_client.lock().await;
42                         rpc.get_header(header_hash, height_hint).await
43                 })
44         }
45
46         fn get_block<'a>(
47                 &'a mut self, header_hash: &'a BlockHash,
48         ) -> AsyncBlockSourceResult<'a, Block> {
49                 Box::pin(async move {
50                         let mut rpc = self.bitcoind_rpc_client.lock().await;
51                         rpc.get_block(header_hash).await
52                 })
53         }
54
55         fn get_best_block<'a>(&'a mut self) -> AsyncBlockSourceResult<(BlockHash, Option<u32>)> {
56                 Box::pin(async move {
57                         let mut rpc = self.bitcoind_rpc_client.lock().await;
58                         rpc.get_best_block().await
59                 })
60         }
61 }
62
63 impl BitcoindClient {
64         pub async fn new(
65                 host: String, port: u16, rpc_user: String, rpc_password: String,
66         ) -> std::io::Result<Self> {
67                 let http_endpoint = HttpEndpoint::for_host(host.clone()).with_port(port);
68                 let rpc_credentials =
69                         base64::encode(format!("{}:{}", rpc_user.clone(), rpc_password.clone()));
70                 let bitcoind_rpc_client = RpcClient::new(&rpc_credentials, http_endpoint)?;
71                 let mut fees: HashMap<Target, AtomicU32> = HashMap::new();
72                 fees.insert(Target::Background, AtomicU32::new(253));
73                 fees.insert(Target::Normal, AtomicU32::new(2000));
74                 fees.insert(Target::HighPriority, AtomicU32::new(5000));
75                 let client = Self {
76                         bitcoind_rpc_client: Arc::new(Mutex::new(bitcoind_rpc_client)),
77                         host,
78                         port,
79                         rpc_user,
80                         rpc_password,
81                         fees: Arc::new(fees),
82                 };
83                 BitcoindClient::poll_for_fee_estimates(
84                         client.fees.clone(),
85                         client.bitcoind_rpc_client.clone(),
86                 )
87                 .await;
88                 Ok(client)
89         }
90
91         async fn poll_for_fee_estimates(
92                 fees: Arc<HashMap<Target, AtomicU32>>, rpc_client: Arc<Mutex<RpcClient>>,
93         ) {
94                 tokio::spawn(async move {
95                         loop {
96                                 let background_estimate = {
97                                         let mut rpc = rpc_client.lock().await;
98                                         let background_conf_target = serde_json::json!(144);
99                                         let background_estimate_mode = serde_json::json!("ECONOMICAL");
100                                         let resp = rpc
101                                                 .call_method::<FeeResponse>(
102                                                         "estimatesmartfee",
103                                                         &vec![background_conf_target, background_estimate_mode],
104                                                 )
105                                                 .await
106                                                 .unwrap();
107                                         match resp.feerate {
108                                                 Some(fee) => fee,
109                                                 None => 253,
110                                         }
111                                 };
112                                 // if background_estimate.
113
114                                 let normal_estimate = {
115                                         let mut rpc = rpc_client.lock().await;
116                                         let normal_conf_target = serde_json::json!(18);
117                                         let normal_estimate_mode = serde_json::json!("ECONOMICAL");
118                                         let resp = rpc
119                                                 .call_method::<FeeResponse>(
120                                                         "estimatesmartfee",
121                                                         &vec![normal_conf_target, normal_estimate_mode],
122                                                 )
123                                                 .await
124                                                 .unwrap();
125                                         match resp.feerate {
126                                                 Some(fee) => fee,
127                                                 None => 2000,
128                                         }
129                                 };
130
131                                 let high_prio_estimate = {
132                                         let mut rpc = rpc_client.lock().await;
133                                         let high_prio_conf_target = serde_json::json!(6);
134                                         let high_prio_estimate_mode = serde_json::json!("CONSERVATIVE");
135                                         let resp = rpc
136                                                 .call_method::<FeeResponse>(
137                                                         "estimatesmartfee",
138                                                         &vec![high_prio_conf_target, high_prio_estimate_mode],
139                                                 )
140                                                 .await
141                                                 .unwrap();
142
143                                         match resp.feerate {
144                                                 Some(fee) => fee,
145                                                 None => 5000,
146                                         }
147                                 };
148
149                                 fees.get(&Target::Background)
150                                         .unwrap()
151                                         .store(background_estimate, Ordering::Release);
152                                 fees.get(&Target::Normal).unwrap().store(normal_estimate, Ordering::Release);
153                                 fees.get(&Target::HighPriority)
154                                         .unwrap()
155                                         .store(high_prio_estimate, Ordering::Release);
156                                 // match fees.get(Target::Background) {
157                                 //     Some(fee) => fee.store(background_estimate, Ordering::Release),
158                                 //     None =>
159                                 // }
160                                 // if let Some(fee) = background_estimate.feerate {
161                                 //     fees.get("background").unwrap().store(fee, Ordering::Release);
162                                 // }
163                                 // if let Some(fee) = normal_estimate.feerate {
164                                 //     fees.get("normal").unwrap().store(fee, Ordering::Release);
165                                 // }
166                                 // if let Some(fee) = high_prio_estimate.feerate {
167                                 //     fees.get("high_prio").unwrap().store(fee, Ordering::Release);
168                                 // }
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                 rpc.call_method("fundrawtransaction", &[raw_tx_json]).await.unwrap()
195         }
196
197         pub async fn send_raw_transaction(&self, raw_tx: RawTx) {
198                 let mut rpc = self.bitcoind_rpc_client.lock().await;
199
200                 let raw_tx_json = serde_json::json!(raw_tx.0);
201                 rpc.call_method::<RawTx>("sendrawtransaction", &[raw_tx_json]).await.unwrap();
202         }
203
204         pub async fn sign_raw_transaction_with_wallet(&self, tx_hex: String) -> SignedTx {
205                 let mut rpc = self.bitcoind_rpc_client.lock().await;
206
207                 let tx_hex_json = serde_json::json!(tx_hex);
208                 rpc.call_method("signrawtransactionwithwallet", &vec![tx_hex_json]).await.unwrap()
209         }
210
211         pub async fn get_new_address(&self) -> Address {
212                 let mut rpc = self.bitcoind_rpc_client.lock().await;
213
214                 let addr_args = vec![serde_json::json!("LDK output address")];
215                 let addr = rpc.call_method::<NewAddress>("getnewaddress", &addr_args).await.unwrap();
216                 Address::from_str(addr.0.as_str()).unwrap()
217         }
218
219         pub async fn get_blockchain_info(&self) -> BlockchainInfo {
220                 let mut rpc = self.bitcoind_rpc_client.lock().await;
221                 rpc.call_method::<BlockchainInfo>("getblockchaininfo", &vec![]).await.unwrap()
222         }
223 }
224
225 impl FeeEstimator for BitcoindClient {
226         fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u32 {
227                 match confirmation_target {
228                         ConfirmationTarget::Background => {
229                                 self.fees.get(&Target::Background).unwrap().load(Ordering::Acquire)
230                         }
231                         ConfirmationTarget::Normal => {
232                                 self.fees.get(&Target::Normal).unwrap().load(Ordering::Acquire)
233                         }
234                         ConfirmationTarget::HighPriority => {
235                                 self.fees.get(&Target::HighPriority).unwrap().load(Ordering::Acquire)
236                         }
237                 }
238                 // self.fees.g
239                 // 253
240                 // match confirmation_target {
241                 //     ConfirmationTarget::Background =>
242                 // }
243                 // let mut rpc = self.bitcoind_rpc_client.lock().unwrap();
244
245                 // let (conf_target, estimate_mode, default) = match confirmation_target {
246                 //      ConfirmationTarget::Background => (144, "ECONOMICAL", 253),
247                 //      ConfirmationTarget::Normal => (18, "ECONOMICAL", 20000),
248                 //      ConfirmationTarget::HighPriority => (6, "CONSERVATIVE", 50000),
249                 // };
250
251                 // // This function may be called from a tokio runtime, or not. So we need to check before
252                 // // making the call to avoid the error "cannot run a tokio runtime from within a tokio runtime".
253                 // let conf_target_json = serde_json::json!(conf_target);
254                 // let estimate_mode_json = serde_json::json!(estimate_mode);
255                 // let resp = match Handle::try_current() {
256                 //      Ok(_) => tokio::task::block_in_place(|| {
257                 //              runtime
258                 //                      .block_on(rpc.call_method::<FeeResponse>(
259                 //                              "estimatesmartfee",
260                 //                              &vec![conf_target_json, estimate_mode_json],
261                 //                      ))
262                 //                      .unwrap()
263                 //      }),
264                 //      _ => runtime
265                 //              .block_on(rpc.call_method::<FeeResponse>(
266                 //                      "estimatesmartfee",
267                 //                      &vec![conf_target_json, estimate_mode_json],
268                 //              ))
269                 //              .unwrap(),
270                 // };
271                 // if resp.errored {
272                 //      return default;
273                 // }
274                 // resp.feerate.unwrap()
275         }
276 }
277
278 impl BroadcasterInterface for BitcoindClient {
279         fn broadcast_transaction(&self, tx: &Transaction) {
280                 let bitcoind_rpc_client = self.bitcoind_rpc_client.clone();
281                 let tx_serialized = serde_json::json!(encode::serialize_hex(tx));
282                 tokio::spawn(async move {
283                         let mut rpc = bitcoind_rpc_client.lock().await;
284                         rpc.call_method::<RawTx>("sendrawtransaction", &vec![tx_serialized]).await.unwrap();
285                 });
286                 // let bitcoind_rpc_client = self.bitcoind_rpc_client.clone();
287                 // tokio::spawn(async move {
288                 //     let rpc = bitcoind_rpc_client.lock().await;
289                 //     rpc.call_method::<R>
290                 // });
291                 // let mut rpc = self.bitcoind_rpc_client.lock().unwrap();
292                 // let runtime = self.runtime.lock().unwrap();
293
294                 // let tx_serialized = serde_json::json!(encode::serialize_hex(tx));
295                 // // This function may be called from a tokio runtime, or not. So we need to check before
296                 // // making the call to avoid the error "cannot run a tokio runtime from within a tokio runtime".
297                 // match Handle::try_current() {
298                 //      Ok(_) => {
299                 //              tokio::task::block_in_place(|| {
300                 //                      runtime
301                 //                              .block_on(
302                 //                                      rpc.call_method::<RawTx>("sendrawtransaction", &vec![tx_serialized]),
303                 //                              )
304                 //                              .unwrap();
305                 //              });
306                 //      }
307                 //      _ => {
308                 //              runtime
309                 //                      .block_on(rpc.call_method::<RawTx>("sendrawtransaction", &vec![tx_serialized]))
310                 //                      .unwrap();
311                 //      }
312                 // }
313         }
314 }