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