Merge pull request #1977 from jkczyz/2023-01-offers-fuzz
[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 once_cell::sync::OnceCell;
16
17 use std::env;
18 use std::sync::Mutex;
19 use std::time::Duration;
20 use std::collections::{HashMap, HashSet};
21
22 static BITCOIND: OnceCell<BitcoinD> = OnceCell::new();
23 static ELECTRSD: OnceCell<ElectrsD> = OnceCell::new();
24 static PREMINE: OnceCell<()> = OnceCell::new();
25 static MINER_LOCK: OnceCell<Mutex<()>> = OnceCell::new();
26
27 fn get_bitcoind() -> &'static BitcoinD {
28         BITCOIND.get_or_init(|| {
29                 let bitcoind_exe =
30                         env::var("BITCOIND_EXE").ok().or_else(|| bitcoind::downloaded_exe_path().ok()).expect(
31                                 "you need to provide an env var BITCOIND_EXE or specify a bitcoind version feature",
32                                 );
33                 let mut conf = bitcoind::Conf::default();
34                 conf.network = "regtest";
35                 BitcoinD::with_conf(bitcoind_exe, &conf).unwrap()
36         })
37 }
38
39 fn get_electrsd() -> &'static ElectrsD {
40         ELECTRSD.get_or_init(|| {
41                 let bitcoind = get_bitcoind();
42                 let electrs_exe =
43                         env::var("ELECTRS_EXE").ok().or_else(electrsd::downloaded_exe_path).expect(
44                                 "you need to provide env var ELECTRS_EXE or specify an electrsd version feature",
45                         );
46                 let mut conf = electrsd::Conf::default();
47                 conf.http_enabled = true;
48                 conf.network = "regtest";
49                 ElectrsD::with_conf(electrs_exe, &bitcoind, &conf).unwrap()
50         })
51 }
52
53 fn generate_blocks_and_wait(num: usize) {
54         let miner_lock = MINER_LOCK.get_or_init(|| Mutex::new(()));
55         let _miner = miner_lock.lock().unwrap();
56         let cur_height = get_bitcoind().client.get_block_count().unwrap();
57         let address = get_bitcoind().client.get_new_address(Some("test"), Some(AddressType::Legacy)).unwrap();
58         let _block_hashes = get_bitcoind().client.generate_to_address(num as u64, &address).unwrap();
59         wait_for_block(cur_height as usize + num);
60 }
61
62 fn wait_for_block(min_height: usize) {
63         let mut header = get_electrsd().client.block_headers_subscribe().unwrap();
64         loop {
65                 if header.height >= min_height {
66                         break;
67                 }
68                 header = exponential_backoff_poll(|| {
69                         get_electrsd().trigger().unwrap();
70                         get_electrsd().client.ping().unwrap();
71                         get_electrsd().client.block_headers_pop().unwrap()
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 fn premine() {
98         PREMINE.get_or_init(|| {
99                 generate_blocks_and_wait(101);
100         });
101 }
102
103 #[derive(Debug)]
104 enum TestConfirmableEvent {
105         Confirmed(Txid, BlockHash, u32),
106         Unconfirmed(Txid),
107         BestBlockUpdated(BlockHash, u32),
108 }
109
110 struct TestConfirmable {
111         pub confirmed_txs: Mutex<HashMap<Txid, (BlockHash, u32)>>,
112         pub unconfirmed_txs: Mutex<HashSet<Txid>>,
113         pub best_block: Mutex<(BlockHash, u32)>,
114         pub events: Mutex<Vec<TestConfirmableEvent>>,
115 }
116
117 impl TestConfirmable {
118         pub fn new() -> Self {
119                 let genesis_hash = genesis_block(Network::Regtest).block_hash();
120                 Self {
121                         confirmed_txs: Mutex::new(HashMap::new()),
122                         unconfirmed_txs: Mutex::new(HashSet::new()),
123                         best_block: Mutex::new((genesis_hash, 0)),
124                         events: Mutex::new(Vec::new()),
125                 }
126         }
127 }
128
129 impl Confirm for TestConfirmable {
130         fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData<'_>, height: u32) {
131                 for (_, tx) in txdata {
132                         let txid = tx.txid();
133                         let block_hash = header.block_hash();
134                         self.confirmed_txs.lock().unwrap().insert(txid, (block_hash, height));
135                         self.unconfirmed_txs.lock().unwrap().remove(&txid);
136                         self.events.lock().unwrap().push(TestConfirmableEvent::Confirmed(txid, block_hash, height));
137                 }
138         }
139
140         fn transaction_unconfirmed(&self, txid: &Txid) {
141                 self.unconfirmed_txs.lock().unwrap().insert(*txid);
142                 self.confirmed_txs.lock().unwrap().remove(txid);
143                 self.events.lock().unwrap().push(TestConfirmableEvent::Unconfirmed(*txid));
144         }
145
146         fn best_block_updated(&self, header: &BlockHeader, height: u32) {
147                 let block_hash = header.block_hash();
148                 *self.best_block.lock().unwrap() = (block_hash, height);
149                 self.events.lock().unwrap().push(TestConfirmableEvent::BestBlockUpdated(block_hash, height));
150         }
151
152         fn get_relevant_txids(&self) -> Vec<(Txid, Option<BlockHash>)> {
153                 self.confirmed_txs.lock().unwrap().iter().map(|(&txid, (hash, _))| (txid, Some(*hash))).collect::<Vec<_>>()
154         }
155 }
156
157 pub struct TestLogger {}
158
159 impl Logger for TestLogger {
160         fn log(&self, record: &Record) {
161                 println!("{} -- {}",
162                                 record.level,
163                                 record.args);
164         }
165 }
166
167 #[test]
168 #[cfg(feature = "esplora-blocking")]
169 fn test_esplora_syncs() {
170         premine();
171         let mut logger = TestLogger {};
172         let esplora_url = format!("http://{}", get_electrsd().esplora_url.as_ref().unwrap());
173         let tx_sync = EsploraSyncClient::new(esplora_url, &mut logger);
174         let confirmable = TestConfirmable::new();
175
176         // Check we pick up on new best blocks
177         let expected_height = 0u32;
178         assert_eq!(confirmable.best_block.lock().unwrap().1, expected_height);
179
180         tx_sync.sync(vec![&confirmable]).unwrap();
181
182         let expected_height = get_bitcoind().client.get_block_count().unwrap() as u32;
183         assert_eq!(confirmable.best_block.lock().unwrap().1, expected_height);
184
185         let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
186         assert_eq!(events.len(), 1);
187
188         // Check registered confirmed transactions are marked confirmed
189         let new_address = get_bitcoind().client.get_new_address(Some("test"), Some(AddressType::Legacy)).unwrap();
190         let txid = get_bitcoind().client.send_to_address(&new_address, Amount::from_sat(5000), None, None, None, None, None, None).unwrap();
191         tx_sync.register_tx(&txid, &new_address.script_pubkey());
192
193         tx_sync.sync(vec![&confirmable]).unwrap();
194
195         let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
196         assert_eq!(events.len(), 0);
197         assert!(confirmable.confirmed_txs.lock().unwrap().is_empty());
198         assert!(confirmable.unconfirmed_txs.lock().unwrap().is_empty());
199
200         generate_blocks_and_wait(1);
201         tx_sync.sync(vec![&confirmable]).unwrap();
202
203         let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
204         assert_eq!(events.len(), 2);
205         assert!(confirmable.confirmed_txs.lock().unwrap().contains_key(&txid));
206         assert!(confirmable.unconfirmed_txs.lock().unwrap().is_empty());
207
208         // Check previously confirmed transactions are marked unconfirmed when they are reorged.
209         let best_block_hash = get_bitcoind().client.get_best_block_hash().unwrap();
210         get_bitcoind().client.invalidate_block(&best_block_hash).unwrap();
211
212         // We're getting back to the previous height with a new tip, but best block shouldn't change.
213         generate_blocks_and_wait(1);
214         assert_ne!(get_bitcoind().client.get_best_block_hash().unwrap(), best_block_hash);
215         tx_sync.sync(vec![&confirmable]).unwrap();
216         let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
217         assert_eq!(events.len(), 0);
218
219         // Now we're surpassing previous height, getting new tip.
220         generate_blocks_and_wait(1);
221         assert_ne!(get_bitcoind().client.get_best_block_hash().unwrap(), best_block_hash);
222         tx_sync.sync(vec![&confirmable]).unwrap();
223
224         // Transaction still confirmed but under new tip.
225         assert!(confirmable.confirmed_txs.lock().unwrap().contains_key(&txid));
226         assert!(confirmable.unconfirmed_txs.lock().unwrap().is_empty());
227
228         // Check we got unconfirmed, then reconfirmed in the meantime.
229         let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
230         assert_eq!(events.len(), 3);
231
232         match events[0] {
233                 TestConfirmableEvent::Unconfirmed(t) => {
234                         assert_eq!(t, txid);
235                 },
236                 _ => panic!("Unexpected event"),
237         }
238
239         match events[1] {
240                 TestConfirmableEvent::BestBlockUpdated(..) => {},
241                 _ => panic!("Unexpected event"),
242         }
243
244         match events[2] {
245                 TestConfirmableEvent::Confirmed(t, _, _) => {
246                         assert_eq!(t, txid);
247                 },
248                 _ => panic!("Unexpected event"),
249         }
250 }
251
252 #[tokio::test]
253 #[cfg(feature = "esplora-async")]
254 async fn test_esplora_syncs() {
255         premine();
256         let mut logger = TestLogger {};
257         let esplora_url = format!("http://{}", get_electrsd().esplora_url.as_ref().unwrap());
258         let tx_sync = EsploraSyncClient::new(esplora_url, &mut logger);
259         let confirmable = TestConfirmable::new();
260
261         // Check we pick up on new best blocks
262         let expected_height = 0u32;
263         assert_eq!(confirmable.best_block.lock().unwrap().1, expected_height);
264
265         tx_sync.sync(vec![&confirmable]).await.unwrap();
266
267         let expected_height = get_bitcoind().client.get_block_count().unwrap() as u32;
268         assert_eq!(confirmable.best_block.lock().unwrap().1, expected_height);
269
270         let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
271         assert_eq!(events.len(), 1);
272
273         // Check registered confirmed transactions are marked confirmed
274         let new_address = get_bitcoind().client.get_new_address(Some("test"), Some(AddressType::Legacy)).unwrap();
275         let txid = get_bitcoind().client.send_to_address(&new_address, Amount::from_sat(5000), None, None, None, None, None, None).unwrap();
276         tx_sync.register_tx(&txid, &new_address.script_pubkey());
277
278         tx_sync.sync(vec![&confirmable]).await.unwrap();
279
280         let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
281         assert_eq!(events.len(), 0);
282         assert!(confirmable.confirmed_txs.lock().unwrap().is_empty());
283         assert!(confirmable.unconfirmed_txs.lock().unwrap().is_empty());
284
285         generate_blocks_and_wait(1);
286         tx_sync.sync(vec![&confirmable]).await.unwrap();
287
288         let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
289         assert_eq!(events.len(), 2);
290         assert!(confirmable.confirmed_txs.lock().unwrap().contains_key(&txid));
291         assert!(confirmable.unconfirmed_txs.lock().unwrap().is_empty());
292
293         // Check previously confirmed transactions are marked unconfirmed when they are reorged.
294         let best_block_hash = get_bitcoind().client.get_best_block_hash().unwrap();
295         get_bitcoind().client.invalidate_block(&best_block_hash).unwrap();
296
297         // We're getting back to the previous height with a new tip, but best block shouldn't change.
298         generate_blocks_and_wait(1);
299         assert_ne!(get_bitcoind().client.get_best_block_hash().unwrap(), best_block_hash);
300         tx_sync.sync(vec![&confirmable]).await.unwrap();
301         let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
302         assert_eq!(events.len(), 0);
303
304         // Now we're surpassing previous height, getting new tip.
305         generate_blocks_and_wait(1);
306         assert_ne!(get_bitcoind().client.get_best_block_hash().unwrap(), best_block_hash);
307         tx_sync.sync(vec![&confirmable]).await.unwrap();
308
309         // Transaction still confirmed but under new tip.
310         assert!(confirmable.confirmed_txs.lock().unwrap().contains_key(&txid));
311         assert!(confirmable.unconfirmed_txs.lock().unwrap().is_empty());
312
313         // Check we got unconfirmed, then reconfirmed in the meantime.
314         let events = std::mem::take(&mut *confirmable.events.lock().unwrap());
315         assert_eq!(events.len(), 3);
316
317         match events[0] {
318                 TestConfirmableEvent::Unconfirmed(t) => {
319                         assert_eq!(t, txid);
320                 },
321                 _ => panic!("Unexpected event"),
322         }
323
324         match events[1] {
325                 TestConfirmableEvent::BestBlockUpdated(..) => {},
326                 _ => panic!("Unexpected event"),
327         }
328
329         match events[2] {
330                 TestConfirmableEvent::Confirmed(t, _, _) => {
331                         assert_eq!(t, txid);
332                 },
333                 _ => panic!("Unexpected event"),
334         }
335 }