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::Network;
9 use bitcoin::Transaction;
10 use bitcoin::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 = bitcoin::Target::from_be_bytes([0xff; 32]).to_compact_lossy();
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 {
48 version: transaction::Version(0),
49 lock_time: LockTime::ZERO,
53 let merkle_root = TxMerkleNode::from_raw_hash(coinbase.txid().to_raw_hash());
54 self.blocks.push(Block {
56 version: Version::NO_SOFT_FORK_SIGNALLING,
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());
106 let mut total_work = self.blocks[0].header.work();
107 for i in 1..=height {
108 total_work = total_work + self.blocks[i].header.work();
111 chainwork: total_work,
112 height: height as u32,
113 header: self.blocks[height].header,
117 pub fn tip(&self) -> ValidatedBlockHeader {
118 assert!(!self.blocks.is_empty());
119 self.at_height(self.blocks.len() - 1)
122 pub fn disconnect_tip(&mut self) -> Option<Block> {
126 pub fn header_cache(&self, heights: std::ops::RangeInclusive<usize>) -> UnboundedCache {
127 let mut cache = UnboundedCache::new();
129 let value = self.at_height(i);
130 let key = value.header.block_hash();
131 assert!(cache.insert(key, value).is_none());
137 impl BlockSource for Blockchain {
138 fn get_header<'a>(&'a self, header_hash: &'a BlockHash, _height_hint: Option<u32>) -> AsyncBlockSourceResult<'a, BlockHeaderData> {
139 Box::pin(async move {
140 if self.without_headers {
141 return Err(BlockSourceError::persistent("header not found"));
144 for (height, block) in self.blocks.iter().enumerate() {
145 if block.header.block_hash() == *header_hash {
146 let mut header_data = self.at_height_unvalidated(height);
147 if self.malformed_headers {
148 header_data.header.time += 1;
151 return Ok(header_data);
154 Err(BlockSourceError::transient("header not found"))
158 fn get_block<'a>(&'a self, header_hash: &'a BlockHash) -> AsyncBlockSourceResult<'a, BlockData> {
159 Box::pin(async move {
160 for (height, block) in self.blocks.iter().enumerate() {
161 if block.header.block_hash() == *header_hash {
162 if let Some(without_blocks) = &self.without_blocks {
163 if without_blocks.contains(&height) {
164 return Err(BlockSourceError::persistent("block not found"));
168 if self.filtered_blocks {
169 return Ok(BlockData::HeaderOnly(block.header));
171 return Ok(BlockData::FullBlock(block.clone()));
175 Err(BlockSourceError::transient("block not found"))
179 fn get_best_block<'a>(&'a self) -> AsyncBlockSourceResult<'a, (BlockHash, Option<u32>)> {
180 Box::pin(async move {
181 match self.blocks.last() {
182 None => Err(BlockSourceError::transient("empty chain")),
184 let height = (self.blocks.len() - 1) as u32;
185 Ok((block.block_hash(), Some(height)))
192 pub struct NullChainListener;
194 impl chain::Listen for NullChainListener {
195 fn filtered_block_connected(&self, _header: &Header, _txdata: &chain::transaction::TransactionData, _height: u32) {}
196 fn block_disconnected(&self, _header: &Header, _height: u32) {}
199 pub struct MockChainListener {
200 expected_blocks_connected: RefCell<VecDeque<BlockHeaderData>>,
201 expected_filtered_blocks_connected: RefCell<VecDeque<BlockHeaderData>>,
202 expected_blocks_disconnected: RefCell<VecDeque<BlockHeaderData>>,
205 impl MockChainListener {
206 pub fn new() -> Self {
208 expected_blocks_connected: RefCell::new(VecDeque::new()),
209 expected_filtered_blocks_connected: RefCell::new(VecDeque::new()),
210 expected_blocks_disconnected: RefCell::new(VecDeque::new()),
214 pub fn expect_block_connected(self, block: BlockHeaderData) -> Self {
215 self.expected_blocks_connected.borrow_mut().push_back(block);
219 pub fn expect_filtered_block_connected(self, block: BlockHeaderData) -> Self {
220 self.expected_filtered_blocks_connected.borrow_mut().push_back(block);
224 pub fn expect_block_disconnected(self, block: BlockHeaderData) -> Self {
225 self.expected_blocks_disconnected.borrow_mut().push_back(block);
230 impl chain::Listen for MockChainListener {
231 fn block_connected(&self, block: &Block, height: u32) {
232 match self.expected_blocks_connected.borrow_mut().pop_front() {
234 panic!("Unexpected block connected: {:?}", block.block_hash());
236 Some(expected_block) => {
237 assert_eq!(block.block_hash(), expected_block.header.block_hash());
238 assert_eq!(height, expected_block.height);
243 fn filtered_block_connected(&self, header: &Header, _txdata: &chain::transaction::TransactionData, height: u32) {
244 match self.expected_filtered_blocks_connected.borrow_mut().pop_front() {
246 panic!("Unexpected filtered block connected: {:?}", header.block_hash());
248 Some(expected_block) => {
249 assert_eq!(header.block_hash(), expected_block.header.block_hash());
250 assert_eq!(height, expected_block.height);
255 fn block_disconnected(&self, header: &Header, height: u32) {
256 match self.expected_blocks_disconnected.borrow_mut().pop_front() {
258 panic!("Unexpected block disconnected: {:?}", header.block_hash());
260 Some(expected_block) => {
261 assert_eq!(header.block_hash(), expected_block.header.block_hash());
262 assert_eq!(height, expected_block.height);
268 impl Drop for MockChainListener {
270 if std::thread::panicking() {
274 let expected_blocks_connected = self.expected_blocks_connected.borrow();
275 if !expected_blocks_connected.is_empty() {
276 panic!("Expected blocks connected: {:?}", expected_blocks_connected);
279 let expected_filtered_blocks_connected = self.expected_filtered_blocks_connected.borrow();
280 if !expected_filtered_blocks_connected.is_empty() {
281 panic!("Expected filtered_blocks connected: {:?}", expected_filtered_blocks_connected);
284 let expected_blocks_disconnected = self.expected_blocks_disconnected.borrow();
285 if !expected_blocks_disconnected.is_empty() {
286 panic!("Expected blocks disconnected: {:?}", expected_blocks_disconnected);