]> git.bitcoin.ninja Git - rust-lightning/blob - lightning-transaction-sync/tests/integration_tests.rs
Improve `EsploraSyncClient` test coverage
[rust-lightning] / lightning-transaction-sync / tests / integration_tests.rs
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;
6
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;
15
16 use std::env;
17 use std::sync::Mutex;
18 use std::time::Duration;
19 use std::collections::{HashMap, HashSet};
20
21 pub fn setup_bitcoind_and_electrsd() -> (BitcoinD, ElectrsD) {
22         let bitcoind_exe =
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",
25                 );
26         let mut bitcoind_conf = bitcoind::Conf::default();
27         bitcoind_conf.network = "regtest";
28         let bitcoind = BitcoinD::with_conf(bitcoind_exe, &bitcoind_conf).unwrap();
29
30         let electrs_exe = env::var("ELECTRS_EXE")
31                 .ok()
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();
38         (bitcoind, electrsd)
39 }
40
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
44                 .client
45                 .get_new_address(Some("test"), Some(AddressType::Legacy))
46                 .expect("failed to get new address")
47                 .assume_checked();
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);
51 }
52
53 pub fn wait_for_block(electrsd: &ElectrsD, min_height: usize) {
54         let mut header = match electrsd.client.block_headers_subscribe_raw() {
55                 Ok(header) => header,
56                 Err(_) => {
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")
62                 }
63         };
64         loop {
65                 if header.height >= min_height {
66                         break;
67                 }
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")
72                 });
73         }
74 }
75
76 fn exponential_backoff_poll<T, F>(mut poll: F) -> T
77 where
78         F: FnMut() -> Option<T>,
79 {
80         let mut delay = Duration::from_millis(64);
81         let mut tries = 0;
82         loop {
83                 match poll() {
84                         Some(data) => break data,
85                         None if delay.as_millis() < 512 => {
86                                 delay = delay.mul_f32(2.0);
87                                 tries += 1;
88                         }
89                         None if tries == 10 => panic!("Exceeded our maximum wait time."),
90                         None => tries += 1,
91                 }
92
93                 std::thread::sleep(delay);
94         }
95 }
96
97 #[derive(Debug)]
98 enum TestConfirmableEvent {
99         Confirmed(Txid, BlockHash, u32),
100         Unconfirmed(Txid),
101         BestBlockUpdated(BlockHash, u32),
102 }
103
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>>,
109 }
110
111 impl TestConfirmable {
112         pub fn new() -> Self {
113                 let genesis_hash = genesis_block(Network::Regtest).block_hash();
114                 Self {
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()),
119                 }
120         }
121 }
122
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));
131                 }
132         }
133
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));
138         }
139
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));
144         }
145
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<_>>()
148         }
149 }
150
151 #[test]
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();
160
161         // Check we pick up on new best blocks
162         assert_eq!(confirmable.best_block.lock().unwrap().1, 0);
163
164         tx_sync.sync(vec![&confirmable]).unwrap();
165         assert_eq!(confirmable.best_block.lock().unwrap().1, 102);
166
167         let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
168         assert_eq!(events.len(), 1);
169
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());
178
179         tx_sync.sync(vec![&confirmable]).unwrap();
180
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());
185
186         generate_blocks_and_wait(&bitcoind, &electrsd, 1);
187         tx_sync.sync(vec![&confirmable]).unwrap();
188
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());
193
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()
200                 .unwrap();
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
206         };
207
208         tx_sync.register_output(output);
209         tx_sync.sync(vec![&confirmable]).unwrap();
210
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());
216
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();
220
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);
227
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();
232
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());
237
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);
242
243         match events[0] {
244                 TestConfirmableEvent::Unconfirmed(t) => {
245                         assert!(t == txid || t == second_txid);
246                         assert!(seen_txids.insert(t));
247                 },
248                 _ => panic!("Unexpected event"),
249         }
250
251         match events[1] {
252                 TestConfirmableEvent::Unconfirmed(t) => {
253                         assert!(t == txid || t == second_txid);
254                         assert!(seen_txids.insert(t));
255                 },
256                 _ => panic!("Unexpected event"),
257         }
258
259         match events[2] {
260                 TestConfirmableEvent::BestBlockUpdated(..) => {},
261                 _ => panic!("Unexpected event"),
262         }
263
264         match events[3] {
265                 TestConfirmableEvent::Confirmed(t, _, _) => {
266                         assert!(t == txid || t == second_txid);
267                         assert!(seen_txids.remove(&t));
268                 },
269                 _ => panic!("Unexpected event"),
270         }
271
272         match events[4] {
273                 TestConfirmableEvent::Confirmed(t, _, _) => {
274                         assert!(t == txid || t == second_txid);
275                         assert!(seen_txids.remove(&t));
276                 },
277                 _ => panic!("Unexpected event"),
278         }
279
280         assert_eq!(seen_txids.len(), 0);
281 }
282
283 #[tokio::test]
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();
292
293         // Check we pick up on new best blocks
294         assert_eq!(confirmable.best_block.lock().unwrap().1, 0);
295
296         tx_sync.sync(vec![&confirmable]).await.unwrap();
297         assert_eq!(confirmable.best_block.lock().unwrap().1, 102);
298
299         let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
300         assert_eq!(events.len(), 1);
301
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());
310
311         tx_sync.sync(vec![&confirmable]).await.unwrap();
312
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());
317
318         generate_blocks_and_wait(&bitcoind, &electrsd, 1);
319         tx_sync.sync(vec![&confirmable]).await.unwrap();
320
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());
325
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()
332                 .unwrap();
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
338         };
339
340         tx_sync.register_output(output);
341         tx_sync.sync(vec![&confirmable]).await.unwrap();
342
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());
348
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();
352
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);
359
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();
364
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());
369
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);
374
375         match events[0] {
376                 TestConfirmableEvent::Unconfirmed(t) => {
377                         assert!(t == txid || t == second_txid);
378                         assert!(seen_txids.insert(t));
379                 },
380                 _ => panic!("Unexpected event"),
381         }
382
383         match events[1] {
384                 TestConfirmableEvent::Unconfirmed(t) => {
385                         assert!(t == txid || t == second_txid);
386                         assert!(seen_txids.insert(t));
387                 },
388                 _ => panic!("Unexpected event"),
389         }
390
391         match events[2] {
392                 TestConfirmableEvent::BestBlockUpdated(..) => {},
393                 _ => panic!("Unexpected event"),
394         }
395
396         match events[3] {
397                 TestConfirmableEvent::Confirmed(t, _, _) => {
398                         assert!(t == txid || t == second_txid);
399                         assert!(seen_txids.remove(&t));
400                 },
401                 _ => panic!("Unexpected event"),
402         }
403
404         match events[4] {
405                 TestConfirmableEvent::Confirmed(t, _, _) => {
406                         assert!(t == txid || t == second_txid);
407                         assert!(seen_txids.remove(&t));
408                 },
409                 _ => panic!("Unexpected event"),
410         }
411
412         assert_eq!(seen_txids.len(), 0);
413 }