From 10015be42a6291b75a2688b7dec87849e397b8c5 Mon Sep 17 00:00:00 2001 From: Mohammad Nassar Date: Thu, 18 Jul 2024 17:30:06 +0300 Subject: [PATCH] fix(mempool): fix add-tx method by updating the queue according to input state --- crates/mempool/src/mempool.rs | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/crates/mempool/src/mempool.rs b/crates/mempool/src/mempool.rs index d6ee6382..31558a4b 100644 --- a/crates/mempool/src/mempool.rs +++ b/crates/mempool/src/mempool.rs @@ -99,13 +99,26 @@ impl Mempool { } fn insert_tx(&mut self, input: MempoolInput) -> MempoolResult<()> { - let MempoolInput { tx, account } = input; - let tx_reference = TransactionReference::new(&tx); + let MempoolInput { tx, account: Account { sender_address, state: AccountState { nonce } } } = + input; + + // Invalid input. + // TODO(Mohammad): use `should_insert` method. + if tx.nonce < nonce { + return Err(MempoolError::DuplicateTransaction { tx_hash: tx.tx_hash }); + } self.tx_pool.insert(tx)?; - if is_eligible_for_sequencing(tx_reference, account) { - self.tx_queue.insert(tx_reference); + // If the queue is empty, check if a transaction can be inserted into the transaction queue: + // 1. If the input transaction can be added to the queue, this can happen when the input + // transaction's nonce equals the next nonce. + // 2. If the input state fills a gap in the transaction queue, insert it into the queue. + if self.tx_queue.get_nonce(sender_address).is_none() { + if let Some(tx_reference) = self.tx_pool.get_by_address_and_nonce(sender_address, nonce) + { + self.tx_queue.insert(*tx_reference); + } } Ok(()) @@ -139,7 +152,3 @@ impl TransactionReference { } } } - -fn is_eligible_for_sequencing(tx_reference: TransactionReference, account: Account) -> bool { - tx_reference.nonce == account.state.nonce -}