|
| 1 | +use crate::esplora::EsploraSyncClient; |
| 2 | +use lightning::chain::{Confirm, Filter}; |
| 3 | +use lightning::chain::transaction::TransactionData; |
| 4 | +use lightning::util::logger::{Logger, Record}; |
| 5 | + |
| 6 | +use electrsd::{bitcoind, bitcoind::BitcoinD, ElectrsD}; |
| 7 | +use bitcoin::{Amount, Txid, BlockHash, BlockHeader}; |
| 8 | +use bitcoin::blockdata::constants::genesis_block; |
| 9 | +use bitcoin::network::constants::Network; |
| 10 | +use electrsd::bitcoind::bitcoincore_rpc::bitcoincore_rpc_json::AddressType; |
| 11 | +use bitcoind::bitcoincore_rpc::RpcApi; |
| 12 | +use electrum_client::ElectrumApi; |
| 13 | + |
| 14 | +use once_cell::sync::OnceCell; |
| 15 | + |
| 16 | +use std::env; |
| 17 | +use std::sync::Mutex; |
| 18 | +use std::time::Duration; |
| 19 | +use std::collections::{HashMap, HashSet}; |
| 20 | + |
| 21 | +static BITCOIND: OnceCell<BitcoinD> = OnceCell::new(); |
| 22 | +static ELECTRSD: OnceCell<ElectrsD> = OnceCell::new(); |
| 23 | +static PREMINE: OnceCell<()> = OnceCell::new(); |
| 24 | +static MINER_LOCK: Mutex<()> = Mutex::new(()); |
| 25 | + |
| 26 | +fn get_bitcoind() -> &'static BitcoinD { |
| 27 | + BITCOIND.get_or_init(|| { |
| 28 | + let bitcoind_exe = |
| 29 | + env::var("BITCOIND_EXE").ok().or_else(|| bitcoind::downloaded_exe_path().ok()).expect( |
| 30 | + "you need to provide an env var BITCOIND_EXE or specify a bitcoind version feature", |
| 31 | + ); |
| 32 | + let mut conf = bitcoind::Conf::default(); |
| 33 | + conf.network = "regtest"; |
| 34 | + BitcoinD::with_conf(bitcoind_exe, &conf).unwrap() |
| 35 | + }) |
| 36 | +} |
| 37 | + |
| 38 | +fn get_electrsd() -> &'static ElectrsD { |
| 39 | + ELECTRSD.get_or_init(|| { |
| 40 | + let bitcoind = get_bitcoind(); |
| 41 | + let electrs_exe = |
| 42 | + env::var("ELECTRS_EXE").ok().or_else(electrsd::downloaded_exe_path).expect( |
| 43 | + "you need to provide env var ELECTRS_EXE or specify an electrsd version feature", |
| 44 | + ); |
| 45 | + let mut conf = electrsd::Conf::default(); |
| 46 | + conf.http_enabled = true; |
| 47 | + conf.network = "regtest"; |
| 48 | + ElectrsD::with_conf(electrs_exe, &bitcoind, &conf).unwrap() |
| 49 | + }) |
| 50 | +} |
| 51 | + |
| 52 | +fn generate_blocks_and_wait(num: usize) { |
| 53 | + let cur_height = get_bitcoind().client.get_block_count().unwrap(); |
| 54 | + generate_blocks(num); |
| 55 | + wait_for_block(cur_height as usize + num); |
| 56 | +} |
| 57 | + |
| 58 | +fn generate_blocks(num: usize) { |
| 59 | + let address = get_bitcoind().client.get_new_address(Some("test"), Some(AddressType::Legacy)).unwrap(); |
| 60 | + let _block_hashes = get_bitcoind().client.generate_to_address(num as u64, &address).unwrap(); |
| 61 | +} |
| 62 | + |
| 63 | +fn wait_for_block(min_height: usize) { |
| 64 | + let mut header = get_electrsd().client.block_headers_subscribe().unwrap(); |
| 65 | + loop { |
| 66 | + if header.height >= min_height { |
| 67 | + break; |
| 68 | + } |
| 69 | + header = exponential_backoff_poll(|| { |
| 70 | + get_electrsd().trigger().unwrap(); |
| 71 | + get_electrsd().client.ping().unwrap(); |
| 72 | + get_electrsd().client.block_headers_pop().unwrap() |
| 73 | + }); |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +fn exponential_backoff_poll<T, F>(mut poll: F) -> T |
| 78 | +where |
| 79 | + F: FnMut() -> Option<T>, |
| 80 | +{ |
| 81 | + let mut delay = Duration::from_millis(64); |
| 82 | + loop { |
| 83 | + match poll() { |
| 84 | + Some(data) => break data, |
| 85 | + None if delay.as_millis() < 512 => delay = delay.mul_f32(2.0), |
| 86 | + None => {} |
| 87 | + } |
| 88 | + |
| 89 | + std::thread::sleep(delay); |
| 90 | + } |
| 91 | +} |
| 92 | + |
| 93 | +fn premine() { |
| 94 | + PREMINE.get_or_init(|| { |
| 95 | + let _miner = MINER_LOCK.lock().unwrap(); |
| 96 | + generate_blocks_and_wait(101); |
| 97 | + }); |
| 98 | +} |
| 99 | + |
| 100 | +#[derive(Debug)] |
| 101 | +enum TestConfirmableEvent { |
| 102 | + Confirmed(Txid, BlockHash, u32), |
| 103 | + Unconfirmed(Txid), |
| 104 | + BestBlockUpdated(BlockHash, u32), |
| 105 | +} |
| 106 | + |
| 107 | +struct TestConfirmable { |
| 108 | + pub confirmed_txs: Mutex<HashMap<Txid, (BlockHash, u32)>>, |
| 109 | + pub unconfirmed_txs: Mutex<HashSet<Txid>>, |
| 110 | + pub best_block: Mutex<(BlockHash, u32)>, |
| 111 | + pub events: Mutex<Vec<TestConfirmableEvent>>, |
| 112 | +} |
| 113 | + |
| 114 | +impl TestConfirmable { |
| 115 | + pub fn new() -> Self { |
| 116 | + let genesis_hash = genesis_block(Network::Regtest).block_hash(); |
| 117 | + Self { |
| 118 | + confirmed_txs: Mutex::new(HashMap::new()), |
| 119 | + unconfirmed_txs: Mutex::new(HashSet::new()), |
| 120 | + best_block: Mutex::new((genesis_hash, 0)), |
| 121 | + events: Mutex::new(Vec::new()), |
| 122 | + } |
| 123 | + } |
| 124 | +} |
| 125 | + |
| 126 | +impl Confirm for TestConfirmable { |
| 127 | + fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData<'_>, height: u32) { |
| 128 | + for (_, tx) in txdata { |
| 129 | + let txid = tx.txid(); |
| 130 | + let block_hash = header.block_hash(); |
| 131 | + self.confirmed_txs.lock().unwrap().insert(txid, (block_hash, height)); |
| 132 | + self.unconfirmed_txs.lock().unwrap().remove(&txid); |
| 133 | + self.events.lock().unwrap().push(TestConfirmableEvent::Confirmed(txid, block_hash, height)); |
| 134 | + } |
| 135 | + } |
| 136 | + |
| 137 | + fn transaction_unconfirmed(&self, txid: &Txid) { |
| 138 | + self.unconfirmed_txs.lock().unwrap().insert(*txid); |
| 139 | + self.confirmed_txs.lock().unwrap().remove(txid); |
| 140 | + self.events.lock().unwrap().push(TestConfirmableEvent::Unconfirmed(*txid)); |
| 141 | + } |
| 142 | + |
| 143 | + fn best_block_updated(&self, header: &BlockHeader, height: u32) { |
| 144 | + let block_hash = header.block_hash(); |
| 145 | + *self.best_block.lock().unwrap() = (block_hash, height); |
| 146 | + self.events.lock().unwrap().push(TestConfirmableEvent::BestBlockUpdated(block_hash, height)); |
| 147 | + } |
| 148 | + |
| 149 | + fn get_relevant_txids(&self) -> Vec<(Txid, Option<BlockHash>)> { |
| 150 | + self.confirmed_txs.lock().unwrap().iter().map(|(&txid, (hash, _))| (txid, Some(*hash))).collect::<Vec<_>>() |
| 151 | + } |
| 152 | +} |
| 153 | + |
| 154 | +pub struct TestLogger {} |
| 155 | + |
| 156 | +impl Logger for TestLogger { |
| 157 | + fn log(&self, _record: &Record) {} |
| 158 | +} |
| 159 | + |
| 160 | +#[test] |
| 161 | +fn test_esplora_syncs() { |
| 162 | + premine(); |
| 163 | + let mut logger = TestLogger {}; |
| 164 | + let esplora_url = format!("http://{}", get_electrsd().esplora_url.as_ref().unwrap()); |
| 165 | + let tx_sync = EsploraSyncClient::new(esplora_url, &mut logger); |
| 166 | + let confirmable = TestConfirmable::new(); |
| 167 | + |
| 168 | + // Check we pick up on new best blocks |
| 169 | + let expected_height = 0u32; |
| 170 | + assert_eq!(confirmable.best_block.lock().unwrap().1, expected_height); |
| 171 | + |
| 172 | + tx_sync.sync(vec![&confirmable]).unwrap(); |
| 173 | + |
| 174 | + let expected_height = get_bitcoind().client.get_block_count().unwrap() as u32; |
| 175 | + assert_eq!(confirmable.best_block.lock().unwrap().1, expected_height); |
| 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 = get_bitcoind().client.get_new_address(Some("test"), Some(AddressType::Legacy)).unwrap(); |
| 182 | + let txid = get_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.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(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 = get_bitcoind().client.get_best_block_hash().unwrap(); |
| 202 | + get_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(1); |
| 206 | + assert_ne!(get_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(1); |
| 213 | + assert_ne!(get_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 | +} |
0 commit comments