1 use crate::convert::{BlockchainInfo, FeeResponse, FundedTx, NewAddress, RawTx, SignedTx};
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};
13 use std::collections::HashMap;
14 use std::str::FromStr;
15 use std::sync::atomic::{AtomicU32, Ordering};
17 use std::time::Duration;
18 use tokio::sync::Mutex;
20 pub struct BitcoindClient {
21 bitcoind_rpc_client: Arc<Mutex<RpcClient>>,
26 fees: Arc<HashMap<Target, AtomicU32>>,
29 #[derive(Clone, Eq, Hash, PartialEq)]
36 impl BlockSource for &BitcoindClient {
38 &'a mut self, header_hash: &'a BlockHash, height_hint: Option<u32>,
39 ) -> AsyncBlockSourceResult<'a, BlockHeaderData> {
41 let mut rpc = self.bitcoind_rpc_client.lock().await;
42 rpc.get_header(header_hash, height_hint).await
47 &'a mut self, header_hash: &'a BlockHash,
48 ) -> AsyncBlockSourceResult<'a, Block> {
50 let mut rpc = self.bitcoind_rpc_client.lock().await;
51 rpc.get_block(header_hash).await
55 fn get_best_block<'a>(&'a mut self) -> AsyncBlockSourceResult<(BlockHash, Option<u32>)> {
57 let mut rpc = self.bitcoind_rpc_client.lock().await;
58 rpc.get_best_block().await
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);
69 base64::encode(format!("{}:{}", rpc_user.clone(), rpc_password.clone()));
70 let mut bitcoind_rpc_client = RpcClient::new(&rpc_credentials, http_endpoint)?;
71 let _dummy = bitcoind_rpc_client
72 .call_method::<BlockchainInfo>("getblockchaininfo", &vec![])
75 std::io::Error::new(std::io::ErrorKind::PermissionDenied,
76 "Failed to make initial call to bitcoind - please check your RPC user/password and access settings")
78 let mut fees: HashMap<Target, AtomicU32> = HashMap::new();
79 fees.insert(Target::Background, AtomicU32::new(253));
80 fees.insert(Target::Normal, AtomicU32::new(2000));
81 fees.insert(Target::HighPriority, AtomicU32::new(5000));
83 bitcoind_rpc_client: Arc::new(Mutex::new(bitcoind_rpc_client)),
90 BitcoindClient::poll_for_fee_estimates(
92 client.bitcoind_rpc_client.clone(),
98 async fn poll_for_fee_estimates(
99 fees: Arc<HashMap<Target, AtomicU32>>, rpc_client: Arc<Mutex<RpcClient>>,
101 tokio::spawn(async move {
103 let background_estimate = {
104 let mut rpc = rpc_client.lock().await;
105 let background_conf_target = serde_json::json!(144);
106 let background_estimate_mode = serde_json::json!("ECONOMICAL");
108 .call_method::<FeeResponse>(
110 &vec![background_conf_target, background_estimate_mode],
119 // if background_estimate.
121 let normal_estimate = {
122 let mut rpc = rpc_client.lock().await;
123 let normal_conf_target = serde_json::json!(18);
124 let normal_estimate_mode = serde_json::json!("ECONOMICAL");
126 .call_method::<FeeResponse>(
128 &vec![normal_conf_target, normal_estimate_mode],
138 let high_prio_estimate = {
139 let mut rpc = rpc_client.lock().await;
140 let high_prio_conf_target = serde_json::json!(6);
141 let high_prio_estimate_mode = serde_json::json!("CONSERVATIVE");
143 .call_method::<FeeResponse>(
145 &vec![high_prio_conf_target, high_prio_estimate_mode],
156 fees.get(&Target::Background)
158 .store(background_estimate, Ordering::Release);
159 fees.get(&Target::Normal).unwrap().store(normal_estimate, Ordering::Release);
160 fees.get(&Target::HighPriority)
162 .store(high_prio_estimate, Ordering::Release);
163 tokio::time::sleep(Duration::from_secs(60)).await;
168 pub fn get_new_rpc_client(&self) -> std::io::Result<RpcClient> {
169 let http_endpoint = HttpEndpoint::for_host(self.host.clone()).with_port(self.port);
170 let rpc_credentials =
171 base64::encode(format!("{}:{}", self.rpc_user.clone(), self.rpc_password.clone()));
172 RpcClient::new(&rpc_credentials, http_endpoint)
175 pub async fn create_raw_transaction(&self, outputs: Vec<HashMap<String, f64>>) -> RawTx {
176 let mut rpc = self.bitcoind_rpc_client.lock().await;
178 let outputs_json = serde_json::json!(outputs);
179 rpc.call_method::<RawTx>("createrawtransaction", &vec![serde_json::json!([]), outputs_json])
184 pub async fn fund_raw_transaction(&self, raw_tx: RawTx) -> FundedTx {
185 let mut rpc = self.bitcoind_rpc_client.lock().await;
187 let raw_tx_json = serde_json::json!(raw_tx.0);
188 rpc.call_method("fundrawtransaction", &[raw_tx_json]).await.unwrap()
191 pub async fn send_raw_transaction(&self, raw_tx: RawTx) {
192 let mut rpc = self.bitcoind_rpc_client.lock().await;
194 let raw_tx_json = serde_json::json!(raw_tx.0);
195 rpc.call_method::<RawTx>("sendrawtransaction", &[raw_tx_json]).await.unwrap();
198 pub async fn sign_raw_transaction_with_wallet(&self, tx_hex: String) -> SignedTx {
199 let mut rpc = self.bitcoind_rpc_client.lock().await;
201 let tx_hex_json = serde_json::json!(tx_hex);
202 rpc.call_method("signrawtransactionwithwallet", &vec![tx_hex_json]).await.unwrap()
205 pub async fn get_new_address(&self) -> Address {
206 let mut rpc = self.bitcoind_rpc_client.lock().await;
208 let addr_args = vec![serde_json::json!("LDK output address")];
209 let addr = rpc.call_method::<NewAddress>("getnewaddress", &addr_args).await.unwrap();
210 Address::from_str(addr.0.as_str()).unwrap()
213 pub async fn get_blockchain_info(&self) -> BlockchainInfo {
214 let mut rpc = self.bitcoind_rpc_client.lock().await;
215 rpc.call_method::<BlockchainInfo>("getblockchaininfo", &vec![]).await.unwrap()
219 impl FeeEstimator for BitcoindClient {
220 fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u32 {
221 match confirmation_target {
222 ConfirmationTarget::Background => {
223 self.fees.get(&Target::Background).unwrap().load(Ordering::Acquire)
225 ConfirmationTarget::Normal => {
226 self.fees.get(&Target::Normal).unwrap().load(Ordering::Acquire)
228 ConfirmationTarget::HighPriority => {
229 self.fees.get(&Target::HighPriority).unwrap().load(Ordering::Acquire)
235 impl BroadcasterInterface for BitcoindClient {
236 fn broadcast_transaction(&self, tx: &Transaction) {
237 let bitcoind_rpc_client = self.bitcoind_rpc_client.clone();
238 let tx_serialized = serde_json::json!(encode::serialize_hex(tx));
239 tokio::spawn(async move {
240 let mut rpc = bitcoind_rpc_client.lock().await;
241 // This may error due to RL calling `broadcast_transaction` with the same transaction
242 // multiple times, but the error is safe to ignore.
243 match rpc.call_method::<RawTx>("sendrawtransaction", &vec![tx_serialized]).await {
246 let err_str = e.get_ref().unwrap().to_string();
247 if !err_str.contains("Transaction already in block chain")
248 && !err_str.contains("Inputs missing or spent")
249 && !err_str.contains("non-BIP68-final")