# TxPool (Mempool) The **TxPool** (Transaction Pool or Mempool) is the "waiting room" for transactions. When a transaction is received via the RPC, it is not immediately executed. Instead, it is validated and placed here until a Miner picks it up to include it in a block. ## Current Architecture (v0.3.0) In this iteration, the TxPool was updated to handle the new cryptographic data structures. ### 1. The Signed Storage The pool now stores `SignedTransaction` objects instead of raw `Transaction` structs. This ensures that the miner receives the full authorization (signature) needed to execute the transaction later. * **Underlying Data:** `HashMap<B256, SignedTransaction>` * **Key:** `B256` (The Keccak256 hash of the RLP-encoded transaction). * **Value:** The full `SignedTransaction` struct. ### 2. Thread Safety (`SharedTxPool`) Since the TxPool acts as a buffer between the **RPC Server** (Producer) and the **Miner** (Consumer), it must be thread-safe. It uses the `Arc<Mutex<>>` pattern to allow safe concurrent access. ### 3. Deduplication The pool automatically handles deduplication. If the RPC receives the exact same transaction twice (same nonce, same sender, same signature), the hash will be identical, and the `HashMap` will simply update the existing entry rather than creating a duplicate. ## API / Usage The TxPool crate exposes the following interface. ### Structs ```rust // The thread-safe wrapper pub struct SharedTxPool { ... } ``` ### Public Methods #### `new()` Creates a new, empty pool. #### `add(hash, transaction) -> Result` Adds a transaction to the pool. * **Input:** The computed `TxHash` and the `SignedTransaction` struct. * **Logic:** Inserts into the internal map. * **Returns:** `Ok(())` on success. ```rust // Example from RPC state.txpool.add(tx_hash, signed_tx)?; ``` #### `get_all_transactions() -> Vec<SignedTransaction>` Retrieves a snapshot of all pending transactions. * **Usage:** Called by the Miner when it is time to produce a new block. * **Note:** In a real production system, this would sort by "Gas Price" (highest fees first). Currently, it returns them in arbitrary order (HashMap iteration order). ## Evolution Log ### v0.1.0: The Set * **Structure:** `HashMap<Transaction, ()>`. * **Logic:** Used the Transaction struct itself as the key. It acted more like a "Set" (just checking for existence) than a map. ### v0.2.0: Hash Mapping * **Structure:** `HashMap<B256, Transaction>`. * **Change:** Introduced the Transaction Hash as the unique key. This allowed for faster lookups and better deduplication logic. ### v0.3.0: The Signed Update * **Structure:** `HashMap<B256, SignedTransaction>`. * **Change:** Updated to store the `SignedTransaction` struct. * **Tests:** Refactored unit tests to generate valid signatures using `k256` in order to interact with the pool correctly.