1 #![cfg(any(feature = "esplora-blocking", feature = "esplora-async"))]
2 use lightning_transaction_sync::EsploraSyncClient;
3 use lightning::chain::{Confirm, Filter};
4 use lightning::chain::transaction::TransactionData;
5 use lightning::util::logger::{Logger, Record};
7 use electrsd::{bitcoind, bitcoind::BitcoinD, ElectrsD};
8 use bitcoin::{Amount, Txid, BlockHash};
9 use bitcoin::blockdata::block::Header;
10 use bitcoin::blockdata::constants::genesis_block;
11 use bitcoin::network::constants::Network;
12 use electrsd::bitcoind::bitcoincore_rpc::bitcoincore_rpc_json::AddressType;
13 use bitcoind::bitcoincore_rpc::RpcApi;
14 use electrsd::electrum_client::ElectrumApi;
18 use std::time::Duration;
19 use std::collections::{HashMap, HashSet};
21 pub fn setup_bitcoind_and_electrsd() -> (BitcoinD, ElectrsD) {
23 env::var("BITCOIND_EXE").ok().or_else(|| bitcoind::downloaded_exe_path().ok()).expect(
24 "you need to provide an env var BITCOIND_EXE or specify a bitcoind version feature",
26 let mut bitcoind_conf = bitcoind::Conf::default();
27 bitcoind_conf.network = "regtest";
28 let bitcoind = BitcoinD::with_conf(bitcoind_exe, &bitcoind_conf).unwrap();
30 let electrs_exe = env::var("ELECTRS_EXE")
32 .or_else(electrsd::downloaded_exe_path)
33 .expect("you need to provide env var ELECTRS_EXE or specify an electrsd version feature");
34 let mut electrsd_conf = electrsd::Conf::default();
35 electrsd_conf.http_enabled = true;
36 electrsd_conf.network = "regtest";
37 let electrsd = ElectrsD::with_conf(electrs_exe, &bitcoind, &electrsd_conf).unwrap();
41 pub fn generate_blocks_and_wait(bitcoind: &BitcoinD, electrsd: &ElectrsD, num: usize) {
42 let cur_height = bitcoind.client.get_block_count().expect("failed to get current block height");
43 let address = bitcoind
45 .get_new_address(Some("test"), Some(AddressType::Legacy))
46 .expect("failed to get new address")
48 // TODO: expect this Result once the WouldBlock issue is resolved upstream.
49 let _block_hashes_res = bitcoind.client.generate_to_address(num as u64, &address);
50 wait_for_block(electrsd, cur_height as usize + num);
53 pub fn wait_for_block(electrsd: &ElectrsD, min_height: usize) {
54 let mut header = match electrsd.client.block_headers_subscribe_raw() {
57 // While subscribing should succeed the first time around, we ran into some cases where
58 // it didn't. Since we can't proceed without subscribing, we try again after a delay
59 // and panic if it still fails.
60 std::thread::sleep(Duration::from_secs(1));
61 electrsd.client.block_headers_subscribe_raw().expect("failed to subscribe to block headers")
65 if header.height >= min_height {
68 header = exponential_backoff_poll(|| {
69 electrsd.trigger().expect("failed to trigger electrsd");
70 electrsd.client.ping().expect("failed to ping electrsd");
71 electrsd.client.block_headers_pop_raw().expect("failed to pop block header")
76 fn exponential_backoff_poll<T, F>(mut poll: F) -> T
78 F: FnMut() -> Option<T>,
80 let mut delay = Duration::from_millis(64);
84 Some(data) => break data,
85 None if delay.as_millis() < 512 => {
86 delay = delay.mul_f32(2.0);
89 None if tries == 10 => panic!("Exceeded our maximum wait time."),
93 std::thread::sleep(delay);
98 enum TestConfirmableEvent {
99 Confirmed(Txid, BlockHash, u32),
101 BestBlockUpdated(BlockHash, u32),
104 struct TestConfirmable {
105 pub confirmed_txs: Mutex<HashMap<Txid, (BlockHash, u32)>>,
106 pub unconfirmed_txs: Mutex<HashSet<Txid>>,
107 pub best_block: Mutex<(BlockHash, u32)>,
108 pub events: Mutex<Vec<TestConfirmableEvent>>,
111 impl TestConfirmable {
112 pub fn new() -> Self {
113 let genesis_hash = genesis_block(Network::Regtest).block_hash();
115 confirmed_txs: Mutex::new(HashMap::new()),
116 unconfirmed_txs: Mutex::new(HashSet::new()),
117 best_block: Mutex::new((genesis_hash, 0)),
118 events: Mutex::new(Vec::new()),
123 impl Confirm for TestConfirmable {
124 fn transactions_confirmed(&self, header: &Header, txdata: &TransactionData<'_>, height: u32) {
125 for (_, tx) in txdata {
126 let txid = tx.txid();
127 let block_hash = header.block_hash();
128 self.confirmed_txs.lock().unwrap().insert(txid, (block_hash, height));
129 self.unconfirmed_txs.lock().unwrap().remove(&txid);
130 self.events.lock().unwrap().push(TestConfirmableEvent::Confirmed(txid, block_hash, height));
134 fn transaction_unconfirmed(&self, txid: &Txid) {
135 self.unconfirmed_txs.lock().unwrap().insert(*txid);
136 self.confirmed_txs.lock().unwrap().remove(txid);
137 self.events.lock().unwrap().push(TestConfirmableEvent::Unconfirmed(*txid));
140 fn best_block_updated(&self, header: &Header, height: u32) {
141 let block_hash = header.block_hash();
142 *self.best_block.lock().unwrap() = (block_hash, height);
143 self.events.lock().unwrap().push(TestConfirmableEvent::BestBlockUpdated(block_hash, height));
146 fn get_relevant_txids(&self) -> Vec<(Txid, Option<BlockHash>)> {
147 self.confirmed_txs.lock().unwrap().iter().map(|(&txid, (hash, _))| (txid, Some(*hash))).collect::<Vec<_>>()
151 pub struct TestLogger {}
153 impl Logger for TestLogger {
154 fn log(&self, record: &Record) {
162 #[cfg(feature = "esplora-blocking")]
163 fn test_esplora_syncs() {
164 let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
165 generate_blocks_and_wait(&bitcoind, &electrsd, 101);
166 let mut logger = TestLogger {};
167 let esplora_url = format!("http://{}", electrsd.esplora_url.as_ref().unwrap());
168 let tx_sync = EsploraSyncClient::new(esplora_url, &mut logger);
169 let confirmable = TestConfirmable::new();
171 // Check we pick up on new best blocks
172 assert_eq!(confirmable.best_block.lock().unwrap().1, 0);
174 tx_sync.sync(vec![&confirmable]).unwrap();
175 assert_eq!(confirmable.best_block.lock().unwrap().1, 102);
177 let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
178 assert_eq!(events.len(), 1);
180 // Check registered confirmed transactions are marked confirmed
181 let new_address = bitcoind.client.get_new_address(Some("test"), Some(AddressType::Legacy)).unwrap().assume_checked();
182 let txid = bitcoind.client.send_to_address(&new_address, Amount::from_sat(5000), None, None, None, None, None, None).unwrap();
183 tx_sync.register_tx(&txid, &new_address.payload.script_pubkey());
185 tx_sync.sync(vec![&confirmable]).unwrap();
187 let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
188 assert_eq!(events.len(), 0);
189 assert!(confirmable.confirmed_txs.lock().unwrap().is_empty());
190 assert!(confirmable.unconfirmed_txs.lock().unwrap().is_empty());
192 generate_blocks_and_wait(&bitcoind, &electrsd, 1);
193 tx_sync.sync(vec![&confirmable]).unwrap();
195 let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
196 assert_eq!(events.len(), 2);
197 assert!(confirmable.confirmed_txs.lock().unwrap().contains_key(&txid));
198 assert!(confirmable.unconfirmed_txs.lock().unwrap().is_empty());
200 // Check previously confirmed transactions are marked unconfirmed when they are reorged.
201 let best_block_hash = bitcoind.client.get_best_block_hash().unwrap();
202 bitcoind.client.invalidate_block(&best_block_hash).unwrap();
204 // We're getting back to the previous height with a new tip, but best block shouldn't change.
205 generate_blocks_and_wait(&bitcoind, &electrsd, 1);
206 assert_ne!(bitcoind.client.get_best_block_hash().unwrap(), best_block_hash);
207 tx_sync.sync(vec![&confirmable]).unwrap();
208 let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
209 assert_eq!(events.len(), 0);
211 // Now we're surpassing previous height, getting new tip.
212 generate_blocks_and_wait(&bitcoind, &electrsd, 1);
213 assert_ne!(bitcoind.client.get_best_block_hash().unwrap(), best_block_hash);
214 tx_sync.sync(vec![&confirmable]).unwrap();
216 // Transaction still confirmed but under new tip.
217 assert!(confirmable.confirmed_txs.lock().unwrap().contains_key(&txid));
218 assert!(confirmable.unconfirmed_txs.lock().unwrap().is_empty());
220 // Check we got unconfirmed, then reconfirmed in the meantime.
221 let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
222 assert_eq!(events.len(), 3);
225 TestConfirmableEvent::Unconfirmed(t) => {
228 _ => panic!("Unexpected event"),
232 TestConfirmableEvent::BestBlockUpdated(..) => {},
233 _ => panic!("Unexpected event"),
237 TestConfirmableEvent::Confirmed(t, _, _) => {
240 _ => panic!("Unexpected event"),
245 #[cfg(feature = "esplora-async")]
246 async fn test_esplora_syncs() {
247 let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
248 generate_blocks_and_wait(&bitcoind, &electrsd, 101);
249 let mut logger = TestLogger {};
250 let esplora_url = format!("http://{}", electrsd.esplora_url.as_ref().unwrap());
251 let tx_sync = EsploraSyncClient::new(esplora_url, &mut logger);
252 let confirmable = TestConfirmable::new();
254 // Check we pick up on new best blocks
255 assert_eq!(confirmable.best_block.lock().unwrap().1, 0);
257 tx_sync.sync(vec![&confirmable]).await.unwrap();
258 assert_eq!(confirmable.best_block.lock().unwrap().1, 102);
260 let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
261 assert_eq!(events.len(), 1);
263 // Check registered confirmed transactions are marked confirmed
264 let new_address = bitcoind.client.get_new_address(Some("test"), Some(AddressType::Legacy)).unwrap().assume_checked();
265 let txid = bitcoind.client.send_to_address(&new_address, Amount::from_sat(5000), None, None, None, None, None, None).unwrap();
266 tx_sync.register_tx(&txid, &new_address.payload.script_pubkey());
268 tx_sync.sync(vec![&confirmable]).await.unwrap();
270 let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
271 assert_eq!(events.len(), 0);
272 assert!(confirmable.confirmed_txs.lock().unwrap().is_empty());
273 assert!(confirmable.unconfirmed_txs.lock().unwrap().is_empty());
275 generate_blocks_and_wait(&bitcoind, &electrsd, 1);
276 tx_sync.sync(vec![&confirmable]).await.unwrap();
278 let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
279 assert_eq!(events.len(), 2);
280 assert!(confirmable.confirmed_txs.lock().unwrap().contains_key(&txid));
281 assert!(confirmable.unconfirmed_txs.lock().unwrap().is_empty());
283 // Check previously confirmed transactions are marked unconfirmed when they are reorged.
284 let best_block_hash = bitcoind.client.get_best_block_hash().unwrap();
285 bitcoind.client.invalidate_block(&best_block_hash).unwrap();
287 // We're getting back to the previous height with a new tip, but best block shouldn't change.
288 generate_blocks_and_wait(&bitcoind, &electrsd, 1);
289 assert_ne!(bitcoind.client.get_best_block_hash().unwrap(), best_block_hash);
290 tx_sync.sync(vec![&confirmable]).await.unwrap();
291 let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
292 assert_eq!(events.len(), 0);
294 // Now we're surpassing previous height, getting new tip.
295 generate_blocks_and_wait(&bitcoind, &electrsd, 1);
296 assert_ne!(bitcoind.client.get_best_block_hash().unwrap(), best_block_hash);
297 tx_sync.sync(vec![&confirmable]).await.unwrap();
299 // Transaction still confirmed but under new tip.
300 assert!(confirmable.confirmed_txs.lock().unwrap().contains_key(&txid));
301 assert!(confirmable.unconfirmed_txs.lock().unwrap().is_empty());
303 // Check we got unconfirmed, then reconfirmed in the meantime.
304 let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
305 assert_eq!(events.len(), 3);
308 TestConfirmableEvent::Unconfirmed(t) => {
311 _ => panic!("Unexpected event"),
315 TestConfirmableEvent::BestBlockUpdated(..) => {},
316 _ => panic!("Unexpected event"),
320 TestConfirmableEvent::Confirmed(t, _, _) => {
323 _ => panic!("Unexpected event"),