1 use crate::{AsyncBlockSourceResult, BlockData, BlockHeaderData, BlockSource, BlockSourceError, UnboundedCache};
2 use crate::poll::{Validate, ValidatedBlockHeader};
4 use bitcoin::blockdata::block::{Block, Header, Version};
5 use bitcoin::blockdata::constants::genesis_block;
6 use bitcoin::blockdata::locktime::absolute::LockTime;
7 use bitcoin::hash_types::{BlockHash, TxMerkleNode};
8 use bitcoin::network::constants::Network;
9 use bitcoin::Transaction;
13 use std::cell::RefCell;
14 use std::collections::VecDeque;
17 pub struct Blockchain {
18 pub blocks: Vec<Block>,
19 without_blocks: Option<std::ops::RangeFrom<usize>>,
20 without_headers: bool,
21 malformed_headers: bool,
22 filtered_blocks: bool,
26 pub fn default() -> Self {
27 Blockchain::with_network(Network::Bitcoin)
30 pub fn with_network(network: Network) -> Self {
31 let blocks = vec![genesis_block(network)];
32 Self { blocks, ..Default::default() }
35 pub fn with_height(mut self, height: usize) -> Self {
36 self.blocks.reserve_exact(height);
37 let bits = bitcoin::Target::from_be_bytes([0xff; 32]).to_compact_lossy();
39 let prev_block = &self.blocks[i - 1];
40 let prev_blockhash = prev_block.block_hash();
41 let time = prev_block.header.time + height as u32;
42 // Must have at least one transaction, because the merkle root is not defined for an empty block
43 // and we would fail when we later checked, as of bitcoin crate 0.28.0.
44 // Note that elsewhere in tests we assume that the merkle root of an empty block is all zeros,
45 // but that's OK because those tests don't trigger the check.
46 let coinbase = Transaction {
48 lock_time: LockTime::ZERO,
52 let merkle_root = TxMerkleNode::from_raw_hash(coinbase.txid().to_raw_hash());
53 self.blocks.push(Block {
55 version: Version::NO_SOFT_FORK_SIGNALLING,
62 txdata: vec![coinbase],
68 pub fn without_blocks(self, range: std::ops::RangeFrom<usize>) -> Self {
69 Self { without_blocks: Some(range), ..self }
72 pub fn without_headers(self) -> Self {
73 Self { without_headers: true, ..self }
76 pub fn malformed_headers(self) -> Self {
77 Self { malformed_headers: true, ..self }
80 pub fn filtered_blocks(self) -> Self {
81 Self { filtered_blocks: true, ..self }
84 pub fn fork_at_height(&self, height: usize) -> Self {
85 assert!(height + 1 < self.blocks.len());
86 let mut blocks = self.blocks.clone();
87 let mut prev_blockhash = blocks[height].block_hash();
88 for block in blocks.iter_mut().skip(height + 1) {
89 block.header.prev_blockhash = prev_blockhash;
90 block.header.nonce += 1;
91 prev_blockhash = block.block_hash();
93 Self { blocks, without_blocks: None, ..*self }
96 pub fn at_height(&self, height: usize) -> ValidatedBlockHeader {
97 let block_header = self.at_height_unvalidated(height);
98 let block_hash = self.blocks[height].block_hash();
99 block_header.validate(block_hash).unwrap()
102 fn at_height_unvalidated(&self, height: usize) -> BlockHeaderData {
103 assert!(!self.blocks.is_empty());
104 assert!(height < self.blocks.len());
105 let mut total_work = self.blocks[0].header.work();
106 for i in 1..=height {
107 total_work = total_work + self.blocks[i].header.work();
110 chainwork: total_work,
111 height: height as u32,
112 header: self.blocks[height].header,
116 pub fn tip(&self) -> ValidatedBlockHeader {
117 assert!(!self.blocks.is_empty());
118 self.at_height(self.blocks.len() - 1)
121 pub fn disconnect_tip(&mut self) -> Option<Block> {
125 pub fn header_cache(&self, heights: std::ops::RangeInclusive<usize>) -> UnboundedCache {
126 let mut cache = UnboundedCache::new();
128 let value = self.at_height(i);
129 let key = value.header.block_hash();
130 assert!(cache.insert(key, value).is_none());
136 impl BlockSource for Blockchain {
137 fn get_header<'a>(&'a self, header_hash: &'a BlockHash, _height_hint: Option<u32>) -> AsyncBlockSourceResult<'a, BlockHeaderData> {
138 Box::pin(async move {
139 if self.without_headers {
140 return Err(BlockSourceError::persistent("header not found"));
143 for (height, block) in self.blocks.iter().enumerate() {
144 if block.header.block_hash() == *header_hash {
145 let mut header_data = self.at_height_unvalidated(height);
146 if self.malformed_headers {
147 header_data.header.time += 1;
150 return Ok(header_data);
153 Err(BlockSourceError::transient("header not found"))
157 fn get_block<'a>(&'a self, header_hash: &'a BlockHash) -> AsyncBlockSourceResult<'a, BlockData> {
158 Box::pin(async move {
159 for (height, block) in self.blocks.iter().enumerate() {
160 if block.header.block_hash() == *header_hash {
161 if let Some(without_blocks) = &self.without_blocks {
162 if without_blocks.contains(&height) {
163 return Err(BlockSourceError::persistent("block not found"));
167 if self.filtered_blocks {
168 return Ok(BlockData::HeaderOnly(block.header));
170 return Ok(BlockData::FullBlock(block.clone()));
174 Err(BlockSourceError::transient("block not found"))
178 fn get_best_block<'a>(&'a self) -> AsyncBlockSourceResult<'a, (BlockHash, Option<u32>)> {
179 Box::pin(async move {
180 match self.blocks.last() {
181 None => Err(BlockSourceError::transient("empty chain")),
183 let height = (self.blocks.len() - 1) as u32;
184 Ok((block.block_hash(), Some(height)))
191 pub struct NullChainListener;
193 impl chain::Listen for NullChainListener {
194 fn filtered_block_connected(&self, _header: &Header, _txdata: &chain::transaction::TransactionData, _height: u32) {}
195 fn block_disconnected(&self, _header: &Header, _height: u32) {}
198 pub struct MockChainListener {
199 expected_blocks_connected: RefCell<VecDeque<BlockHeaderData>>,
200 expected_filtered_blocks_connected: RefCell<VecDeque<BlockHeaderData>>,
201 expected_blocks_disconnected: RefCell<VecDeque<BlockHeaderData>>,
204 impl MockChainListener {
205 pub fn new() -> Self {
207 expected_blocks_connected: RefCell::new(VecDeque::new()),
208 expected_filtered_blocks_connected: RefCell::new(VecDeque::new()),
209 expected_blocks_disconnected: RefCell::new(VecDeque::new()),
213 pub fn expect_block_connected(self, block: BlockHeaderData) -> Self {
214 self.expected_blocks_connected.borrow_mut().push_back(block);
218 pub fn expect_filtered_block_connected(self, block: BlockHeaderData) -> Self {
219 self.expected_filtered_blocks_connected.borrow_mut().push_back(block);
223 pub fn expect_block_disconnected(self, block: BlockHeaderData) -> Self {
224 self.expected_blocks_disconnected.borrow_mut().push_back(block);
229 impl chain::Listen for MockChainListener {
230 fn block_connected(&self, block: &Block, height: u32) {
231 match self.expected_blocks_connected.borrow_mut().pop_front() {
233 panic!("Unexpected block connected: {:?}", block.block_hash());
235 Some(expected_block) => {
236 assert_eq!(block.block_hash(), expected_block.header.block_hash());
237 assert_eq!(height, expected_block.height);
242 fn filtered_block_connected(&self, header: &Header, _txdata: &chain::transaction::TransactionData, height: u32) {
243 match self.expected_filtered_blocks_connected.borrow_mut().pop_front() {
245 panic!("Unexpected filtered block connected: {:?}", header.block_hash());
247 Some(expected_block) => {
248 assert_eq!(header.block_hash(), expected_block.header.block_hash());
249 assert_eq!(height, expected_block.height);
254 fn block_disconnected(&self, header: &Header, height: u32) {
255 match self.expected_blocks_disconnected.borrow_mut().pop_front() {
257 panic!("Unexpected block disconnected: {:?}", header.block_hash());
259 Some(expected_block) => {
260 assert_eq!(header.block_hash(), expected_block.header.block_hash());
261 assert_eq!(height, expected_block.height);
267 impl Drop for MockChainListener {
269 if std::thread::panicking() {
273 let expected_blocks_connected = self.expected_blocks_connected.borrow();
274 if !expected_blocks_connected.is_empty() {
275 panic!("Expected blocks connected: {:?}", expected_blocks_connected);
278 let expected_filtered_blocks_connected = self.expected_filtered_blocks_connected.borrow();
279 if !expected_filtered_blocks_connected.is_empty() {
280 panic!("Expected filtered_blocks connected: {:?}", expected_filtered_blocks_connected);
283 let expected_blocks_disconnected = self.expected_blocks_disconnected.borrow();
284 if !expected_blocks_disconnected.is_empty() {
285 panic!("Expected blocks disconnected: {:?}", expected_blocks_disconnected);