Use upstream `TestLogger` util in tx sync tests
[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};
4 use lightning::chain::transaction::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"), Some(AddressType::Legacy)).unwrap().assume_checked();
172         let txid = bitcoind.client.send_to_address(&new_address, Amount::from_sat(5000), None, None, None, None, None, None).unwrap();
173         tx_sync.register_tx(&txid, &new_address.payload.script_pubkey());
174
175         tx_sync.sync(vec![&confirmable]).unwrap();
176
177         let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
178         assert_eq!(events.len(), 0);
179         assert!(confirmable.confirmed_txs.lock().unwrap().is_empty());
180         assert!(confirmable.unconfirmed_txs.lock().unwrap().is_empty());
181
182         generate_blocks_and_wait(&bitcoind, &electrsd, 1);
183         tx_sync.sync(vec![&confirmable]).unwrap();
184
185         let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
186         assert_eq!(events.len(), 2);
187         assert!(confirmable.confirmed_txs.lock().unwrap().contains_key(&txid));
188         assert!(confirmable.unconfirmed_txs.lock().unwrap().is_empty());
189
190         // Check previously confirmed transactions are marked unconfirmed when they are reorged.
191         let best_block_hash = bitcoind.client.get_best_block_hash().unwrap();
192         bitcoind.client.invalidate_block(&best_block_hash).unwrap();
193
194         // We're getting back to the previous height with a new tip, but best block shouldn't change.
195         generate_blocks_and_wait(&bitcoind, &electrsd, 1);
196         assert_ne!(bitcoind.client.get_best_block_hash().unwrap(), best_block_hash);
197         tx_sync.sync(vec![&confirmable]).unwrap();
198         let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
199         assert_eq!(events.len(), 0);
200
201         // Now we're surpassing previous height, getting new tip.
202         generate_blocks_and_wait(&bitcoind, &electrsd, 1);
203         assert_ne!(bitcoind.client.get_best_block_hash().unwrap(), best_block_hash);
204         tx_sync.sync(vec![&confirmable]).unwrap();
205
206         // Transaction still confirmed but under new tip.
207         assert!(confirmable.confirmed_txs.lock().unwrap().contains_key(&txid));
208         assert!(confirmable.unconfirmed_txs.lock().unwrap().is_empty());
209
210         // Check we got unconfirmed, then reconfirmed in the meantime.
211         let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
212         assert_eq!(events.len(), 3);
213
214         match events[0] {
215                 TestConfirmableEvent::Unconfirmed(t) => {
216                         assert_eq!(t, txid);
217                 },
218                 _ => panic!("Unexpected event"),
219         }
220
221         match events[1] {
222                 TestConfirmableEvent::BestBlockUpdated(..) => {},
223                 _ => panic!("Unexpected event"),
224         }
225
226         match events[2] {
227                 TestConfirmableEvent::Confirmed(t, _, _) => {
228                         assert_eq!(t, txid);
229                 },
230                 _ => panic!("Unexpected event"),
231         }
232 }
233
234 #[tokio::test]
235 #[cfg(feature = "esplora-async")]
236 async fn test_esplora_syncs() {
237         let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
238         generate_blocks_and_wait(&bitcoind, &electrsd, 101);
239         let mut logger = TestLogger::new();
240         let esplora_url = format!("http://{}", electrsd.esplora_url.as_ref().unwrap());
241         let tx_sync = EsploraSyncClient::new(esplora_url, &mut logger);
242         let confirmable = TestConfirmable::new();
243
244         // Check we pick up on new best blocks
245         assert_eq!(confirmable.best_block.lock().unwrap().1, 0);
246
247         tx_sync.sync(vec![&confirmable]).await.unwrap();
248         assert_eq!(confirmable.best_block.lock().unwrap().1, 102);
249
250         let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
251         assert_eq!(events.len(), 1);
252
253         // Check registered confirmed transactions are marked confirmed
254         let new_address = bitcoind.client.get_new_address(Some("test"), Some(AddressType::Legacy)).unwrap().assume_checked();
255         let txid = bitcoind.client.send_to_address(&new_address, Amount::from_sat(5000), None, None, None, None, None, None).unwrap();
256         tx_sync.register_tx(&txid, &new_address.payload.script_pubkey());
257
258         tx_sync.sync(vec![&confirmable]).await.unwrap();
259
260         let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
261         assert_eq!(events.len(), 0);
262         assert!(confirmable.confirmed_txs.lock().unwrap().is_empty());
263         assert!(confirmable.unconfirmed_txs.lock().unwrap().is_empty());
264
265         generate_blocks_and_wait(&bitcoind, &electrsd, 1);
266         tx_sync.sync(vec![&confirmable]).await.unwrap();
267
268         let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
269         assert_eq!(events.len(), 2);
270         assert!(confirmable.confirmed_txs.lock().unwrap().contains_key(&txid));
271         assert!(confirmable.unconfirmed_txs.lock().unwrap().is_empty());
272
273         // Check previously confirmed transactions are marked unconfirmed when they are reorged.
274         let best_block_hash = bitcoind.client.get_best_block_hash().unwrap();
275         bitcoind.client.invalidate_block(&best_block_hash).unwrap();
276
277         // We're getting back to the previous height with a new tip, but best block shouldn't change.
278         generate_blocks_and_wait(&bitcoind, &electrsd, 1);
279         assert_ne!(bitcoind.client.get_best_block_hash().unwrap(), best_block_hash);
280         tx_sync.sync(vec![&confirmable]).await.unwrap();
281         let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
282         assert_eq!(events.len(), 0);
283
284         // Now we're surpassing previous height, getting new tip.
285         generate_blocks_and_wait(&bitcoind, &electrsd, 1);
286         assert_ne!(bitcoind.client.get_best_block_hash().unwrap(), best_block_hash);
287         tx_sync.sync(vec![&confirmable]).await.unwrap();
288
289         // Transaction still confirmed but under new tip.
290         assert!(confirmable.confirmed_txs.lock().unwrap().contains_key(&txid));
291         assert!(confirmable.unconfirmed_txs.lock().unwrap().is_empty());
292
293         // Check we got unconfirmed, then reconfirmed in the meantime.
294         let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
295         assert_eq!(events.len(), 3);
296
297         match events[0] {
298                 TestConfirmableEvent::Unconfirmed(t) => {
299                         assert_eq!(t, txid);
300                 },
301                 _ => panic!("Unexpected event"),
302         }
303
304         match events[1] {
305                 TestConfirmableEvent::BestBlockUpdated(..) => {},
306                 _ => panic!("Unexpected event"),
307         }
308
309         match events[2] {
310                 TestConfirmableEvent::Confirmed(t, _, _) => {
311                         assert_eq!(t, txid);
312                 },
313                 _ => panic!("Unexpected event"),
314         }
315 }