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