Skip to content

Commit

Permalink
chore(mempool): add logs to mempool logic
Browse files Browse the repository at this point in the history
  • Loading branch information
elintul committed Oct 20, 2024
1 parent 8ea0860 commit c3ee901
Show file tree
Hide file tree
Showing 6 changed files with 56 additions and 3 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/mempool/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ starknet_mempool_infra.workspace = true
starknet_mempool_p2p_types.workspace = true
starknet_mempool_types.workspace = true
tokio.workspace = true
tracing.workspace = true

[dev-dependencies]
assert_matches.workspace = true
Expand Down
48 changes: 45 additions & 3 deletions crates/mempool/src/mempool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use starknet_mempool_types::mempool_types::{
CommitBlockArgs,
MempoolResult,
};
use tracing;

use crate::transaction_pool::TransactionPool;
use crate::transaction_queue::TransactionQueue;
Expand Down Expand Up @@ -52,6 +53,7 @@ impl Mempool {
/// Transactions are guaranteed to be unique across calls until the block in-progress is
/// created.
// TODO: Consider renaming to `pop_txs` to be more consistent with the standard library.
#[tracing::instrument(skip(self), err)]
pub fn get_txs(&mut self, n_txs: usize) -> MempoolResult<Vec<Transaction>> {
let mut eligible_tx_references: Vec<TransactionReference> = Vec::with_capacity(n_txs);
let mut n_remaining_txs = n_txs;
Expand All @@ -68,6 +70,11 @@ impl Mempool {
self.mempool_state.insert(tx_ref.address, tx_ref.nonce);
}

tracing::info!(
"Returned {} out of {n_txs} transactions, ready for sequencing.",
eligible_tx_references.len()
);

Ok(eligible_tx_references
.iter()
.map(|tx_ref| {
Expand All @@ -80,6 +87,16 @@ impl Mempool {
}

/// Adds a new transaction to the mempool.
#[tracing::instrument(
skip(self, args),
fields( // Log subset of (informative) fields.
tx_nonce = %args.tx.nonce(),
tx_hash = %args.tx.tx_hash(),
account_state = %args.account_state
),
ret,
err
)]
pub fn add_tx(&mut self, args: AddTransactionArgs) -> MempoolResult<()> {
let AddTransactionArgs { tx, account_state } = args;
self.validate_incoming_nonce(tx.nonce(), account_state)?;
Expand All @@ -101,17 +118,22 @@ impl Mempool {

/// Update the mempool's internal state according to the committed block (resolves nonce gaps,
/// updates account balances).
#[tracing::instrument(skip(self, args), ret, err)]
pub fn commit_block(&mut self, args: CommitBlockArgs) -> MempoolResult<()> {
let CommitBlockArgs { nonces, tx_hashes } = args;
tracing::debug!("Committing block with {} transactions to mempool.", tx_hashes.len());

// Align mempool data to committed nonces.
for (&address, &nonce) in &args.nonces {
for (&address, &nonce) in &nonces {
let next_nonce = nonce.try_increment().map_err(|_| MempoolError::FeltOutOfRange)?;
let account_state = AccountState { address, nonce: next_nonce };
self.align_to_account_state(account_state);
}
tracing::debug!("Aligned mempool to committed nonces.");

// Rewind nonces of addresses that were not included in block.
let known_addresses_not_included_in_block =
self.mempool_state.keys().filter(|&key| !args.nonces.contains_key(key));
self.mempool_state.keys().filter(|&key| !nonces.contains_key(key));
for address in known_addresses_not_included_in_block {
// Account nonce is the minimal nonce of this address: it was proposed but not included.
let tx_reference = self
Expand All @@ -123,18 +145,21 @@ impl Mempool {
}

// Hard-delete: finally, remove committed transactions from the mempool.
for tx_hash in args.tx_hashes {
for tx_hash in tx_hashes {
let Ok(_tx) = self.tx_pool.remove(tx_hash) else {
continue; // Transaction hash unknown to mempool, from a different node.
};

// TODO(clean_account_nonces): remove address from nonce table after a block cycle /
// TTL.
}
tracing::debug!("Removed committed transactions known to mempool.");

// Commit: clear block creation staged state.
self.mempool_state.clear();

tracing::debug!("Successfully committed block to mempool.");

Ok(())
}

Expand Down Expand Up @@ -219,10 +244,16 @@ impl Mempool {
};

if !self.should_replace_tx(existing_tx_ref, &incoming_tx_ref) {
tracing::info!(
"{existing_tx_ref} was not replaced by {incoming_tx_ref} due to insufficient
fee escalation."
);
// TODO(Elin): consider adding a more specific error type / message.
return Err(MempoolError::DuplicateNonce { address, nonce });
}

tracing::info!("{existing_tx_ref} will be replaced by {incoming_tx_ref}.");

self.tx_queue.remove(address);
self.tx_pool
.remove(existing_tx_ref.tx_hash)
Expand Down Expand Up @@ -274,6 +305,17 @@ pub struct TransactionReference {
pub max_l2_gas_price: GasPrice,
}

impl std::fmt::Display for TransactionReference {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let TransactionReference { address, nonce, tx_hash, tip, max_l2_gas_price } = self;
write!(
f,
"TransactionReference {{ address: {address}, nonce: {nonce}, tx_hash: {tx_hash},
tip: {tip}, max_l2_gas_price: {max_l2_gas_price} }}"
)
}
}

impl TransactionReference {
pub fn new(tx: &Transaction) -> Self {
TransactionReference {
Expand Down
7 changes: 7 additions & 0 deletions crates/mempool_types/src/mempool_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,13 @@ pub struct AccountState {
pub nonce: Nonce,
}

impl std::fmt::Display for AccountState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let AccountState { address, nonce } = self;
write!(f, "AccountState {{ address: {address}, nonce: {nonce} }}")
}
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AddTransactionArgs {
pub tx: Transaction,
Expand Down
1 change: 1 addition & 0 deletions crates/starknet_api/src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,7 @@ pub struct CompiledClassHash(pub StarkHash);
#[derive(
Debug,
Default,
Display,
Copy,
Clone,
Eq,
Expand Down
1 change: 1 addition & 0 deletions crates/starknet_api/src/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -969,6 +969,7 @@ pub struct EventIndexInTransactionOutput(pub usize);
PartialOrd,
Serialize,
derive_more::Deref,
derive_more::Display,
)]
#[serde(from = "PrefixedBytesAsHex<8_usize>", into = "PrefixedBytesAsHex<8_usize>")]
pub struct Tip(pub u64);
Expand Down

0 comments on commit c3ee901

Please sign in to comment.