From e2cc2616e11f32ac32ed5b97f5fec18ccb28f4a5 Mon Sep 17 00:00:00 2001 From: Gilad Chase Date: Thu, 13 Jun 2024 12:08:24 +0300 Subject: [PATCH] fix: change inner AddressPrioQueue - pop_front in Vec is O(n). - should be private to protect invariant. --- crates/mempool/src/priority_queue.rs | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/crates/mempool/src/priority_queue.rs b/crates/mempool/src/priority_queue.rs index cec62d0c..ff53086b 100644 --- a/crates/mempool/src/priority_queue.rs +++ b/crates/mempool/src/priority_queue.rs @@ -1,5 +1,5 @@ use std::cmp::Ordering; -use std::collections::BTreeSet; +use std::collections::{BTreeSet, VecDeque}; use starknet_mempool_types::mempool_types::ThinTransaction; // Assumption: for the MVP only one transaction from the same contract class can be in the mempool @@ -61,22 +61,32 @@ impl PartialOrd for PrioritizedTransaction { // TODO: remove when is used. #[allow(dead_code)] -// Assumption: there are no gaps, and the transactions are received in order. -pub struct AddressPriorityQueue(pub Vec); +// Invariant: Transactions have strictly increasing nonces, without gaps. +// Assumption: Transactions are provided in the correct order. +#[derive(Default)] +pub struct AddressPriorityQueue(VecDeque); // TODO: remove when is used. #[allow(dead_code)] impl AddressPriorityQueue { pub fn push(&mut self, tx: ThinTransaction) { - self.0.push(tx); + if let Some(last_tx) = self.0.back() { + assert_eq!( + tx.nonce, + last_tx.nonce.try_increment().expect("Nonce overflow."), + "Nonces must be strictly increasing without gaps." + ); + } + + self.0.push_back(tx); } pub fn top(&self) -> Option<&ThinTransaction> { - self.0.first() + self.0.front() } - pub fn pop_front(&mut self) -> ThinTransaction { - self.0.remove(0) + pub fn pop_front(&mut self) -> Option { + self.0.pop_front() } pub fn is_empty(&self) -> bool {