2 not(target_os = "windows"),
3 any(feature = "esplora-blocking", feature = "esplora-async", feature = "electrum")
6 use lightning::chain::transaction::{OutPoint, TransactionData};
7 use lightning::chain::{Confirm, Filter, WatchedOutput};
8 use lightning::util::test_utils::TestLogger;
9 #[cfg(feature = "electrum")]
10 use lightning_transaction_sync::ElectrumSyncClient;
11 #[cfg(any(feature = "esplora-blocking", feature = "esplora-async"))]
12 use lightning_transaction_sync::EsploraSyncClient;
14 use bdk_macros::maybe_await;
15 use bitcoin::blockdata::block::Header;
16 use bitcoin::blockdata::constants::genesis_block;
17 use bitcoin::network::Network;
18 use bitcoin::{Amount, BlockHash, Txid};
19 use bitcoind::bitcoincore_rpc::RpcApi;
20 use electrsd::bitcoind::bitcoincore_rpc::bitcoincore_rpc_json::AddressType;
21 use electrsd::{bitcoind, bitcoind::BitcoinD, ElectrsD};
23 use std::collections::{HashMap, HashSet};
26 use std::time::Duration;
28 pub fn setup_bitcoind_and_electrsd() -> (BitcoinD, ElectrsD) {
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",
33 let mut bitcoind_conf = bitcoind::Conf::default();
34 bitcoind_conf.network = "regtest";
35 let bitcoind = BitcoinD::with_conf(bitcoind_exe, &bitcoind_conf).unwrap();
37 let electrs_exe = env::var("ELECTRS_EXE")
39 .or_else(electrsd::downloaded_exe_path)
40 .expect("you need to provide env var ELECTRS_EXE or specify an electrsd version feature");
41 let mut electrsd_conf = electrsd::Conf::default();
42 electrsd_conf.http_enabled = true;
43 electrsd_conf.network = "regtest";
44 let electrsd = ElectrsD::with_conf(electrs_exe, &bitcoind, &electrsd_conf).unwrap();
48 pub fn generate_blocks_and_wait(bitcoind: &BitcoinD, electrsd: &ElectrsD, num: usize) {
49 let cur_height = bitcoind.client.get_block_count().expect("failed to get current block height");
50 let address = bitcoind
52 .get_new_address(Some("test"), Some(AddressType::Legacy))
53 .expect("failed to get new address")
55 // TODO: expect this Result once the WouldBlock issue is resolved upstream.
56 let _block_hashes_res = bitcoind.client.generate_to_address(num as u64, &address);
57 wait_for_block(electrsd, cur_height as usize + num);
60 pub fn wait_for_block(electrsd: &ElectrsD, min_height: usize) {
61 use electrsd::electrum_client::ElectrumApi;
62 let mut header = match electrsd.client.block_headers_subscribe_raw() {
65 // While subscribing should succeed the first time around, we ran into some cases where
66 // it didn't. Since we can't proceed without subscribing, we try again after a delay
67 // and panic if it still fails.
68 std::thread::sleep(Duration::from_secs(1));
71 .block_headers_subscribe_raw()
72 .expect("failed to subscribe to block headers")
76 if header.height >= min_height {
79 header = exponential_backoff_poll(|| {
80 electrsd.trigger().expect("failed to trigger electrsd");
81 electrsd.client.ping().expect("failed to ping electrsd");
82 electrsd.client.block_headers_pop_raw().expect("failed to pop block header")
87 fn exponential_backoff_poll<T, F>(mut poll: F) -> T
89 F: FnMut() -> Option<T>,
91 let mut delay = Duration::from_millis(64);
95 Some(data) => break data,
96 None if delay.as_millis() < 512 => {
97 delay = delay.mul_f32(2.0);
100 None if tries == 10 => panic!("Exceeded our maximum wait time."),
104 std::thread::sleep(delay);
109 enum TestConfirmableEvent {
110 Confirmed(Txid, BlockHash, u32),
112 BestBlockUpdated(BlockHash, u32),
115 struct TestConfirmable {
116 pub confirmed_txs: Mutex<HashMap<Txid, (BlockHash, u32)>>,
117 pub unconfirmed_txs: Mutex<HashSet<Txid>>,
118 pub best_block: Mutex<(BlockHash, u32)>,
119 pub events: Mutex<Vec<TestConfirmableEvent>>,
122 impl TestConfirmable {
123 pub fn new() -> Self {
124 let genesis_hash = genesis_block(Network::Regtest).block_hash();
126 confirmed_txs: Mutex::new(HashMap::new()),
127 unconfirmed_txs: Mutex::new(HashSet::new()),
128 best_block: Mutex::new((genesis_hash, 0)),
129 events: Mutex::new(Vec::new()),
134 impl Confirm for TestConfirmable {
135 fn transactions_confirmed(&self, header: &Header, txdata: &TransactionData<'_>, height: u32) {
136 for (_, tx) in txdata {
137 let txid = tx.txid();
138 let block_hash = header.block_hash();
139 self.confirmed_txs.lock().unwrap().insert(txid, (block_hash, height));
140 self.unconfirmed_txs.lock().unwrap().remove(&txid);
141 let event = TestConfirmableEvent::Confirmed(txid, block_hash, height);
142 self.events.lock().unwrap().push(event);
146 fn transaction_unconfirmed(&self, txid: &Txid) {
147 self.unconfirmed_txs.lock().unwrap().insert(*txid);
148 self.confirmed_txs.lock().unwrap().remove(txid);
149 self.events.lock().unwrap().push(TestConfirmableEvent::Unconfirmed(*txid));
152 fn best_block_updated(&self, header: &Header, height: u32) {
153 let block_hash = header.block_hash();
154 *self.best_block.lock().unwrap() = (block_hash, height);
155 let event = TestConfirmableEvent::BestBlockUpdated(block_hash, height);
156 self.events.lock().unwrap().push(event);
159 fn get_relevant_txids(&self) -> Vec<(Txid, u32, Option<BlockHash>)> {
160 let lock = self.confirmed_txs.lock().unwrap();
161 lock.iter().map(|(&txid, (hash, height))| (txid, *height, Some(*hash))).collect()
165 macro_rules! test_syncing {
166 ($tx_sync: expr, $confirmable: expr, $bitcoind: expr, $electrsd: expr) => {{
167 // Check we pick up on new best blocks
168 assert_eq!($confirmable.best_block.lock().unwrap().1, 0);
170 maybe_await!($tx_sync.sync(vec![&$confirmable])).unwrap();
171 assert_eq!($confirmable.best_block.lock().unwrap().1, 102);
173 let events = std::mem::take(&mut *$confirmable.events.lock().unwrap());
174 assert_eq!(events.len(), 1);
176 // Check registered confirmed transactions are marked confirmed
177 let new_address = $bitcoind
179 .get_new_address(Some("test"), Some(AddressType::Legacy))
186 Amount::from_sat(5000),
195 let second_txid = $bitcoind
199 Amount::from_sat(5000),
208 $tx_sync.register_tx(&txid, &new_address.payload().script_pubkey());
210 maybe_await!($tx_sync.sync(vec![&$confirmable])).unwrap();
212 let events = std::mem::take(&mut *$confirmable.events.lock().unwrap());
213 assert_eq!(events.len(), 0);
214 assert!($confirmable.confirmed_txs.lock().unwrap().is_empty());
215 assert!($confirmable.unconfirmed_txs.lock().unwrap().is_empty());
217 generate_blocks_and_wait(&$bitcoind, &$electrsd, 1);
218 maybe_await!($tx_sync.sync(vec![&$confirmable])).unwrap();
220 let events = std::mem::take(&mut *$confirmable.events.lock().unwrap());
221 assert_eq!(events.len(), 2);
222 assert!($confirmable.confirmed_txs.lock().unwrap().contains_key(&txid));
223 assert!($confirmable.unconfirmed_txs.lock().unwrap().is_empty());
225 // Now take an arbitrary output of the second transaction and check we'll confirm its spend.
226 let tx_res = $bitcoind.client.get_transaction(&second_txid, None).unwrap();
227 let block_hash = tx_res.info.blockhash.unwrap();
228 let tx = tx_res.transaction().unwrap();
229 let prev_outpoint = tx.input.first().unwrap().previous_output;
230 let prev_tx = $bitcoind
232 .get_transaction(&prev_outpoint.txid, None)
236 let prev_script_pubkey = prev_tx.output[prev_outpoint.vout as usize].script_pubkey.clone();
237 let output = WatchedOutput {
238 block_hash: Some(block_hash),
239 outpoint: OutPoint { txid: prev_outpoint.txid, index: prev_outpoint.vout as u16 },
240 script_pubkey: prev_script_pubkey,
243 $tx_sync.register_output(output);
244 maybe_await!($tx_sync.sync(vec![&$confirmable])).unwrap();
246 let events = std::mem::take(&mut *$confirmable.events.lock().unwrap());
247 assert_eq!(events.len(), 1);
248 assert!($confirmable.confirmed_txs.lock().unwrap().contains_key(&second_txid));
249 assert_eq!($confirmable.confirmed_txs.lock().unwrap().len(), 2);
250 assert!($confirmable.unconfirmed_txs.lock().unwrap().is_empty());
252 // Check previously confirmed transactions are marked unconfirmed when they are reorged.
253 let best_block_hash = $bitcoind.client.get_best_block_hash().unwrap();
254 $bitcoind.client.invalidate_block(&best_block_hash).unwrap();
256 // We're getting back to the previous height with a new tip, but best block shouldn't change.
257 generate_blocks_and_wait(&$bitcoind, &$electrsd, 1);
258 assert_ne!($bitcoind.client.get_best_block_hash().unwrap(), best_block_hash);
259 maybe_await!($tx_sync.sync(vec![&$confirmable])).unwrap();
260 let events = std::mem::take(&mut *$confirmable.events.lock().unwrap());
261 assert_eq!(events.len(), 0);
263 // Now we're surpassing previous height, getting new tip.
264 generate_blocks_and_wait(&$bitcoind, &$electrsd, 1);
265 assert_ne!($bitcoind.client.get_best_block_hash().unwrap(), best_block_hash);
266 maybe_await!($tx_sync.sync(vec![&$confirmable])).unwrap();
268 // Transactions still confirmed but under new tip.
269 assert!($confirmable.confirmed_txs.lock().unwrap().contains_key(&txid));
270 assert!($confirmable.confirmed_txs.lock().unwrap().contains_key(&second_txid));
271 assert!($confirmable.unconfirmed_txs.lock().unwrap().is_empty());
273 // Check we got unconfirmed, then reconfirmed in the meantime.
274 let mut seen_txids = HashSet::new();
275 let events = std::mem::take(&mut *$confirmable.events.lock().unwrap());
276 assert_eq!(events.len(), 5);
279 TestConfirmableEvent::Unconfirmed(t) => {
280 assert!(t == txid || t == second_txid);
281 assert!(seen_txids.insert(t));
283 _ => panic!("Unexpected event"),
287 TestConfirmableEvent::Unconfirmed(t) => {
288 assert!(t == txid || t == second_txid);
289 assert!(seen_txids.insert(t));
291 _ => panic!("Unexpected event"),
295 TestConfirmableEvent::BestBlockUpdated(..) => {},
296 _ => panic!("Unexpected event"),
300 TestConfirmableEvent::Confirmed(t, _, _) => {
301 assert!(t == txid || t == second_txid);
302 assert!(seen_txids.remove(&t));
304 _ => panic!("Unexpected event"),
308 TestConfirmableEvent::Confirmed(t, _, _) => {
309 assert!(t == txid || t == second_txid);
310 assert!(seen_txids.remove(&t));
312 _ => panic!("Unexpected event"),
315 assert_eq!(seen_txids.len(), 0);
320 #[cfg(feature = "esplora-blocking")]
321 fn test_esplora_syncs() {
322 let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
323 generate_blocks_and_wait(&bitcoind, &electrsd, 101);
324 let mut logger = TestLogger::new();
325 let esplora_url = format!("http://{}", electrsd.esplora_url.as_ref().unwrap());
326 let tx_sync = EsploraSyncClient::new(esplora_url, &mut logger);
327 let confirmable = TestConfirmable::new();
329 test_syncing!(tx_sync, confirmable, bitcoind, electrsd);
333 #[cfg(feature = "esplora-async")]
334 async fn test_esplora_syncs() {
335 let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
336 generate_blocks_and_wait(&bitcoind, &electrsd, 101);
337 let mut logger = TestLogger::new();
338 let esplora_url = format!("http://{}", electrsd.esplora_url.as_ref().unwrap());
339 let tx_sync = EsploraSyncClient::new(esplora_url, &mut logger);
340 let confirmable = TestConfirmable::new();
342 test_syncing!(tx_sync, confirmable, bitcoind, electrsd);
346 #[cfg(feature = "electrum")]
347 fn test_electrum_syncs() {
348 let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
349 generate_blocks_and_wait(&bitcoind, &electrsd, 101);
350 let mut logger = TestLogger::new();
351 let electrum_url = format!("tcp://{}", electrsd.electrum_url);
352 let tx_sync = ElectrumSyncClient::new(electrum_url, &mut logger).unwrap();
353 let confirmable = TestConfirmable::new();
354 test_syncing!(tx_sync, confirmable, bitcoind, electrsd);