From 334329f38a32e23510ea62bdd974dfdc1bbf49d5 Mon Sep 17 00:00:00 2001 From: teor Date: Fri, 12 Jun 2020 15:04:52 +1000 Subject: [PATCH] state: Move block header hashing to block_index Only hash block headers in the lowest-level block index code. This design has a few benefits: - failures are obvious, because the hash is not available, - get_tip() returns a smaller object, - we avoid re-hashing block headers multiple times. These efficiency changes may be needed to support chain reorganisations, multiple tips, and heavy query loads. --- zebra-state/src/in_memory.rs | 7 ++++--- zebra-state/src/in_memory/block_index.rs | 8 ++++---- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/zebra-state/src/in_memory.rs b/zebra-state/src/in_memory.rs index f2898db0..81ae72c2 100644 --- a/zebra-state/src/in_memory.rs +++ b/zebra-state/src/in_memory.rs @@ -30,8 +30,10 @@ impl Service for ZebraState { fn call(&mut self, req: Request) -> Self::Future { match req { Request::AddBlock { block } => { - let hash = block.as_ref().into(); - let result = self.index.insert(block).map(|_| Response::Added { hash }); + let result = self + .index + .insert(block) + .map(|hash| Response::Added { hash }); async { result }.boxed() } @@ -48,7 +50,6 @@ impl Service for ZebraState { let result = self .index .get_tip() - .map(|block| block.as_ref().into()) .map(|hash| Response::Tip { hash }) .ok_or_else(|| "zebra-state contains no blocks".into()); diff --git a/zebra-state/src/in_memory/block_index.rs b/zebra-state/src/in_memory/block_index.rs index 87a0c1de..885b24af 100644 --- a/zebra-state/src/in_memory/block_index.rs +++ b/zebra-state/src/in_memory/block_index.rs @@ -17,7 +17,7 @@ impl BlockIndex { pub(super) fn insert( &mut self, block: impl Into>, - ) -> Result<(), Box> { + ) -> Result> { let block = block.into(); let hash = block.as_ref().into(); let height = block.coinbase_height().unwrap(); @@ -26,7 +26,7 @@ impl BlockIndex { Entry::Vacant(entry) => { let _ = entry.insert(block.clone()); let _ = self.by_hash.insert(hash, block); - Ok(()) + Ok(hash) } Entry::Occupied(_) => Err("forks in the chain aren't supported yet")?, } @@ -40,12 +40,12 @@ impl BlockIndex { .cloned() } - pub(super) fn get_tip(&self) -> Option> { + pub(super) fn get_tip(&self) -> Option { self.by_height .iter() .next_back() .map(|(_key, value)| value) - .cloned() + .map(|block| block.as_ref().into()) } }