1 #![cfg(any(feature = "esplora-blocking", feature = "esplora-async"))]
2 use lightning_transaction_sync::EsploraSyncClient;
3 use lightning::chain::{Confirm, Filter, WatchedOutput};
4 use lightning::chain::transaction::{OutPoint, TransactionData};
5 use lightning::util::test_utils::TestLogger;
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, u32, Option<BlockHash>)> {
147 self.confirmed_txs.lock().unwrap().iter().map(|(&txid, (hash, height))| (txid, *height, Some(*hash))).collect::<Vec<_>>()
152 #[cfg(feature = "esplora-blocking")]
153 fn test_esplora_syncs() {
154 let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
155 generate_blocks_and_wait(&bitcoind, &electrsd, 101);
156 let mut logger = TestLogger::new();
157 let esplora_url = format!("http://{}", electrsd.esplora_url.as_ref().unwrap());
158 let tx_sync = EsploraSyncClient::new(esplora_url, &mut logger);
159 let confirmable = TestConfirmable::new();
161 // Check we pick up on new best blocks
162 assert_eq!(confirmable.best_block.lock().unwrap().1, 0);
164 tx_sync.sync(vec![&confirmable]).unwrap();
165 assert_eq!(confirmable.best_block.lock().unwrap().1, 102);
167 let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
168 assert_eq!(events.len(), 1);
170 // Check registered confirmed transactions are marked confirmed
171 let new_address = bitcoind.client.get_new_address(Some("test"),
172 Some(AddressType::Legacy)).unwrap().assume_checked();
173 let txid = bitcoind.client.send_to_address(&new_address, Amount::from_sat(5000), None, None,
174 None, None, None, None).unwrap();
175 let second_txid = bitcoind.client.send_to_address(&new_address, Amount::from_sat(5000), None,
176 None, None, None, None, None).unwrap();
177 tx_sync.register_tx(&txid, &new_address.script_pubkey());
179 tx_sync.sync(vec![&confirmable]).unwrap();
181 let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
182 assert_eq!(events.len(), 0);
183 assert!(confirmable.confirmed_txs.lock().unwrap().is_empty());
184 assert!(confirmable.unconfirmed_txs.lock().unwrap().is_empty());
186 generate_blocks_and_wait(&bitcoind, &electrsd, 1);
187 tx_sync.sync(vec![&confirmable]).unwrap();
189 let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
190 assert_eq!(events.len(), 2);
191 assert!(confirmable.confirmed_txs.lock().unwrap().contains_key(&txid));
192 assert!(confirmable.unconfirmed_txs.lock().unwrap().is_empty());
194 // Now take an arbitrary output of the second transaction and check we'll confirm its spend.
195 let tx_res = bitcoind.client.get_transaction(&second_txid, None).unwrap();
196 let block_hash = tx_res.info.blockhash.unwrap();
197 let tx = tx_res.transaction().unwrap();
198 let prev_outpoint = tx.input.first().unwrap().previous_output;
199 let prev_tx = bitcoind.client.get_transaction(&prev_outpoint.txid, None).unwrap().transaction()
201 let prev_script_pubkey = prev_tx.output[prev_outpoint.vout as usize].script_pubkey.clone();
202 let output = WatchedOutput {
203 block_hash: Some(block_hash),
204 outpoint: OutPoint { txid: prev_outpoint.txid, index: prev_outpoint.vout as u16 },
205 script_pubkey: prev_script_pubkey
208 tx_sync.register_output(output);
209 tx_sync.sync(vec![&confirmable]).unwrap();
211 let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
212 assert_eq!(events.len(), 1);
213 assert!(confirmable.confirmed_txs.lock().unwrap().contains_key(&second_txid));
214 assert_eq!(confirmable.confirmed_txs.lock().unwrap().len(), 2);
215 assert!(confirmable.unconfirmed_txs.lock().unwrap().is_empty());
217 // Check previously confirmed transactions are marked unconfirmed when they are reorged.
218 let best_block_hash = bitcoind.client.get_best_block_hash().unwrap();
219 bitcoind.client.invalidate_block(&best_block_hash).unwrap();
221 // We're getting back to the previous height with a new tip, but best block shouldn't change.
222 generate_blocks_and_wait(&bitcoind, &electrsd, 1);
223 assert_ne!(bitcoind.client.get_best_block_hash().unwrap(), best_block_hash);
224 tx_sync.sync(vec![&confirmable]).unwrap();
225 let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
226 assert_eq!(events.len(), 0);
228 // Now we're surpassing previous height, getting new tip.
229 generate_blocks_and_wait(&bitcoind, &electrsd, 1);
230 assert_ne!(bitcoind.client.get_best_block_hash().unwrap(), best_block_hash);
231 tx_sync.sync(vec![&confirmable]).unwrap();
233 // Transactions still confirmed but under new tip.
234 assert!(confirmable.confirmed_txs.lock().unwrap().contains_key(&txid));
235 assert!(confirmable.confirmed_txs.lock().unwrap().contains_key(&second_txid));
236 assert!(confirmable.unconfirmed_txs.lock().unwrap().is_empty());
238 // Check we got unconfirmed, then reconfirmed in the meantime.
239 let mut seen_txids = HashSet::new();
240 let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
241 assert_eq!(events.len(), 5);
244 TestConfirmableEvent::Unconfirmed(t) => {
245 assert!(t == txid || t == second_txid);
246 assert!(seen_txids.insert(t));
248 _ => panic!("Unexpected event"),
252 TestConfirmableEvent::Unconfirmed(t) => {
253 assert!(t == txid || t == second_txid);
254 assert!(seen_txids.insert(t));
256 _ => panic!("Unexpected event"),
260 TestConfirmableEvent::BestBlockUpdated(..) => {},
261 _ => panic!("Unexpected event"),
265 TestConfirmableEvent::Confirmed(t, _, _) => {
266 assert!(t == txid || t == second_txid);
267 assert!(seen_txids.remove(&t));
269 _ => panic!("Unexpected event"),
273 TestConfirmableEvent::Confirmed(t, _, _) => {
274 assert!(t == txid || t == second_txid);
275 assert!(seen_txids.remove(&t));
277 _ => panic!("Unexpected event"),
280 assert_eq!(seen_txids.len(), 0);
284 #[cfg(feature = "esplora-async")]
285 async fn test_esplora_syncs() {
286 let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
287 generate_blocks_and_wait(&bitcoind, &electrsd, 101);
288 let mut logger = TestLogger::new();
289 let esplora_url = format!("http://{}", electrsd.esplora_url.as_ref().unwrap());
290 let tx_sync = EsploraSyncClient::new(esplora_url, &mut logger);
291 let confirmable = TestConfirmable::new();
293 // Check we pick up on new best blocks
294 assert_eq!(confirmable.best_block.lock().unwrap().1, 0);
296 tx_sync.sync(vec![&confirmable]).await.unwrap();
297 assert_eq!(confirmable.best_block.lock().unwrap().1, 102);
299 let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
300 assert_eq!(events.len(), 1);
302 // Check registered confirmed transactions are marked confirmed
303 let new_address = bitcoind.client.get_new_address(Some("test"),
304 Some(AddressType::Legacy)).unwrap().assume_checked();
305 let txid = bitcoind.client.send_to_address(&new_address, Amount::from_sat(5000), None, None,
306 None, None, None, None).unwrap();
307 let second_txid = bitcoind.client.send_to_address(&new_address, Amount::from_sat(5000), None,
308 None, None, None, None, None).unwrap();
309 tx_sync.register_tx(&txid, &new_address.script_pubkey());
311 tx_sync.sync(vec![&confirmable]).await.unwrap();
313 let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
314 assert_eq!(events.len(), 0);
315 assert!(confirmable.confirmed_txs.lock().unwrap().is_empty());
316 assert!(confirmable.unconfirmed_txs.lock().unwrap().is_empty());
318 generate_blocks_and_wait(&bitcoind, &electrsd, 1);
319 tx_sync.sync(vec![&confirmable]).await.unwrap();
321 let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
322 assert_eq!(events.len(), 2);
323 assert!(confirmable.confirmed_txs.lock().unwrap().contains_key(&txid));
324 assert!(confirmable.unconfirmed_txs.lock().unwrap().is_empty());
326 // Now take an arbitrary output of the second transaction and check we'll confirm its spend.
327 let tx_res = bitcoind.client.get_transaction(&second_txid, None).unwrap();
328 let block_hash = tx_res.info.blockhash.unwrap();
329 let tx = tx_res.transaction().unwrap();
330 let prev_outpoint = tx.input.first().unwrap().previous_output;
331 let prev_tx = bitcoind.client.get_transaction(&prev_outpoint.txid, None).unwrap().transaction()
333 let prev_script_pubkey = prev_tx.output[prev_outpoint.vout as usize].script_pubkey.clone();
334 let output = WatchedOutput {
335 block_hash: Some(block_hash),
336 outpoint: OutPoint { txid: prev_outpoint.txid, index: prev_outpoint.vout as u16 },
337 script_pubkey: prev_script_pubkey
340 tx_sync.register_output(output);
341 tx_sync.sync(vec![&confirmable]).await.unwrap();
343 let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
344 assert_eq!(events.len(), 1);
345 assert!(confirmable.confirmed_txs.lock().unwrap().contains_key(&second_txid));
346 assert_eq!(confirmable.confirmed_txs.lock().unwrap().len(), 2);
347 assert!(confirmable.unconfirmed_txs.lock().unwrap().is_empty());
349 // Check previously confirmed transactions are marked unconfirmed when they are reorged.
350 let best_block_hash = bitcoind.client.get_best_block_hash().unwrap();
351 bitcoind.client.invalidate_block(&best_block_hash).unwrap();
353 // We're getting back to the previous height with a new tip, but best block shouldn't change.
354 generate_blocks_and_wait(&bitcoind, &electrsd, 1);
355 assert_ne!(bitcoind.client.get_best_block_hash().unwrap(), best_block_hash);
356 tx_sync.sync(vec![&confirmable]).await.unwrap();
357 let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
358 assert_eq!(events.len(), 0);
360 // Now we're surpassing previous height, getting new tip.
361 generate_blocks_and_wait(&bitcoind, &electrsd, 1);
362 assert_ne!(bitcoind.client.get_best_block_hash().unwrap(), best_block_hash);
363 tx_sync.sync(vec![&confirmable]).await.unwrap();
365 // Transactions still confirmed but under new tip.
366 assert!(confirmable.confirmed_txs.lock().unwrap().contains_key(&txid));
367 assert!(confirmable.confirmed_txs.lock().unwrap().contains_key(&second_txid));
368 assert!(confirmable.unconfirmed_txs.lock().unwrap().is_empty());
370 // Check we got unconfirmed, then reconfirmed in the meantime.
371 let mut seen_txids = HashSet::new();
372 let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
373 assert_eq!(events.len(), 5);
376 TestConfirmableEvent::Unconfirmed(t) => {
377 assert!(t == txid || t == second_txid);
378 assert!(seen_txids.insert(t));
380 _ => panic!("Unexpected event"),
384 TestConfirmableEvent::Unconfirmed(t) => {
385 assert!(t == txid || t == second_txid);
386 assert!(seen_txids.insert(t));
388 _ => panic!("Unexpected event"),
392 TestConfirmableEvent::BestBlockUpdated(..) => {},
393 _ => panic!("Unexpected event"),
397 TestConfirmableEvent::Confirmed(t, _, _) => {
398 assert!(t == txid || t == second_txid);
399 assert!(seen_txids.remove(&t));
401 _ => panic!("Unexpected event"),
405 TestConfirmableEvent::Confirmed(t, _, _) => {
406 assert!(t == txid || t == second_txid);
407 assert!(seen_txids.remove(&t));
409 _ => panic!("Unexpected event"),
412 assert_eq!(seen_txids.len(), 0);