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