|
1 |
| -use crate::{AsyncBlockSourceResult, BlockHeaderData, BlockSourceError, BlockSourceResult}; |
| 1 | +use crate::{AsyncBlockSourceResult, BlockHeaderData, BlockSource, BlockSourceError, BlockSourceResult}; |
2 | 2 |
|
3 | 3 | use bitcoin::blockdata::block::Block;
|
4 | 4 | use bitcoin::hash_types::BlockHash;
|
5 | 5 | use bitcoin::network::constants::Network;
|
6 | 6 |
|
| 7 | +use std::ops::DerefMut; |
| 8 | + |
7 | 9 | /// The `Poll` trait defines behavior for polling block sources for a chain tip and retrieving
|
8 | 10 | /// related chain data. It serves as an adapter for `BlockSource`.
|
| 11 | +/// |
| 12 | +/// [`ChainPoller`] adapts a single `BlockSource`, while any other implementations of `Poll` are |
| 13 | +/// required to be built in terms of it to ensure chain data validity. |
| 14 | +/// |
| 15 | +/// [`ChainPoller`]: ../struct.ChainPoller.html |
9 | 16 | pub trait Poll {
|
10 | 17 | /// Returns a chain tip in terms of its relationship to the provided chain tip.
|
11 | 18 | fn poll_chain_tip<'a>(&'a mut self, best_known_chain_tip: ValidatedBlockHeader) ->
|
@@ -146,3 +153,204 @@ impl std::ops::Deref for ValidatedBlock {
|
146 | 153 | &self.inner
|
147 | 154 | }
|
148 | 155 | }
|
| 156 | + |
| 157 | +/// The canonical `Poll` implementation used for a single `BlockSource`. |
| 158 | +/// |
| 159 | +/// Other `Poll` implementations must be built using `ChainPoller` as it provides the only means of |
| 160 | +/// validating chain data. |
| 161 | +pub struct ChainPoller<B: DerefMut<Target=T> + Sized + Sync + Send, T: BlockSource> { |
| 162 | + block_source: B, |
| 163 | + network: Network, |
| 164 | +} |
| 165 | + |
| 166 | +impl<B: DerefMut<Target=T> + Sized + Sync + Send, T: BlockSource> ChainPoller<B, T> { |
| 167 | + /// Creates a new poller for the given block source. |
| 168 | + /// |
| 169 | + /// If the `network` parameter is mainnet, then the difficulty between blocks is checked for |
| 170 | + /// validity. |
| 171 | + pub fn new(block_source: B, network: Network) -> Self { |
| 172 | + Self { block_source, network } |
| 173 | + } |
| 174 | +} |
| 175 | + |
| 176 | +impl<B: DerefMut<Target=T> + Sized + Sync + Send, T: BlockSource> Poll for ChainPoller<B, T> { |
| 177 | + fn poll_chain_tip<'a>(&'a mut self, best_known_chain_tip: ValidatedBlockHeader) -> |
| 178 | + AsyncBlockSourceResult<'a, ChainTip> |
| 179 | + { |
| 180 | + Box::pin(async move { |
| 181 | + let (block_hash, height) = self.block_source.get_best_block().await?; |
| 182 | + if block_hash == best_known_chain_tip.header.block_hash() { |
| 183 | + return Ok(ChainTip::Common); |
| 184 | + } |
| 185 | + |
| 186 | + let chain_tip = self.block_source |
| 187 | + .get_header(&block_hash, height).await? |
| 188 | + .validate(block_hash)?; |
| 189 | + if chain_tip.chainwork > best_known_chain_tip.chainwork { |
| 190 | + Ok(ChainTip::Better(chain_tip)) |
| 191 | + } else { |
| 192 | + Ok(ChainTip::Worse(chain_tip)) |
| 193 | + } |
| 194 | + }) |
| 195 | + } |
| 196 | + |
| 197 | + fn look_up_previous_header<'a>(&'a mut self, header: &'a ValidatedBlockHeader) -> |
| 198 | + AsyncBlockSourceResult<'a, ValidatedBlockHeader> |
| 199 | + { |
| 200 | + Box::pin(async move { |
| 201 | + if header.height == 0 { |
| 202 | + return Err(BlockSourceError::persistent("genesis block reached")); |
| 203 | + } |
| 204 | + |
| 205 | + let previous_hash = &header.header.prev_blockhash; |
| 206 | + let height = header.height - 1; |
| 207 | + let previous_header = self.block_source |
| 208 | + .get_header(previous_hash, Some(height)).await? |
| 209 | + .validate(*previous_hash)?; |
| 210 | + header.check_builds_on(&previous_header, self.network)?; |
| 211 | + |
| 212 | + Ok(previous_header) |
| 213 | + }) |
| 214 | + } |
| 215 | + |
| 216 | + fn fetch_block<'a>(&'a mut self, header: &'a ValidatedBlockHeader) -> |
| 217 | + AsyncBlockSourceResult<'a, ValidatedBlock> |
| 218 | + { |
| 219 | + Box::pin(async move { |
| 220 | + self.block_source |
| 221 | + .get_block(&header.block_hash).await? |
| 222 | + .validate(header.block_hash) |
| 223 | + }) |
| 224 | + } |
| 225 | +} |
| 226 | + |
| 227 | +#[cfg(test)] |
| 228 | +mod tests { |
| 229 | + use crate::*; |
| 230 | + use crate::test_utils::Blockchain; |
| 231 | + use super::*; |
| 232 | + use bitcoin::util::uint::Uint256; |
| 233 | + |
| 234 | + #[tokio::test] |
| 235 | + async fn poll_empty_chain() { |
| 236 | + let mut chain = Blockchain::default().with_height(0); |
| 237 | + let best_known_chain_tip = chain.tip(); |
| 238 | + chain.disconnect_tip(); |
| 239 | + |
| 240 | + let mut poller = ChainPoller::new(&mut chain, Network::Bitcoin); |
| 241 | + match poller.poll_chain_tip(best_known_chain_tip).await { |
| 242 | + Err(e) => { |
| 243 | + assert_eq!(e.kind(), BlockSourceErrorKind::Transient); |
| 244 | + assert_eq!(e.into_inner().as_ref().to_string(), "empty chain"); |
| 245 | + }, |
| 246 | + Ok(_) => panic!("Expected error"), |
| 247 | + } |
| 248 | + } |
| 249 | + |
| 250 | + #[tokio::test] |
| 251 | + async fn poll_chain_without_headers() { |
| 252 | + let mut chain = Blockchain::default().with_height(1).without_headers(); |
| 253 | + let best_known_chain_tip = chain.at_height(0); |
| 254 | + |
| 255 | + let mut poller = ChainPoller::new(&mut chain, Network::Bitcoin); |
| 256 | + match poller.poll_chain_tip(best_known_chain_tip).await { |
| 257 | + Err(e) => { |
| 258 | + assert_eq!(e.kind(), BlockSourceErrorKind::Persistent); |
| 259 | + assert_eq!(e.into_inner().as_ref().to_string(), "header not found"); |
| 260 | + }, |
| 261 | + Ok(_) => panic!("Expected error"), |
| 262 | + } |
| 263 | + } |
| 264 | + |
| 265 | + #[tokio::test] |
| 266 | + async fn poll_chain_with_invalid_pow() { |
| 267 | + let mut chain = Blockchain::default().with_height(1); |
| 268 | + let best_known_chain_tip = chain.at_height(0); |
| 269 | + |
| 270 | + // Invalidate the tip by changing its target. |
| 271 | + chain.blocks.last_mut().unwrap().header.bits = |
| 272 | + BlockHeader::compact_target_from_u256(&Uint256::from_be_bytes([0; 32])); |
| 273 | + |
| 274 | + let mut poller = ChainPoller::new(&mut chain, Network::Bitcoin); |
| 275 | + match poller.poll_chain_tip(best_known_chain_tip).await { |
| 276 | + Err(e) => { |
| 277 | + assert_eq!(e.kind(), BlockSourceErrorKind::Persistent); |
| 278 | + assert_eq!(e.into_inner().as_ref().to_string(), "block target correct but not attained"); |
| 279 | + }, |
| 280 | + Ok(_) => panic!("Expected error"), |
| 281 | + } |
| 282 | + } |
| 283 | + |
| 284 | + #[tokio::test] |
| 285 | + async fn poll_chain_with_malformed_headers() { |
| 286 | + let mut chain = Blockchain::default().with_height(1).malformed_headers(); |
| 287 | + let best_known_chain_tip = chain.at_height(0); |
| 288 | + |
| 289 | + let mut poller = ChainPoller::new(&mut chain, Network::Bitcoin); |
| 290 | + match poller.poll_chain_tip(best_known_chain_tip).await { |
| 291 | + Err(e) => { |
| 292 | + assert_eq!(e.kind(), BlockSourceErrorKind::Persistent); |
| 293 | + assert_eq!(e.into_inner().as_ref().to_string(), "invalid block hash"); |
| 294 | + }, |
| 295 | + Ok(_) => panic!("Expected error"), |
| 296 | + } |
| 297 | + } |
| 298 | + |
| 299 | + #[tokio::test] |
| 300 | + async fn poll_chain_with_common_tip() { |
| 301 | + let mut chain = Blockchain::default().with_height(0); |
| 302 | + let best_known_chain_tip = chain.tip(); |
| 303 | + |
| 304 | + let mut poller = ChainPoller::new(&mut chain, Network::Bitcoin); |
| 305 | + match poller.poll_chain_tip(best_known_chain_tip).await { |
| 306 | + Err(e) => panic!("Unexpected error: {:?}", e), |
| 307 | + Ok(tip) => assert_eq!(tip, ChainTip::Common), |
| 308 | + } |
| 309 | + } |
| 310 | + |
| 311 | + #[tokio::test] |
| 312 | + async fn poll_chain_with_uncommon_tip_but_equal_chainwork() { |
| 313 | + let mut chain = Blockchain::default().with_height(1); |
| 314 | + let best_known_chain_tip = chain.tip(); |
| 315 | + |
| 316 | + // Change the nonce to get a different block hash with the same chainwork. |
| 317 | + chain.blocks.last_mut().unwrap().header.nonce += 1; |
| 318 | + let worse_chain_tip = chain.tip(); |
| 319 | + assert_eq!(best_known_chain_tip.chainwork, worse_chain_tip.chainwork); |
| 320 | + |
| 321 | + let mut poller = ChainPoller::new(&mut chain, Network::Bitcoin); |
| 322 | + match poller.poll_chain_tip(best_known_chain_tip).await { |
| 323 | + Err(e) => panic!("Unexpected error: {:?}", e), |
| 324 | + Ok(tip) => assert_eq!(tip, ChainTip::Worse(worse_chain_tip)), |
| 325 | + } |
| 326 | + } |
| 327 | + |
| 328 | + #[tokio::test] |
| 329 | + async fn poll_chain_with_worse_tip() { |
| 330 | + let mut chain = Blockchain::default().with_height(1); |
| 331 | + let best_known_chain_tip = chain.tip(); |
| 332 | + |
| 333 | + chain.disconnect_tip(); |
| 334 | + let worse_chain_tip = chain.tip(); |
| 335 | + |
| 336 | + let mut poller = ChainPoller::new(&mut chain, Network::Bitcoin); |
| 337 | + match poller.poll_chain_tip(best_known_chain_tip).await { |
| 338 | + Err(e) => panic!("Unexpected error: {:?}", e), |
| 339 | + Ok(tip) => assert_eq!(tip, ChainTip::Worse(worse_chain_tip)), |
| 340 | + } |
| 341 | + } |
| 342 | + |
| 343 | + #[tokio::test] |
| 344 | + async fn poll_chain_with_better_tip() { |
| 345 | + let mut chain = Blockchain::default().with_height(1); |
| 346 | + let best_known_chain_tip = chain.at_height(0); |
| 347 | + |
| 348 | + let better_chain_tip = chain.tip(); |
| 349 | + |
| 350 | + let mut poller = ChainPoller::new(&mut chain, Network::Bitcoin); |
| 351 | + match poller.poll_chain_tip(best_known_chain_tip).await { |
| 352 | + Err(e) => panic!("Unexpected error: {:?}", e), |
| 353 | + Ok(tip) => assert_eq!(tip, ChainTip::Better(better_chain_tip)), |
| 354 | + } |
| 355 | + } |
| 356 | +} |
0 commit comments