|
| 1 | +pub mod utils; |
| 2 | + |
| 3 | +#[cfg(test)] |
| 4 | +mod tests { |
| 5 | + use std::{ |
| 6 | + sync::mpsc::TryRecvError, |
| 7 | + time::{Duration, Instant}, |
| 8 | + }; |
| 9 | + |
| 10 | + use crate::utils::SpaceD; |
| 11 | + use anyhow::Result; |
| 12 | + use bitcoind::bitcoincore_rpc::RpcApi; |
| 13 | + use protocol::constants::ChainAnchor; |
| 14 | + use reqwest::blocking::Client; |
| 15 | + use spaced::source::{BitcoinRpc, BitcoinRpcAuth, BlockEvent, BlockFetcher}; |
| 16 | + use wallet::bitcoin::Network; |
| 17 | + |
| 18 | + #[test] |
| 19 | + fn test_block_fetching_from_bitcoin_rpc() -> Result<()> { |
| 20 | + let spaced = SpaceD::new()?; |
| 21 | + let fetcher_rpc = BitcoinRpc::new( |
| 22 | + &spaced.bitcoind.rpc_url(), |
| 23 | + BitcoinRpcAuth::UserPass("user".to_string(), "password".to_string()), |
| 24 | + ); |
| 25 | + let miner_addr = spaced |
| 26 | + .bitcoind |
| 27 | + .client |
| 28 | + .get_new_address(None, None)? |
| 29 | + .require_network(Network::Regtest)?; |
| 30 | + const GENERATED_BLOCKS: u32 = 10; |
| 31 | + spaced |
| 32 | + .bitcoind |
| 33 | + .client |
| 34 | + .generate_to_address(GENERATED_BLOCKS as u64, &miner_addr)?; |
| 35 | + |
| 36 | + let client = Client::new(); |
| 37 | + let (fetcher, receiver) = BlockFetcher::new(fetcher_rpc.clone(), client.clone(), 8); |
| 38 | + fetcher.start(ChainAnchor { |
| 39 | + hash: fetcher_rpc.send_json_blocking(&client, &fetcher_rpc.get_block_hash(0))?, |
| 40 | + height: 0, |
| 41 | + }); |
| 42 | + |
| 43 | + let mut start_block = 0; |
| 44 | + let timeout = Duration::from_secs(5); |
| 45 | + let start_time = Instant::now(); |
| 46 | + |
| 47 | + loop { |
| 48 | + if start_time.elapsed() > timeout { |
| 49 | + panic!("Test timed out after {:?}", timeout); |
| 50 | + } |
| 51 | + match receiver.try_recv() { |
| 52 | + Ok(BlockEvent::Block(id, _)) => { |
| 53 | + start_block += 1; |
| 54 | + if id.height == GENERATED_BLOCKS { |
| 55 | + break; |
| 56 | + } |
| 57 | + } |
| 58 | + Ok(BlockEvent::Error(e)) => panic!("Unexpected error: {}", e), |
| 59 | + Err(TryRecvError::Empty) => { |
| 60 | + std::thread::sleep(Duration::from_millis(10)); |
| 61 | + } |
| 62 | + Err(TryRecvError::Disconnected) => panic!("Disconnected unexpectedly"), |
| 63 | + } |
| 64 | + } |
| 65 | + assert_eq!( |
| 66 | + start_block, GENERATED_BLOCKS, |
| 67 | + "Not all blocks were received" |
| 68 | + ); |
| 69 | + Ok(()) |
| 70 | + } |
| 71 | +} |
0 commit comments