Skip to main content

reth_transaction_pool/
maintain.rs

1//! Support for maintaining the state of the transaction pool
2
3use crate::{
4    blobstore::{BlobStoreCanonTracker, BlobStoreUpdates},
5    error::PoolError,
6    metrics::MaintainPoolMetrics,
7    traits::{CanonicalStateUpdate, EthPoolTransaction, TransactionPool, TransactionPoolExt},
8    BlockInfo, PoolTransaction, PoolUpdateKind, TransactionOrigin,
9};
10use alloy_consensus::{transaction::TxHashRef, BlockHeader, Typed2718};
11use alloy_eips::{BlockNumberOrTag, Decodable2718};
12use alloy_primitives::{
13    map::{AddressSet, B256Set, HashSet},
14    Address, BlockHash, BlockNumber, Bytes,
15};
16use alloy_rlp::Encodable;
17use futures_util::{
18    future::{BoxFuture, Fuse, FusedFuture},
19    FutureExt, Stream, StreamExt,
20};
21use reth_chain_state::CanonStateNotification;
22use reth_chainspec::{ChainSpecProvider, EthChainSpec, EthereumHardforks};
23use reth_execution_types::ChangedAccount;
24use reth_fs_util::FsPathError;
25use reth_primitives_traits::{
26    transaction::signed::SignedTransaction, NodePrimitives, SealedHeader,
27};
28use reth_storage_api::{errors::provider::ProviderError, BlockReaderIdExt, StateProviderFactory};
29use reth_tasks::Runtime;
30use serde::{Deserialize, Serialize};
31use std::{
32    borrow::Borrow,
33    hash::{Hash, Hasher},
34    path::{Path, PathBuf},
35    sync::Arc,
36};
37use tokio::{
38    sync::oneshot,
39    time::{self, Duration},
40};
41use tracing::{debug, error, info, trace, warn};
42
43/// Maximum amount of time non-executable transaction are queued.
44pub const MAX_QUEUED_TRANSACTION_LIFETIME: Duration = Duration::from_secs(3 * 60 * 60);
45
46/// Additional settings for maintaining the transaction pool
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub struct MaintainPoolConfig {
49    /// Maximum (reorg) depth we handle when updating the transaction pool: `new.number -
50    /// last_seen.number`
51    ///
52    /// Default: 64 (2 epochs)
53    pub max_update_depth: u64,
54    /// Maximum number of accounts to reload from state at once when updating the transaction pool.
55    ///
56    /// Default: 100
57    pub max_reload_accounts: usize,
58
59    /// Maximum amount of time non-executable, non local transactions are queued.
60    /// Default: 3 hours
61    pub max_tx_lifetime: Duration,
62
63    /// Apply no exemptions to the locally received transactions.
64    ///
65    /// This includes:
66    ///   - no price exemptions
67    ///   - no eviction exemptions
68    pub no_local_exemptions: bool,
69}
70
71impl Default for MaintainPoolConfig {
72    fn default() -> Self {
73        Self {
74            max_update_depth: 64,
75            max_reload_accounts: 100,
76            max_tx_lifetime: MAX_QUEUED_TRANSACTION_LIFETIME,
77            no_local_exemptions: false,
78        }
79    }
80}
81
82/// Settings for local transaction backup task
83#[derive(Debug, Clone, Default)]
84pub struct LocalTransactionBackupConfig {
85    /// Path to transactions backup file
86    pub transactions_path: Option<PathBuf>,
87}
88
89impl LocalTransactionBackupConfig {
90    /// Receive path to transactions backup and return initialized config
91    pub const fn with_local_txs_backup(transactions_path: PathBuf) -> Self {
92        Self { transactions_path: Some(transactions_path) }
93    }
94}
95
96/// Returns a spawnable future for maintaining the state of the transaction pool.
97pub fn maintain_transaction_pool_future<N, Client, P, St>(
98    client: Client,
99    pool: P,
100    events: St,
101    task_spawner: Runtime,
102    config: MaintainPoolConfig,
103) -> BoxFuture<'static, ()>
104where
105    N: NodePrimitives,
106    Client: StateProviderFactory
107        + BlockReaderIdExt<Header = N::BlockHeader>
108        + ChainSpecProvider<ChainSpec: EthChainSpec<Header = N::BlockHeader> + EthereumHardforks>
109        + Clone
110        + 'static,
111    P: TransactionPoolExt<Transaction: PoolTransaction<Consensus = N::SignedTx>, Block = N::Block>
112        + 'static,
113    St: Stream<Item = CanonStateNotification<N>> + Send + Unpin + 'static,
114{
115    async move {
116        maintain_transaction_pool(client, pool, events, task_spawner, config).await;
117    }
118    .boxed()
119}
120
121/// Maintains the state of the transaction pool by handling new blocks and reorgs.
122///
123/// This listens for any new blocks and reorgs and updates the transaction pool's state accordingly
124pub async fn maintain_transaction_pool<N, Client, P, St>(
125    client: Client,
126    pool: P,
127    mut events: St,
128    task_spawner: Runtime,
129    config: MaintainPoolConfig,
130) where
131    N: NodePrimitives,
132    Client: StateProviderFactory
133        + BlockReaderIdExt<Header = N::BlockHeader>
134        + ChainSpecProvider<ChainSpec: EthChainSpec<Header = N::BlockHeader> + EthereumHardforks>
135        + Clone
136        + 'static,
137    P: TransactionPoolExt<Transaction: PoolTransaction<Consensus = N::SignedTx>, Block = N::Block>
138        + 'static,
139    St: Stream<Item = CanonStateNotification<N>> + Send + Unpin + 'static,
140{
141    let metrics = MaintainPoolMetrics::default();
142    let MaintainPoolConfig { max_update_depth, max_reload_accounts, .. } = config;
143    // ensure the pool points to latest state
144    if let Ok(Some(latest)) = client.header_by_number_or_tag(BlockNumberOrTag::Latest) {
145        let latest = SealedHeader::seal_slow(latest);
146        let chain_spec = client.chain_spec();
147        let info = BlockInfo {
148            block_gas_limit: latest.gas_limit(),
149            last_seen_block_hash: latest.hash(),
150            last_seen_block_number: latest.number(),
151            pending_basefee: chain_spec
152                .next_block_base_fee(latest.header(), latest.timestamp())
153                .unwrap_or_default(),
154            pending_blob_fee: latest
155                .maybe_next_block_blob_fee(chain_spec.blob_params_at_timestamp(latest.timestamp())),
156        };
157        pool.set_block_info(info);
158    }
159
160    // keeps track of mined blob transaction so we can clean finalized transactions
161    let mut blob_store_tracker = BlobStoreCanonTracker::default();
162
163    // handle to the pool's blob store, used to skip cleanup while it holds no blobs
164    let blob_store = pool.blob_store();
165
166    // keeps track of the latest finalized block
167    let mut last_finalized_block =
168        FinalizedBlockTracker::new(client.finalized_block_number().ok().flatten());
169
170    // keeps track of any dirty accounts that we know of are out of sync with the pool
171    let mut dirty_addresses = HashSet::default();
172
173    // keeps track of the state of the pool wrt to blocks
174    let mut maintained_state = MaintainedPoolState::InSync;
175
176    // the future that reloads accounts from state
177    let mut reload_accounts_fut = Fuse::terminated();
178
179    // set when a reload failed because historical state is unavailable during pipeline sync,
180    // retrying is pointless until the next canonical state event
181    let mut wait_for_next_event = false;
182
183    // eviction interval for stale non local txs
184    let mut stale_eviction_interval = time::interval(config.max_tx_lifetime);
185
186    // toggle for the first notification
187    let mut first_event = true;
188
189    // The update loop that waits for new blocks and reorgs and performs pool updated
190    // Listen for new chain events and derive the update action for the pool
191    loop {
192        trace!(target: "txpool", state=?maintained_state, "awaiting new block or reorg");
193
194        metrics.set_dirty_accounts_len(dirty_addresses.len());
195        let pool_info = pool.block_info();
196
197        // after performing a pool update after a new block we have some time to properly update
198        // dirty accounts and correct if the pool drifted from current state, for example after
199        // restart or a pipeline run
200        if maintained_state.is_drifted() {
201            metrics.inc_drift();
202            // assuming all senders are dirty
203            dirty_addresses = pool.unique_senders();
204            // make sure we toggle the state back to in sync
205            maintained_state = MaintainedPoolState::InSync;
206        }
207
208        // if we have accounts that are out of sync with the pool, we reload them in chunks
209        if !dirty_addresses.is_empty() &&
210            reload_accounts_fut.is_terminated() &&
211            !wait_for_next_event
212        {
213            let (tx, rx) = oneshot::channel();
214            let c = client.clone();
215            let at = pool_info.last_seen_block_hash;
216            let fut = if dirty_addresses.len() > max_reload_accounts {
217                // need to chunk accounts to reload
218                let accs_to_reload =
219                    dirty_addresses.iter().copied().take(max_reload_accounts).collect::<Vec<_>>();
220                for acc in &accs_to_reload {
221                    // make sure we remove them from the dirty set
222                    dirty_addresses.remove(acc);
223                }
224                async move {
225                    let res = load_accounts(c, at, accs_to_reload);
226                    let _ = tx.send(res);
227                }
228                .boxed()
229            } else {
230                // can fetch all dirty accounts at once
231                let accs_to_reload = std::mem::take(&mut dirty_addresses);
232                async move {
233                    let res = load_accounts(c, at, accs_to_reload);
234                    let _ = tx.send(res);
235                }
236                .boxed()
237            };
238            reload_accounts_fut = rx.fuse();
239            task_spawner.spawn_blocking_task(fut);
240        }
241
242        // check if we have a new finalized block
243        if let Some(finalized) =
244            last_finalized_block.update(client.finalized_block_number().ok().flatten())
245        {
246            if let BlobStoreUpdates::Finalized(blobs) =
247                blob_store_tracker.on_finalized_block(finalized)
248            {
249                metrics.inc_deleted_tracked_blobs(blobs.len());
250                // remove all finalized blobs from the blob store
251                pool.delete_blobs(blobs);
252            }
253            // and also do periodic cleanup, deletions of replaced or evicted blobs are only queued
254            // in the blob store until this runs, and queued blobs still count towards its length
255            if blob_store.blobs_len() > 0 {
256                let pool = pool.clone();
257                task_spawner.spawn_blocking_task(async move {
258                    debug!(target: "txpool", finalized_block = %finalized, "cleaning up blob store");
259                    pool.cleanup_blobs();
260                });
261            }
262        }
263
264        // outcomes of the futures we are waiting on
265        let mut event = None;
266        let mut reloaded = None;
267
268        // select of account reloads and new canonical state updates which should arrive at the rate
269        // of the block time
270        tokio::select! {
271            res = &mut reload_accounts_fut =>  {
272                reloaded = Some(res);
273            }
274            ev = events.next() =>  {
275                 if ev.is_none() {
276                    // the stream ended, we are done
277                    break;
278                }
279                event = ev;
280                // state may have advanced, so allow reloading dirty accounts again
281                wait_for_next_event = false;
282                // on receiving the first event on start up, mark the pool as drifted to explicitly
283                // trigger revalidation and clear out outdated txs.
284                if first_event {
285                    maintained_state = MaintainedPoolState::Drifted;
286                    first_event = false
287                }
288            }
289            _ = stale_eviction_interval.tick() => {
290                let queued = pool
291                    .queued_transactions();
292                let mut stale_blobs = Vec::new();
293                let now = std::time::Instant::now();
294                let stale_txs: Vec<_> = queued
295                    .into_iter()
296                    .filter(|tx| {
297                        // filter stale transactions based on config
298                        (tx.origin.is_external() || config.no_local_exemptions) && now - tx.timestamp > config.max_tx_lifetime
299                    })
300                    .map(|tx| {
301                        if tx.is_eip4844() {
302                            stale_blobs.push(*tx.hash());
303                        }
304                        *tx.hash()
305                    })
306                    .collect();
307                debug!(target: "txpool", count=%stale_txs.len(), "removing stale transactions");
308                pool.remove_transactions(stale_txs);
309                pool.delete_blobs(stale_blobs);
310            }
311        }
312        // handle the result of the account reload
313        match reloaded {
314            Some(Ok(Ok(LoadedAccounts { accounts, failed_to_load }))) => {
315                // reloaded accounts successfully
316                // extend accounts we failed to load from database
317                dirty_addresses.extend(failed_to_load);
318                // update the pool with the loaded accounts
319                pool.update_accounts(accounts);
320            }
321            Some(Ok(Err(res))) => {
322                // Failed to load accounts from state
323                let (accs, err) = *res;
324                debug!(target: "txpool", %err, "failed to load accounts");
325                if matches!(err, ProviderError::StateUnavailableDuringSync) {
326                    wait_for_next_event = true;
327                }
328                dirty_addresses.extend(accs);
329            }
330            Some(Err(_)) => {
331                // failed to receive the accounts, sender dropped, only possible if task panicked
332                maintained_state = MaintainedPoolState::Drifted;
333            }
334            None => {}
335        }
336
337        // handle the new block or reorg
338        let Some(event) = event else { continue };
339        match event {
340            CanonStateNotification::Reorg { old, new } => {
341                let (old_blocks, old_state) = old.inner();
342                let (new_blocks, new_state) = new.inner();
343                let new_tip = new_blocks.tip();
344                let new_first = new_blocks.first();
345                let old_first = old_blocks.first();
346
347                // check if the reorg is not canonical with the pool's block
348                if !(old_first.parent_hash() == pool_info.last_seen_block_hash ||
349                    new_first.parent_hash() == pool_info.last_seen_block_hash)
350                {
351                    // the new block points to a higher block than the oldest block in the old chain
352                    maintained_state = MaintainedPoolState::Drifted;
353                }
354
355                let chain_spec = client.chain_spec();
356
357                // fees for the next block: `new_tip+1`
358                let pending_block_base_fee = chain_spec
359                    .next_block_base_fee(new_tip.header(), new_tip.timestamp())
360                    .unwrap_or_default();
361                let pending_block_blob_fee = new_tip.header().maybe_next_block_blob_fee(
362                    chain_spec.blob_params_at_timestamp(new_tip.timestamp()),
363                );
364
365                // we know all changed account in the new chain
366                let new_changed_accounts: HashSet<_> =
367                    new_state.changed_accounts().map(ChangedAccountEntry).collect();
368
369                // find all accounts that were changed in the old chain but _not_ in the new chain
370                let missing_changed_acc = old_state
371                    .accounts_iter()
372                    .map(|(a, _)| a)
373                    .filter(|addr| !new_changed_accounts.contains(addr));
374
375                // for these we need to fetch the nonce+balance from the db at the new tip
376                let mut changed_accounts =
377                    match load_accounts(client.clone(), new_tip.hash(), missing_changed_acc) {
378                        Ok(LoadedAccounts { accounts, failed_to_load }) => {
379                            // extend accounts we failed to load from database
380                            dirty_addresses.extend(failed_to_load);
381
382                            accounts
383                        }
384                        Err(err) => {
385                            let (addresses, err) = *err;
386                            debug!(
387                                target: "txpool",
388                                %err,
389                                "failed to load missing changed accounts at new tip: {:?}",
390                                new_tip.hash()
391                            );
392                            dirty_addresses.extend(addresses);
393                            vec![]
394                        }
395                    };
396
397                // also include all accounts from new chain
398                // we can use extend here because they are unique
399                changed_accounts.extend(new_changed_accounts.into_iter().map(|entry| entry.0));
400
401                // all transactions mined in the new chain
402                let mined_transactions = new_blocks.transaction_hashes_vec();
403                let new_mined_transactions =
404                    mined_transactions.iter().copied().collect::<B256Set>();
405
406                // update the pool then re-inject the pruned transactions
407                // find all transactions that were mined in the old chain but not in the new chain
408                let pruned_old_transactions = old_blocks
409                    .transactions_with_sender()
410                    .filter(|(_, tx)| !new_mined_transactions.contains(tx.tx_hash()))
411                    .filter_map(|(signer, tx)| {
412                        let tx = tx.clone().with_signer(*signer);
413                        if tx.is_eip4844() {
414                            // reorged blobs no longer include the blob, which is necessary for
415                            // validating the transaction. Even though the transaction could have
416                            // been validated previously, we still need the blob in order to
417                            // accurately set the transaction's
418                            // encoded-length which is propagated over the network.
419                            pool.get_blob(*tx.tx_hash())
420                                .ok()
421                                .flatten()
422                                .map(Arc::unwrap_or_clone)
423                                .and_then(|sidecar| {
424                                    <P as TransactionPool>::Transaction::try_from_eip4844(
425                                        tx, sidecar,
426                                    )
427                                })
428                        } else {
429                            <P as TransactionPool>::Transaction::try_from_consensus(tx).ok()
430                        }
431                    })
432                    .collect::<Vec<_>>();
433
434                // update the pool first
435                let update = CanonicalStateUpdate {
436                    new_tip: new_tip.sealed_block(),
437                    pending_block_base_fee,
438                    pending_block_blob_fee,
439                    changed_accounts,
440                    // all transactions mined in the new chain need to be removed from the pool
441                    mined_transactions,
442                    update_kind: PoolUpdateKind::Reorg,
443                };
444                pool.on_canonical_state_change(update);
445
446                // all transactions that were mined in the old chain but not in the new chain need
447                // to be re-injected
448                //
449                // Note: we no longer know if the tx was local or external
450                // Because the transactions are not finalized, the corresponding blobs are still in
451                // blob store (if we previously received them from the network)
452                metrics.inc_reinserted_transactions(pruned_old_transactions.len());
453                let _ = pool.add_external_transactions(pruned_old_transactions).await;
454
455                // keep track of new mined blob transactions
456                blob_store_tracker.add_new_chain_blocks(&new_blocks);
457            }
458            CanonStateNotification::Commit { new } => {
459                let (blocks, state) = new.inner();
460                let tip = blocks.tip();
461                let chain_spec = client.chain_spec();
462
463                // fees for the next block: `tip+1`
464                let pending_block_base_fee = chain_spec
465                    .next_block_base_fee(tip.header(), tip.timestamp())
466                    .unwrap_or_default();
467                let pending_block_blob_fee = tip.header().maybe_next_block_blob_fee(
468                    chain_spec.blob_params_at_timestamp(tip.timestamp()),
469                );
470
471                let first_block = blocks.first();
472                trace!(
473                    target: "txpool",
474                    first = first_block.number(),
475                    tip = tip.number(),
476                    pool_block = pool_info.last_seen_block_number,
477                    "update pool on new commit"
478                );
479
480                // check if the depth is too large and should be skipped, this could happen after
481                // initial sync or long re-sync
482                let depth = tip.number().abs_diff(pool_info.last_seen_block_number);
483                if depth > max_update_depth {
484                    maintained_state = MaintainedPoolState::Drifted;
485                    debug!(target: "txpool", ?depth, "skipping deep canonical update");
486                    // move the pool and the validator to the new tip without updating accounts or
487                    // removing mined transactions
488                    let update = CanonicalStateUpdate {
489                        new_tip: tip.sealed_block(),
490                        pending_block_base_fee,
491                        pending_block_blob_fee,
492                        changed_accounts: Vec::new(),
493                        mined_transactions: Vec::new(),
494                        update_kind: PoolUpdateKind::Commit,
495                    };
496                    pool.on_canonical_state_change(update);
497
498                    // keep track of mined blob transactions
499                    blob_store_tracker.add_new_chain_blocks(&blocks);
500
501                    continue
502                }
503
504                let mut changed_accounts = Vec::with_capacity(state.state().len());
505                for acc in state.changed_accounts() {
506                    // we can always clear the dirty flag for this account
507                    dirty_addresses.remove(&acc.address);
508                    changed_accounts.push(acc);
509                }
510
511                let mined_transactions = blocks.transaction_hashes_vec();
512
513                // check if the range of the commit is canonical with the pool's block
514                if first_block.parent_hash() != pool_info.last_seen_block_hash {
515                    // we received a new canonical chain commit but the commit is not canonical with
516                    // the pool's block, this could happen after initial sync or
517                    // long re-sync
518                    maintained_state = MaintainedPoolState::Drifted;
519                }
520
521                // Canonical update
522                let update = CanonicalStateUpdate {
523                    new_tip: tip.sealed_block(),
524                    pending_block_base_fee,
525                    pending_block_blob_fee,
526                    changed_accounts,
527                    mined_transactions,
528                    update_kind: PoolUpdateKind::Commit,
529                };
530                pool.on_canonical_state_change(update);
531
532                // keep track of mined blob transactions
533                blob_store_tracker.add_new_chain_blocks(&blocks);
534            }
535        }
536    }
537}
538
539struct FinalizedBlockTracker {
540    last_finalized_block: Option<BlockNumber>,
541}
542
543impl FinalizedBlockTracker {
544    const fn new(last_finalized_block: Option<BlockNumber>) -> Self {
545        Self { last_finalized_block }
546    }
547
548    /// Updates the tracked finalized block and returns the new finalized block if it changed
549    fn update(&mut self, finalized_block: Option<BlockNumber>) -> Option<BlockNumber> {
550        let finalized = finalized_block?;
551        self.last_finalized_block.is_none_or(|last| last < finalized).then(|| {
552            self.last_finalized_block = Some(finalized);
553            finalized
554        })
555    }
556}
557
558/// Keeps track of the pool's state, whether the accounts in the pool are in sync with the actual
559/// state.
560#[derive(Debug, PartialEq, Eq)]
561enum MaintainedPoolState {
562    /// Pool is assumed to be in sync with the current state
563    InSync,
564    /// Pool could be out of sync with the state
565    Drifted,
566}
567
568impl MaintainedPoolState {
569    /// Returns `true` if the pool is assumed to be out of sync with the current state.
570    #[inline]
571    const fn is_drifted(&self) -> bool {
572        matches!(self, Self::Drifted)
573    }
574}
575
576/// A unique [`ChangedAccount`] identified by its address that can be used for deduplication
577#[derive(Eq)]
578struct ChangedAccountEntry(ChangedAccount);
579
580impl PartialEq for ChangedAccountEntry {
581    fn eq(&self, other: &Self) -> bool {
582        self.0.address == other.0.address
583    }
584}
585
586impl Hash for ChangedAccountEntry {
587    fn hash<H: Hasher>(&self, state: &mut H) {
588        self.0.address.hash(state);
589    }
590}
591
592impl Borrow<Address> for ChangedAccountEntry {
593    fn borrow(&self) -> &Address {
594        &self.0.address
595    }
596}
597
598#[derive(Default)]
599struct LoadedAccounts {
600    /// All accounts that were loaded
601    accounts: Vec<ChangedAccount>,
602    /// All accounts that failed to load
603    failed_to_load: Vec<Address>,
604}
605
606/// Loads all accounts at the given state
607///
608/// Returns an error with all given addresses if the state is not available.
609///
610/// Note: this expects _unique_ addresses
611fn load_accounts<Client, I>(
612    client: Client,
613    at: BlockHash,
614    addresses: I,
615) -> Result<LoadedAccounts, Box<(AddressSet, ProviderError)>>
616where
617    I: IntoIterator<Item = Address>,
618    Client: StateProviderFactory,
619{
620    let addresses = addresses.into_iter();
621    let mut res = LoadedAccounts::default();
622    let state = match client.history_by_block_hash(at) {
623        Ok(state) => state,
624        Err(err) => return Err(Box::new((addresses.collect(), err))),
625    };
626    for addr in addresses {
627        if let Ok(maybe_acc) = state.basic_account(&addr) {
628            let acc = maybe_acc
629                .map(|acc| ChangedAccount { address: addr, nonce: acc.nonce, balance: acc.balance })
630                .unwrap_or_else(|| ChangedAccount::empty(addr));
631            res.accounts.push(acc)
632        } else {
633            // failed to load account.
634            res.failed_to_load.push(addr);
635        }
636    }
637    Ok(res)
638}
639
640/// Loads transactions from a file, decodes them from the JSON or RLP format, and
641/// inserts them into the transaction pool on node boot up.
642/// The file is removed after the transactions have been successfully processed.
643async fn load_and_reinsert_transactions<P>(
644    pool: P,
645    file_path: &Path,
646) -> Result<(), TransactionsBackupError>
647where
648    P: TransactionPool<Transaction: PoolTransaction<Consensus: SignedTransaction>>,
649{
650    if !file_path.exists() {
651        return Ok(())
652    }
653
654    debug!(target: "txpool", txs_file =?file_path, "Check local persistent storage for saved transactions");
655    let data = reth_fs_util::read(file_path)?;
656
657    if data.is_empty() {
658        return Ok(())
659    }
660
661    let pool_transactions: Vec<(TransactionOrigin, <P as TransactionPool>::Transaction)> =
662        if let Ok(tx_backups) = serde_json::from_slice::<Vec<TxBackup>>(&data) {
663            tx_backups
664                .into_iter()
665                .filter_map(|backup| {
666                    let tx_signed =
667                        <P::Transaction as PoolTransaction>::Consensus::decode_2718_exact(
668                            backup.rlp.as_ref(),
669                        )
670                        .ok()?;
671                    let recovered = tx_signed.try_into_recovered().ok()?;
672                    let pool_tx =
673                        <P::Transaction as PoolTransaction>::try_from_consensus(recovered).ok()?;
674
675                    Some((backup.origin, pool_tx))
676                })
677                .collect()
678        } else {
679            let txs_signed: Vec<<P::Transaction as PoolTransaction>::Consensus> =
680                alloy_rlp::Decodable::decode(&mut data.as_slice())?;
681
682            txs_signed
683                .into_iter()
684                .filter_map(|tx| tx.try_into_recovered().ok())
685                .filter_map(|tx| {
686                    <P::Transaction as PoolTransaction>::try_from_consensus(tx)
687                        .ok()
688                        .map(|pool_tx| (TransactionOrigin::Local, pool_tx))
689                })
690                .collect()
691        };
692
693    let inserted = futures_util::future::join_all(
694        pool_transactions.into_iter().map(|(origin, tx)| pool.add_transaction(origin, tx)),
695    )
696    .await;
697
698    info!(target: "txpool", txs_file =?file_path, num_txs=%inserted.len(), "Successfully reinserted local transactions from file");
699    reth_fs_util::remove_file(file_path)?;
700    Ok(())
701}
702
703fn save_local_txs_backup<P>(pool: P, file_path: &Path)
704where
705    P: TransactionPool<Transaction: PoolTransaction<Consensus: Encodable>>,
706{
707    let local_transactions = pool.get_local_transactions();
708    if local_transactions.is_empty() {
709        trace!(target: "txpool", "no local transactions to save");
710        return
711    }
712
713    let local_transactions = local_transactions
714        .into_iter()
715        .map(|tx| TxBackup { rlp: tx.encoded_2718_consensus(), origin: tx.origin })
716        .collect::<Vec<_>>();
717
718    let json_data = match serde_json::to_string(&local_transactions) {
719        Ok(data) => data,
720        Err(err) => {
721            warn!(target: "txpool", %err, txs_file=?file_path, "failed to serialize local transactions to json");
722            return
723        }
724    };
725
726    info!(target: "txpool", txs_file =?file_path, num_txs=%local_transactions.len(), "Saving current local transactions");
727    let parent_dir = file_path.parent().map(std::fs::create_dir_all).transpose();
728
729    match parent_dir.map(|_| reth_fs_util::write(file_path, json_data)) {
730        Ok(_) => {
731            info!(target: "txpool", txs_file=?file_path, "Wrote local transactions to file");
732        }
733        Err(err) => {
734            warn!(target: "txpool", %err, txs_file=?file_path, "Failed to write local transactions to file");
735        }
736    }
737}
738
739/// A transaction backup that is saved as json to a file for
740/// reinsertion into the pool
741#[derive(Debug, Deserialize, Serialize)]
742pub struct TxBackup {
743    /// Encoded transaction
744    pub rlp: Bytes,
745    /// The origin of the transaction
746    pub origin: TransactionOrigin,
747}
748
749/// Errors possible during txs backup load and decode
750#[derive(thiserror::Error, Debug)]
751pub enum TransactionsBackupError {
752    /// Error during RLP decoding of transactions
753    #[error("failed to apply transactions backup. Encountered RLP decode error: {0}")]
754    Decode(#[from] alloy_rlp::Error),
755    /// Error during json decoding of transactions
756    #[error("failed to apply transactions backup. Encountered JSON decode error: {0}")]
757    Json(#[from] serde_json::Error),
758    /// Error during file upload
759    #[error("failed to apply transactions backup. Encountered file error: {0}")]
760    FsPath(#[from] FsPathError),
761    /// Error adding transactions to the transaction pool
762    #[error("failed to insert transactions to the transactions pool. Encountered pool error: {0}")]
763    Pool(#[from] PoolError),
764}
765
766/// Task which manages saving local transactions to the persistent file in case of shutdown.
767/// Reloads the transactions from the file on the boot up and inserts them into the pool.
768pub async fn backup_local_transactions_task<P>(
769    shutdown: reth_tasks::shutdown::GracefulShutdown,
770    pool: P,
771    config: LocalTransactionBackupConfig,
772) where
773    P: TransactionPool<Transaction: PoolTransaction<Consensus: SignedTransaction>>,
774{
775    let Some(transactions_path) = config.transactions_path else {
776        // nothing to do
777        return
778    };
779
780    if let Err(err) = load_and_reinsert_transactions(pool.clone(), &transactions_path).await {
781        error!(target: "txpool", "{}", err)
782    }
783
784    let graceful_guard = shutdown.await;
785
786    // write transactions to disk
787    save_local_txs_backup(pool, &transactions_path);
788
789    drop(graceful_guard)
790}
791
792#[cfg(test)]
793mod tests {
794    use super::*;
795    use crate::{
796        blobstore::InMemoryBlobStore,
797        error::{InvalidPoolTransactionError, PoolErrorKind},
798        test_utils::TransactionBuilder,
799        validate::EthTransactionValidatorBuilder,
800        CoinbaseTipOrdering, EthPooledTransaction, Pool, TransactionOrigin,
801    };
802    use alloy_consensus::Header;
803    use alloy_eips::{eip1559::ETHEREUM_BLOCK_GAS_LIMIT_30M, eip2718::Decodable2718};
804    use alloy_primitives::{address, hex, B256, U256};
805    use reth_ethereum_primitives::{Block, PooledTransactionVariant};
806    use reth_evm_ethereum::EthEvmConfig;
807    use reth_execution_types::Chain;
808    use reth_fs_util as fs;
809    use reth_primitives_traits::{RecoveredBlock, SealedBlock};
810    use reth_provider::test_utils::{ExtendedAccount, MockEthProvider};
811    use reth_tasks::Runtime;
812
813    #[test]
814    fn changed_acc_entry() {
815        let changed_acc = ChangedAccountEntry(ChangedAccount::empty(Address::random()));
816        let mut copy = changed_acc.0;
817        copy.nonce = 10;
818        assert!(changed_acc.eq(&ChangedAccountEntry(copy)));
819    }
820
821    const EXTENSION: &str = "json";
822    const FILENAME: &str = "test_transactions_backup";
823
824    #[tokio::test(flavor = "multi_thread")]
825    async fn test_save_local_txs_backup() {
826        let temp_dir = tempfile::tempdir().unwrap();
827        let transactions_path = temp_dir.path().join(FILENAME).with_extension(EXTENSION);
828        let tx_bytes = hex!(
829            "02f87201830655c2808505ef61f08482565f94388c818ca8b9251b393131c08a736a67ccb192978801049e39c4b5b1f580c001a01764ace353514e8abdfb92446de356b260e3c1225b73fc4c8876a6258d12a129a04f02294aa61ca7676061cd99f29275491218b4754b46a0248e5e42bc5091f507"
830        );
831        let tx = PooledTransactionVariant::decode_2718(&mut &tx_bytes[..]).unwrap();
832        let provider = MockEthProvider::default().with_genesis_block();
833        let transaction = EthPooledTransaction::from_pooled(tx.try_into_recovered().unwrap());
834        let tx_to_cmp = transaction.clone();
835        let sender = address!("1f9090aaE28b8a3dCeaDf281B0F12828e676c326");
836        provider.add_account(sender, ExtendedAccount::new(42, U256::MAX));
837        let blob_store = InMemoryBlobStore::default();
838        let validator = EthTransactionValidatorBuilder::new(provider, EthEvmConfig::mainnet())
839            .set_block_gas_limit(ETHEREUM_BLOCK_GAS_LIMIT_30M)
840            .build(blob_store.clone());
841
842        let txpool = Pool::new(
843            validator,
844            CoinbaseTipOrdering::default(),
845            blob_store.clone(),
846            Default::default(),
847        );
848
849        txpool.add_transaction(TransactionOrigin::Local, transaction.clone()).await.unwrap();
850
851        let rt = Runtime::test();
852        let config = LocalTransactionBackupConfig::with_local_txs_backup(transactions_path.clone());
853        rt.spawn_critical_with_graceful_shutdown_signal("test task", |shutdown| {
854            backup_local_transactions_task(shutdown, txpool.clone(), config)
855        });
856
857        let mut txns = txpool.get_local_transactions();
858        let tx_on_finish = txns.pop().expect("there should be 1 transaction");
859
860        assert_eq!(*tx_to_cmp.hash(), *tx_on_finish.hash());
861
862        rt.graceful_shutdown();
863
864        let data = fs::read(transactions_path).unwrap();
865
866        let txs: Vec<TxBackup> = serde_json::from_slice::<Vec<TxBackup>>(&data).unwrap();
867        assert_eq!(txs.len(), 1);
868
869        temp_dir.close().unwrap();
870    }
871
872    #[tokio::test(flavor = "multi_thread")]
873    async fn deep_commit_refreshes_validator_head() {
874        // mainnet genesis has a 5,000 gas limit, which the validator picks up from the latest
875        // header
876        let provider = MockEthProvider::default().with_genesis_block();
877        let transaction = EthPooledTransaction::try_from_consensus(
878            TransactionBuilder::default()
879                .gas_limit(21_000)
880                .max_fee_per_gas(1_000_000_000)
881                .to(Address::ZERO)
882                .into_eip1559()
883                .try_into_recovered()
884                .unwrap(),
885        )
886        .unwrap();
887        provider.add_account(transaction.sender(), ExtendedAccount::new(0, U256::MAX));
888        let blob_store = InMemoryBlobStore::default();
889        let validator =
890            EthTransactionValidatorBuilder::new(provider.clone(), EthEvmConfig::mainnet())
891                .build(blob_store.clone());
892        let txpool =
893            Pool::new(validator, CoinbaseTipOrdering::default(), blob_store, Default::default());
894
895        let err = txpool
896            .add_transaction(TransactionOrigin::External, transaction.clone())
897            .await
898            .unwrap_err();
899        assert!(matches!(
900            err.kind,
901            PoolErrorKind::InvalidTransaction(InvalidPoolTransactionError::ExceedsGasLimit(
902                21_000, 5_000
903            ))
904        ));
905
906        let config = MaintainPoolConfig::default();
907        let tip = RecoveredBlock::<Block>::new_sealed(
908            SealedBlock::from_sealed_parts(
909                SealedHeader::new(
910                    Header {
911                        number: config.max_update_depth + 1,
912                        gas_limit: ETHEREUM_BLOCK_GAS_LIMIT_30M,
913                        ..Default::default()
914                    },
915                    B256::random(),
916                ),
917                Default::default(),
918            ),
919            Default::default(),
920        );
921        let commit: CanonStateNotification = CanonStateNotification::Commit {
922            new: Arc::new(Chain::new(vec![tip], Default::default(), Default::default())),
923        };
924        let maintain = maintain_transaction_pool(
925            provider,
926            txpool.clone(),
927            futures::stream::iter([commit]),
928            Runtime::test(),
929            config,
930        );
931        time::timeout(Duration::from_secs(10), maintain).await.unwrap();
932        assert_eq!(txpool.block_info().last_seen_block_number, config.max_update_depth + 1);
933
934        let hash = *transaction.hash();
935        let added = txpool.add_transaction(TransactionOrigin::External, transaction).await.unwrap();
936        assert_eq!(added.hash, hash);
937    }
938
939    #[test]
940    fn test_update_with_higher_finalized_block() {
941        let mut tracker = FinalizedBlockTracker::new(Some(10));
942        assert_eq!(tracker.update(Some(15)), Some(15));
943        assert_eq!(tracker.last_finalized_block, Some(15));
944    }
945
946    #[test]
947    fn test_update_with_lower_finalized_block() {
948        let mut tracker = FinalizedBlockTracker::new(Some(20));
949        assert_eq!(tracker.update(Some(15)), None);
950        // finalized block should NOT go backwards
951        assert_eq!(tracker.last_finalized_block, Some(20));
952    }
953
954    #[test]
955    fn test_update_with_equal_finalized_block() {
956        let mut tracker = FinalizedBlockTracker::new(Some(20));
957        assert_eq!(tracker.update(Some(20)), None);
958        assert_eq!(tracker.last_finalized_block, Some(20));
959    }
960
961    #[test]
962    fn test_update_with_no_last_finalized_block() {
963        let mut tracker = FinalizedBlockTracker::new(None);
964        assert_eq!(tracker.update(Some(10)), Some(10));
965        assert_eq!(tracker.last_finalized_block, Some(10));
966    }
967
968    #[test]
969    fn test_update_with_no_new_finalized_block() {
970        let mut tracker = FinalizedBlockTracker::new(Some(10));
971        assert_eq!(tracker.update(None), None);
972        assert_eq!(tracker.last_finalized_block, Some(10));
973    }
974
975    #[test]
976    fn test_update_with_no_finalized_blocks() {
977        let mut tracker = FinalizedBlockTracker::new(None);
978        assert_eq!(tracker.update(None), None);
979        assert_eq!(tracker.last_finalized_block, None);
980    }
981}