1 use crate::{AsyncBlockSourceResult, BlockData, BlockHeaderData, BlockSource, BlockSourceError, UnboundedCache};
2 use crate::poll::{Validate, ValidatedBlockHeader};
4 use bitcoin::blockdata::block::{Block, BlockHeader};
5 use bitcoin::blockdata::constants::genesis_block;
6 use bitcoin::hash_types::BlockHash;
7 use bitcoin::network::constants::Network;
8 use bitcoin::util::uint::Uint256;
9 use bitcoin::util::hash::bitcoin_merkle_root;
10 use bitcoin::{PackedLockTime, Transaction};
14 use std::cell::RefCell;
15 use std::collections::VecDeque;
18 pub struct Blockchain {
19 pub blocks: Vec<Block>,
20 without_blocks: Option<std::ops::RangeFrom<usize>>,
21 without_headers: bool,
22 malformed_headers: bool,
23 filtered_blocks: bool,
27 pub fn default() -> Self {
28 Blockchain::with_network(Network::Bitcoin)
31 pub fn with_network(network: Network) -> Self {
32 let blocks = vec![genesis_block(network)];
33 Self { blocks, ..Default::default() }
36 pub fn with_height(mut self, height: usize) -> Self {
37 self.blocks.reserve_exact(height);
38 let bits = BlockHeader::compact_target_from_u256(&Uint256::from_be_bytes([0xff; 32]));
40 let prev_block = &self.blocks[i - 1];
41 let prev_blockhash = prev_block.block_hash();
42 let time = prev_block.header.time + height as u32;
43 // Must have at least one transaction, because the merkle root is not defined for an empty block
44 // and we would fail when we later checked, as of bitcoin crate 0.28.0.
45 // Note that elsewhere in tests we assume that the merkle root of an empty block is all zeros,
46 // but that's OK because those tests don't trigger the check.
47 let coinbase = Transaction {
49 lock_time: PackedLockTime::ZERO,
53 let merkle_root = bitcoin_merkle_root(vec![coinbase.txid().as_hash()].into_iter()).unwrap();
54 self.blocks.push(Block {
58 merkle_root: merkle_root.into(),
63 txdata: vec![coinbase],
69 pub fn without_blocks(self, range: std::ops::RangeFrom<usize>) -> Self {
70 Self { without_blocks: Some(range), ..self }
73 pub fn without_headers(self) -> Self {
74 Self { without_headers: true, ..self }
77 pub fn malformed_headers(self) -> Self {
78 Self { malformed_headers: true, ..self }
81 pub fn filtered_blocks(self) -> Self {
82 Self { filtered_blocks: true, ..self }
85 pub fn fork_at_height(&self, height: usize) -> Self {
86 assert!(height + 1 < self.blocks.len());
87 let mut blocks = self.blocks.clone();
88 let mut prev_blockhash = blocks[height].block_hash();
89 for block in blocks.iter_mut().skip(height + 1) {
90 block.header.prev_blockhash = prev_blockhash;
91 block.header.nonce += 1;
92 prev_blockhash = block.block_hash();
94 Self { blocks, without_blocks: None, ..*self }
97 pub fn at_height(&self, height: usize) -> ValidatedBlockHeader {
98 let block_header = self.at_height_unvalidated(height);
99 let block_hash = self.blocks[height].block_hash();
100 block_header.validate(block_hash).unwrap()
103 fn at_height_unvalidated(&self, height: usize) -> BlockHeaderData {
104 assert!(!self.blocks.is_empty());
105 assert!(height < self.blocks.len());
107 chainwork: self.blocks[0].header.work() + Uint256::from_u64(height as u64).unwrap(),
108 height: height as u32,
109 header: self.blocks[height].header,
113 pub fn tip(&self) -> ValidatedBlockHeader {
114 assert!(!self.blocks.is_empty());
115 self.at_height(self.blocks.len() - 1)
118 pub fn disconnect_tip(&mut self) -> Option<Block> {
122 pub fn header_cache(&self, heights: std::ops::RangeInclusive<usize>) -> UnboundedCache {
123 let mut cache = UnboundedCache::new();
125 let value = self.at_height(i);
126 let key = value.header.block_hash();
127 assert!(cache.insert(key, value).is_none());
133 impl BlockSource for Blockchain {
134 fn get_header<'a>(&'a self, header_hash: &'a BlockHash, _height_hint: Option<u32>) -> AsyncBlockSourceResult<'a, BlockHeaderData> {
135 Box::pin(async move {
136 if self.without_headers {
137 return Err(BlockSourceError::persistent("header not found"));
140 for (height, block) in self.blocks.iter().enumerate() {
141 if block.header.block_hash() == *header_hash {
142 let mut header_data = self.at_height_unvalidated(height);
143 if self.malformed_headers {
144 header_data.header.time += 1;
147 return Ok(header_data);
150 Err(BlockSourceError::transient("header not found"))
154 fn get_block<'a>(&'a self, header_hash: &'a BlockHash) -> AsyncBlockSourceResult<'a, BlockData> {
155 Box::pin(async move {
156 for (height, block) in self.blocks.iter().enumerate() {
157 if block.header.block_hash() == *header_hash {
158 if let Some(without_blocks) = &self.without_blocks {
159 if without_blocks.contains(&height) {
160 return Err(BlockSourceError::persistent("block not found"));
164 if self.filtered_blocks {
165 return Ok(BlockData::HeaderOnly(block.header));
167 return Ok(BlockData::FullBlock(block.clone()));
171 Err(BlockSourceError::transient("block not found"))
175 fn get_best_block<'a>(&'a self) -> AsyncBlockSourceResult<'a, (BlockHash, Option<u32>)> {
176 Box::pin(async move {
177 match self.blocks.last() {
178 None => Err(BlockSourceError::transient("empty chain")),
180 let height = (self.blocks.len() - 1) as u32;
181 Ok((block.block_hash(), Some(height)))
188 pub struct NullChainListener;
190 impl chain::Listen for NullChainListener {
191 fn filtered_block_connected(&self, _header: &BlockHeader, _txdata: &chain::transaction::TransactionData, _height: u32) {}
192 fn block_disconnected(&self, _header: &BlockHeader, _height: u32) {}
195 pub struct MockChainListener {
196 expected_blocks_connected: RefCell<VecDeque<BlockHeaderData>>,
197 expected_filtered_blocks_connected: RefCell<VecDeque<BlockHeaderData>>,
198 expected_blocks_disconnected: RefCell<VecDeque<BlockHeaderData>>,
201 impl MockChainListener {
202 pub fn new() -> Self {
204 expected_blocks_connected: RefCell::new(VecDeque::new()),
205 expected_filtered_blocks_connected: RefCell::new(VecDeque::new()),
206 expected_blocks_disconnected: RefCell::new(VecDeque::new()),
210 pub fn expect_block_connected(self, block: BlockHeaderData) -> Self {
211 self.expected_blocks_connected.borrow_mut().push_back(block);
215 pub fn expect_filtered_block_connected(self, block: BlockHeaderData) -> Self {
216 self.expected_filtered_blocks_connected.borrow_mut().push_back(block);
220 pub fn expect_block_disconnected(self, block: BlockHeaderData) -> Self {
221 self.expected_blocks_disconnected.borrow_mut().push_back(block);
226 impl chain::Listen for MockChainListener {
227 fn block_connected(&self, block: &Block, height: u32) {
228 match self.expected_blocks_connected.borrow_mut().pop_front() {
230 panic!("Unexpected block connected: {:?}", block.block_hash());
232 Some(expected_block) => {
233 assert_eq!(block.block_hash(), expected_block.header.block_hash());
234 assert_eq!(height, expected_block.height);
239 fn filtered_block_connected(&self, header: &BlockHeader, _txdata: &chain::transaction::TransactionData, height: u32) {
240 match self.expected_filtered_blocks_connected.borrow_mut().pop_front() {
242 panic!("Unexpected filtered block connected: {:?}", header.block_hash());
244 Some(expected_block) => {
245 assert_eq!(header.block_hash(), expected_block.header.block_hash());
246 assert_eq!(height, expected_block.height);
251 fn block_disconnected(&self, header: &BlockHeader, height: u32) {
252 match self.expected_blocks_disconnected.borrow_mut().pop_front() {
254 panic!("Unexpected block disconnected: {:?}", header.block_hash());
256 Some(expected_block) => {
257 assert_eq!(header.block_hash(), expected_block.header.block_hash());
258 assert_eq!(height, expected_block.height);
264 impl Drop for MockChainListener {
266 if std::thread::panicking() {
270 let expected_blocks_connected = self.expected_blocks_connected.borrow();
271 if !expected_blocks_connected.is_empty() {
272 panic!("Expected blocks connected: {:?}", expected_blocks_connected);
275 let expected_filtered_blocks_connected = self.expected_filtered_blocks_connected.borrow();
276 if !expected_filtered_blocks_connected.is_empty() {
277 panic!("Expected filtered_blocks connected: {:?}", expected_filtered_blocks_connected);
280 let expected_blocks_disconnected = self.expected_blocks_disconnected.borrow();
281 if !expected_blocks_disconnected.is_empty() {
282 panic!("Expected blocks disconnected: {:?}", expected_blocks_disconnected);