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