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