From f345556a270d9cba7932dc2d9b5fa53a3054f4f5 Mon Sep 17 00:00:00 2001 From: Matthias Seitz Date: Thu, 26 Oct 2023 20:01:01 +0200 Subject: [PATCH] perf: clear all transactions if exceeds configured keeper (#6127) --- crates/anvil/src/eth/backend/mem/mod.rs | 14 ++++---------- crates/anvil/src/eth/backend/mem/storage.rs | 17 +++++++++++++++++ 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/crates/anvil/src/eth/backend/mem/mod.rs b/crates/anvil/src/eth/backend/mem/mod.rs index a8cd2b9e5a7c..0fe9bd9003c5 100644 --- a/crates/anvil/src/eth/backend/mem/mod.rs +++ b/crates/anvil/src/eth/backend/mem/mod.rs @@ -969,19 +969,13 @@ impl Backend { storage.transactions.insert(mined_tx.info.transaction_hash, mined_tx); } + // remove old transactions that exceed the transaction block keeper if let Some(transaction_block_keeper) = self.transaction_block_keeper { if storage.blocks.len() > transaction_block_keeper { - let n: U64 = block_number + let to_clear = block_number .as_u64() - .saturating_sub(transaction_block_keeper.try_into().unwrap()) - .into(); - if let Some(hash) = storage.hashes.get(&n) { - if let Some(block) = storage.blocks.get(hash) { - for tx in block.clone().transactions { - let _ = storage.transactions.remove(&tx.hash()); - } - } - } + .saturating_sub(transaction_block_keeper.try_into().unwrap()); + storage.remove_block_transactions_by_number(to_clear) } } diff --git a/crates/anvil/src/eth/backend/mem/storage.rs b/crates/anvil/src/eth/backend/mem/storage.rs index 4d693ed06011..7da581aba46b 100644 --- a/crates/anvil/src/eth/backend/mem/storage.rs +++ b/crates/anvil/src/eth/backend/mem/storage.rs @@ -272,6 +272,23 @@ impl BlockchainStorage { total_difficulty: Default::default(), } } + + /// Removes all stored transactions for the given block number + pub fn remove_block_transactions_by_number(&mut self, num: u64) { + if let Some(hash) = self.hashes.get(&(num.into())).copied() { + self.remove_block_transactions(hash); + } + } + + /// Removes all stored transactions for the given block hash + pub fn remove_block_transactions(&mut self, block_hash: H256) { + if let Some(block) = self.blocks.get_mut(&block_hash) { + for tx in block.transactions.iter() { + self.transactions.remove(&tx.hash()); + } + block.transactions.clear(); + } + } } // === impl BlockchainStorage ===