Drop `test_esplora_connects_to_public_server`
[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::logger::{Logger, Record};
6
7 use electrsd::{bitcoind, bitcoind::BitcoinD, ElectrsD};
8 use bitcoin::{Amount, Txid, BlockHash, BlockHeader};
9 use bitcoin::blockdata::constants::genesis_block;
10 use bitcoin::network::constants::Network;
11 use electrsd::bitcoind::bitcoincore_rpc::bitcoincore_rpc_json::AddressType;
12 use bitcoind::bitcoincore_rpc::RpcApi;
13 use electrum_client::ElectrumApi;
14
15 use std::env;
16 use std::sync::Mutex;
17 use std::time::Duration;
18 use std::collections::{HashMap, HashSet};
19
20 pub fn setup_bitcoind_and_electrsd() -> (BitcoinD, ElectrsD) {
21         let bitcoind_exe =
22                 env::var("BITCOIND_EXE").ok().or_else(|| bitcoind::downloaded_exe_path().ok()).expect(
23                         "you need to provide an env var BITCOIND_EXE or specify a bitcoind version feature",
24                 );
25         let mut bitcoind_conf = bitcoind::Conf::default();
26         bitcoind_conf.network = "regtest";
27         let bitcoind = BitcoinD::with_conf(bitcoind_exe, &bitcoind_conf).unwrap();
28
29         let electrs_exe = env::var("ELECTRS_EXE")
30                 .ok()
31                 .or_else(electrsd::downloaded_exe_path)
32                 .expect("you need to provide env var ELECTRS_EXE or specify an electrsd version feature");
33         let mut electrsd_conf = electrsd::Conf::default();
34         electrsd_conf.http_enabled = true;
35         electrsd_conf.network = "regtest";
36         let electrsd = ElectrsD::with_conf(electrs_exe, &bitcoind, &electrsd_conf).unwrap();
37         (bitcoind, electrsd)
38 }
39
40 pub fn generate_blocks_and_wait(bitcoind: &BitcoinD, electrsd: &ElectrsD, num: usize) {
41         let cur_height = bitcoind.client.get_block_count().expect("failed to get current block height");
42         let address = bitcoind
43                 .client
44                 .get_new_address(Some("test"), Some(AddressType::Legacy))
45                 .expect("failed to get new address");
46         // TODO: expect this Result once the WouldBlock issue is resolved upstream.
47         let _block_hashes_res = bitcoind.client.generate_to_address(num as u64, &address);
48         wait_for_block(electrsd, cur_height as usize + num);
49 }
50
51 pub fn wait_for_block(electrsd: &ElectrsD, min_height: usize) {
52         let mut header = match electrsd.client.block_headers_subscribe() {
53                 Ok(header) => header,
54                 Err(_) => {
55                         // While subscribing should succeed the first time around, we ran into some cases where
56                         // it didn't. Since we can't proceed without subscribing, we try again after a delay
57                         // and panic if it still fails.
58                         std::thread::sleep(Duration::from_secs(1));
59                         electrsd.client.block_headers_subscribe().expect("failed to subscribe to block headers")
60                 }
61         };
62         loop {
63                 if header.height >= min_height {
64                         break;
65                 }
66                 header = exponential_backoff_poll(|| {
67                         electrsd.trigger().expect("failed to trigger electrsd");
68                         electrsd.client.ping().expect("failed to ping electrsd");
69                         electrsd.client.block_headers_pop().expect("failed to pop block header")
70                 });
71         }
72 }
73
74 fn exponential_backoff_poll<T, F>(mut poll: F) -> T
75 where
76         F: FnMut() -> Option<T>,
77 {
78         let mut delay = Duration::from_millis(64);
79         let mut tries = 0;
80         loop {
81                 match poll() {
82                         Some(data) => break data,
83                         None if delay.as_millis() < 512 => {
84                                 delay = delay.mul_f32(2.0);
85                                 tries += 1;
86                         }
87                         None if tries == 10 => panic!("Exceeded our maximum wait time."),
88                         None => tries += 1,
89                 }
90
91                 std::thread::sleep(delay);
92         }
93 }
94
95 #[derive(Debug)]
96 enum TestConfirmableEvent {
97         Confirmed(Txid, BlockHash, u32),
98         Unconfirmed(Txid),
99         BestBlockUpdated(BlockHash, u32),
100 }
101
102 struct TestConfirmable {
103         pub confirmed_txs: Mutex<HashMap<Txid, (BlockHash, u32)>>,
104         pub unconfirmed_txs: Mutex<HashSet<Txid>>,
105         pub best_block: Mutex<(BlockHash, u32)>,
106         pub events: Mutex<Vec<TestConfirmableEvent>>,
107 }
108
109 impl TestConfirmable {
110         pub fn new() -> Self {
111                 let genesis_hash = genesis_block(Network::Regtest).block_hash();
112                 Self {
113                         confirmed_txs: Mutex::new(HashMap::new()),
114                         unconfirmed_txs: Mutex::new(HashSet::new()),
115                         best_block: Mutex::new((genesis_hash, 0)),
116                         events: Mutex::new(Vec::new()),
117                 }
118         }
119 }
120
121 impl Confirm for TestConfirmable {
122         fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData<'_>, height: u32) {
123                 for (_, tx) in txdata {
124                         let txid = tx.txid();
125                         let block_hash = header.block_hash();
126                         self.confirmed_txs.lock().unwrap().insert(txid, (block_hash, height));
127                         self.unconfirmed_txs.lock().unwrap().remove(&txid);
128                         self.events.lock().unwrap().push(TestConfirmableEvent::Confirmed(txid, block_hash, height));
129                 }
130         }
131
132         fn transaction_unconfirmed(&self, txid: &Txid) {
133                 self.unconfirmed_txs.lock().unwrap().insert(*txid);
134                 self.confirmed_txs.lock().unwrap().remove(txid);
135                 self.events.lock().unwrap().push(TestConfirmableEvent::Unconfirmed(*txid));
136         }
137
138         fn best_block_updated(&self, header: &BlockHeader, height: u32) {
139                 let block_hash = header.block_hash();
140                 *self.best_block.lock().unwrap() = (block_hash, height);
141                 self.events.lock().unwrap().push(TestConfirmableEvent::BestBlockUpdated(block_hash, height));
142         }
143
144         fn get_relevant_txids(&self) -> Vec<(Txid, Option<BlockHash>)> {
145                 self.confirmed_txs.lock().unwrap().iter().map(|(&txid, (hash, _))| (txid, Some(*hash))).collect::<Vec<_>>()
146         }
147 }
148
149 pub struct TestLogger {}
150
151 impl Logger for TestLogger {
152         fn log(&self, record: &Record) {
153                 println!("{} -- {}",
154                                 record.level,
155                                 record.args);
156         }
157 }
158
159 #[test]
160 #[cfg(feature = "esplora-blocking")]
161 fn test_esplora_syncs() {
162         let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
163         generate_blocks_and_wait(&bitcoind, &electrsd, 101);
164         let mut logger = TestLogger {};
165         let esplora_url = format!("http://{}", electrsd.esplora_url.as_ref().unwrap());
166         let tx_sync = EsploraSyncClient::new(esplora_url, &mut logger);
167         let confirmable = TestConfirmable::new();
168
169         // Check we pick up on new best blocks
170         assert_eq!(confirmable.best_block.lock().unwrap().1, 0);
171
172         tx_sync.sync(vec![&confirmable]).unwrap();
173         assert_eq!(confirmable.best_block.lock().unwrap().1, 102);
174
175         let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
176         assert_eq!(events.len(), 1);
177
178         // Check registered confirmed transactions are marked confirmed
179         let new_address = bitcoind.client.get_new_address(Some("test"), Some(AddressType::Legacy)).unwrap();
180         let txid = bitcoind.client.send_to_address(&new_address, Amount::from_sat(5000), None, None, None, None, None, None).unwrap();
181         tx_sync.register_tx(&txid, &new_address.script_pubkey());
182
183         tx_sync.sync(vec![&confirmable]).unwrap();
184
185         let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
186         assert_eq!(events.len(), 0);
187         assert!(confirmable.confirmed_txs.lock().unwrap().is_empty());
188         assert!(confirmable.unconfirmed_txs.lock().unwrap().is_empty());
189
190         generate_blocks_and_wait(&bitcoind, &electrsd, 1);
191         tx_sync.sync(vec![&confirmable]).unwrap();
192
193         let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
194         assert_eq!(events.len(), 2);
195         assert!(confirmable.confirmed_txs.lock().unwrap().contains_key(&txid));
196         assert!(confirmable.unconfirmed_txs.lock().unwrap().is_empty());
197
198         // Check previously confirmed transactions are marked unconfirmed when they are reorged.
199         let best_block_hash = bitcoind.client.get_best_block_hash().unwrap();
200         bitcoind.client.invalidate_block(&best_block_hash).unwrap();
201
202         // We're getting back to the previous height with a new tip, but best block shouldn't change.
203         generate_blocks_and_wait(&bitcoind, &electrsd, 1);
204         assert_ne!(bitcoind.client.get_best_block_hash().unwrap(), best_block_hash);
205         tx_sync.sync(vec![&confirmable]).unwrap();
206         let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
207         assert_eq!(events.len(), 0);
208
209         // Now we're surpassing previous height, getting new tip.
210         generate_blocks_and_wait(&bitcoind, &electrsd, 1);
211         assert_ne!(bitcoind.client.get_best_block_hash().unwrap(), best_block_hash);
212         tx_sync.sync(vec![&confirmable]).unwrap();
213
214         // Transaction still confirmed but under new tip.
215         assert!(confirmable.confirmed_txs.lock().unwrap().contains_key(&txid));
216         assert!(confirmable.unconfirmed_txs.lock().unwrap().is_empty());
217
218         // Check we got unconfirmed, then reconfirmed in the meantime.
219         let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
220         assert_eq!(events.len(), 3);
221
222         match events[0] {
223                 TestConfirmableEvent::Unconfirmed(t) => {
224                         assert_eq!(t, txid);
225                 },
226                 _ => panic!("Unexpected event"),
227         }
228
229         match events[1] {
230                 TestConfirmableEvent::BestBlockUpdated(..) => {},
231                 _ => panic!("Unexpected event"),
232         }
233
234         match events[2] {
235                 TestConfirmableEvent::Confirmed(t, _, _) => {
236                         assert_eq!(t, txid);
237                 },
238                 _ => panic!("Unexpected event"),
239         }
240 }
241
242 #[tokio::test]
243 #[cfg(feature = "esplora-async")]
244 async fn test_esplora_syncs() {
245         let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
246         generate_blocks_and_wait(&bitcoind, &electrsd, 101);
247         let mut logger = TestLogger {};
248         let esplora_url = format!("http://{}", electrsd.esplora_url.as_ref().unwrap());
249         let tx_sync = EsploraSyncClient::new(esplora_url, &mut logger);
250         let confirmable = TestConfirmable::new();
251
252         // Check we pick up on new best blocks
253         assert_eq!(confirmable.best_block.lock().unwrap().1, 0);
254
255         tx_sync.sync(vec![&confirmable]).await.unwrap();
256         assert_eq!(confirmable.best_block.lock().unwrap().1, 102);
257
258         let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
259         assert_eq!(events.len(), 1);
260
261         // Check registered confirmed transactions are marked confirmed
262         let new_address = bitcoind.client.get_new_address(Some("test"), Some(AddressType::Legacy)).unwrap();
263         let txid = bitcoind.client.send_to_address(&new_address, Amount::from_sat(5000), None, None, None, None, None, None).unwrap();
264         tx_sync.register_tx(&txid, &new_address.script_pubkey());
265
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(), 0);
270         assert!(confirmable.confirmed_txs.lock().unwrap().is_empty());
271         assert!(confirmable.unconfirmed_txs.lock().unwrap().is_empty());
272
273         generate_blocks_and_wait(&bitcoind, &electrsd, 1);
274         tx_sync.sync(vec![&confirmable]).await.unwrap();
275
276         let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
277         assert_eq!(events.len(), 2);
278         assert!(confirmable.confirmed_txs.lock().unwrap().contains_key(&txid));
279         assert!(confirmable.unconfirmed_txs.lock().unwrap().is_empty());
280
281         // Check previously confirmed transactions are marked unconfirmed when they are reorged.
282         let best_block_hash = bitcoind.client.get_best_block_hash().unwrap();
283         bitcoind.client.invalidate_block(&best_block_hash).unwrap();
284
285         // We're getting back to the previous height with a new tip, but best block shouldn't change.
286         generate_blocks_and_wait(&bitcoind, &electrsd, 1);
287         assert_ne!(bitcoind.client.get_best_block_hash().unwrap(), best_block_hash);
288         tx_sync.sync(vec![&confirmable]).await.unwrap();
289         let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
290         assert_eq!(events.len(), 0);
291
292         // Now we're surpassing previous height, getting new tip.
293         generate_blocks_and_wait(&bitcoind, &electrsd, 1);
294         assert_ne!(bitcoind.client.get_best_block_hash().unwrap(), best_block_hash);
295         tx_sync.sync(vec![&confirmable]).await.unwrap();
296
297         // Transaction still confirmed but under new tip.
298         assert!(confirmable.confirmed_txs.lock().unwrap().contains_key(&txid));
299         assert!(confirmable.unconfirmed_txs.lock().unwrap().is_empty());
300
301         // Check we got unconfirmed, then reconfirmed in the meantime.
302         let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
303         assert_eq!(events.len(), 3);
304
305         match events[0] {
306                 TestConfirmableEvent::Unconfirmed(t) => {
307                         assert_eq!(t, txid);
308                 },
309                 _ => panic!("Unexpected event"),
310         }
311
312         match events[1] {
313                 TestConfirmableEvent::BestBlockUpdated(..) => {},
314                 _ => panic!("Unexpected event"),
315         }
316
317         match events[2] {
318                 TestConfirmableEvent::Confirmed(t, _, _) => {
319                         assert_eq!(t, txid);
320                 },
321                 _ => panic!("Unexpected event"),
322         }
323 }