Static invoice encoding and parsing
[rust-lightning] / lightning-block-sync / src / test_utils.rs
1 use crate::{AsyncBlockSourceResult, BlockData, BlockHeaderData, BlockSource, BlockSourceError, UnboundedCache};
2 use crate::poll::{Validate, ValidatedBlockHeader};
3
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;
11
12 use lightning::chain;
13
14 use std::cell::RefCell;
15 use std::collections::VecDeque;
16
17 #[derive(Default)]
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,
24 }
25
26 impl Blockchain {
27         pub fn default() -> Self {
28                 Blockchain::with_network(Network::Bitcoin)
29         }
30
31         pub fn with_network(network: Network) -> Self {
32                 let blocks = vec![genesis_block(network)];
33                 Self { blocks, ..Default::default() }
34         }
35
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();
39                 for i in 1..=height {
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,
50                                 input: vec![],
51                                 output: vec![]
52                         };
53                         let merkle_root = TxMerkleNode::from_raw_hash(coinbase.txid().to_raw_hash());
54                         self.blocks.push(Block {
55                                 header: Header {
56                                         version: Version::NO_SOFT_FORK_SIGNALLING,
57                                         prev_blockhash,
58                                         merkle_root,
59                                         time,
60                                         bits,
61                                         nonce: 0,
62                                 },
63                                 txdata: vec![coinbase],
64                         });
65                 }
66                 self
67         }
68
69         pub fn without_blocks(self, range: std::ops::RangeFrom<usize>) -> Self {
70                 Self { without_blocks: Some(range), ..self }
71         }
72
73         pub fn without_headers(self) -> Self {
74                 Self { without_headers: true, ..self }
75         }
76
77         pub fn malformed_headers(self) -> Self {
78                 Self { malformed_headers: true, ..self }
79         }
80
81         pub fn filtered_blocks(self) -> Self {
82                 Self { filtered_blocks: true, ..self }
83         }
84
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();
93                 }
94                 Self { blocks, without_blocks: None, ..*self }
95         }
96
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()
101         }
102
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();
109                 }
110                 BlockHeaderData {
111                         chainwork: total_work,
112                         height: height as u32,
113                         header: self.blocks[height].header,
114                 }
115         }
116
117         pub fn tip(&self) -> ValidatedBlockHeader {
118                 assert!(!self.blocks.is_empty());
119                 self.at_height(self.blocks.len() - 1)
120         }
121
122         pub fn disconnect_tip(&mut self) -> Option<Block> {
123                 self.blocks.pop()
124         }
125
126         pub fn header_cache(&self, heights: std::ops::RangeInclusive<usize>) -> UnboundedCache {
127                 let mut cache = UnboundedCache::new();
128                 for i in heights {
129                         let value = self.at_height(i);
130                         let key = value.header.block_hash();
131                         assert!(cache.insert(key, value).is_none());
132                 }
133                 cache
134         }
135 }
136
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"));
142                         }
143
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;
149                                         }
150
151                                         return Ok(header_data);
152                                 }
153                         }
154                         Err(BlockSourceError::transient("header not found"))
155                 })
156         }
157
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"));
165                                                 }
166                                         }
167
168                                         if self.filtered_blocks {
169                                                 return Ok(BlockData::HeaderOnly(block.header));
170                                         } else {
171                                                 return Ok(BlockData::FullBlock(block.clone()));
172                                         }
173                                 }
174                         }
175                         Err(BlockSourceError::transient("block not found"))
176                 })
177         }
178
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")),
183                                 Some(block) => {
184                                         let height = (self.blocks.len() - 1) as u32;
185                                         Ok((block.block_hash(), Some(height)))
186                                 },
187                         }
188                 })
189         }
190 }
191
192 pub struct NullChainListener;
193
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) {}
197 }
198
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>>,
203 }
204
205 impl MockChainListener {
206         pub fn new() -> Self {
207                 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()),
211                 }
212         }
213
214         pub fn expect_block_connected(self, block: BlockHeaderData) -> Self {
215                 self.expected_blocks_connected.borrow_mut().push_back(block);
216                 self
217         }
218
219         pub fn expect_filtered_block_connected(self, block: BlockHeaderData) -> Self {
220                 self.expected_filtered_blocks_connected.borrow_mut().push_back(block);
221                 self
222         }
223
224         pub fn expect_block_disconnected(self, block: BlockHeaderData) -> Self {
225                 self.expected_blocks_disconnected.borrow_mut().push_back(block);
226                 self
227         }
228 }
229
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() {
233                         None => {
234                                 panic!("Unexpected block connected: {:?}", block.block_hash());
235                         },
236                         Some(expected_block) => {
237                                 assert_eq!(block.block_hash(), expected_block.header.block_hash());
238                                 assert_eq!(height, expected_block.height);
239                         },
240                 }
241         }
242
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() {
245                         None => {
246                                 panic!("Unexpected filtered block connected: {:?}", header.block_hash());
247                         },
248                         Some(expected_block) => {
249                                 assert_eq!(header.block_hash(), expected_block.header.block_hash());
250                                 assert_eq!(height, expected_block.height);
251                         },
252                 }
253         }
254
255         fn block_disconnected(&self, header: &Header, height: u32) {
256                 match self.expected_blocks_disconnected.borrow_mut().pop_front() {
257                         None => {
258                                 panic!("Unexpected block disconnected: {:?}", header.block_hash());
259                         },
260                         Some(expected_block) => {
261                                 assert_eq!(header.block_hash(), expected_block.header.block_hash());
262                                 assert_eq!(height, expected_block.height);
263                         },
264                 }
265         }
266 }
267
268 impl Drop for MockChainListener {
269         fn drop(&mut self) {
270                 if std::thread::panicking() {
271                         return;
272                 }
273
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);
277                 }
278
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);
282                 }
283
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);
287                 }
288         }
289 }