@aztec/p2p 0.0.1-commit.e3c1de76 → 0.0.1-commit.e558bd1c

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/dest/client/factory.d.ts +3 -3
  2. package/dest/client/factory.d.ts.map +1 -1
  3. package/dest/client/factory.js +5 -3
  4. package/dest/client/interface.d.ts +9 -2
  5. package/dest/client/interface.d.ts.map +1 -1
  6. package/dest/client/p2p_client.d.ts +7 -4
  7. package/dest/client/p2p_client.d.ts.map +1 -1
  8. package/dest/client/p2p_client.js +22 -7
  9. package/dest/client/test/tx_proposal_collector/proposal_tx_collector_worker.js +1 -1
  10. package/dest/config.d.ts +9 -3
  11. package/dest/config.d.ts.map +1 -1
  12. package/dest/config.js +3 -1
  13. package/dest/mem_pools/attestation_pool/attestation_pool.d.ts +94 -87
  14. package/dest/mem_pools/attestation_pool/attestation_pool.d.ts.map +1 -1
  15. package/dest/mem_pools/attestation_pool/attestation_pool.js +411 -3
  16. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.d.ts +2 -2
  17. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.d.ts.map +1 -1
  18. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.js +351 -85
  19. package/dest/mem_pools/attestation_pool/index.d.ts +2 -3
  20. package/dest/mem_pools/attestation_pool/index.d.ts.map +1 -1
  21. package/dest/mem_pools/attestation_pool/index.js +1 -2
  22. package/dest/mem_pools/index.d.ts +2 -2
  23. package/dest/mem_pools/index.d.ts.map +1 -1
  24. package/dest/mem_pools/index.js +1 -1
  25. package/dest/mem_pools/interface.d.ts +3 -3
  26. package/dest/mem_pools/interface.d.ts.map +1 -1
  27. package/dest/mem_pools/tx_pool_v2/archive/index.d.ts +2 -0
  28. package/dest/mem_pools/tx_pool_v2/archive/index.d.ts.map +1 -0
  29. package/dest/mem_pools/tx_pool_v2/archive/index.js +1 -0
  30. package/dest/mem_pools/tx_pool_v2/archive/tx_archive.d.ts +43 -0
  31. package/dest/mem_pools/tx_pool_v2/archive/tx_archive.d.ts.map +1 -0
  32. package/dest/mem_pools/tx_pool_v2/archive/tx_archive.js +103 -0
  33. package/dest/mem_pools/tx_pool_v2/eviction/eviction_manager.d.ts +47 -0
  34. package/dest/mem_pools/tx_pool_v2/eviction/eviction_manager.d.ts.map +1 -0
  35. package/dest/mem_pools/tx_pool_v2/eviction/eviction_manager.js +119 -0
  36. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.d.ts +17 -0
  37. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.d.ts.map +1 -0
  38. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.js +90 -0
  39. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.d.ts +19 -0
  40. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.d.ts.map +1 -0
  41. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.js +89 -0
  42. package/dest/mem_pools/tx_pool_v2/eviction/index.d.ts +10 -0
  43. package/dest/mem_pools/tx_pool_v2/eviction/index.d.ts.map +1 -0
  44. package/dest/mem_pools/tx_pool_v2/eviction/index.js +11 -0
  45. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.d.ts +131 -0
  46. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.d.ts.map +1 -0
  47. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.js +17 -0
  48. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.d.ts +15 -0
  49. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.d.ts.map +1 -0
  50. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.js +63 -0
  51. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.d.ts +17 -0
  52. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.d.ts.map +1 -0
  53. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.js +91 -0
  54. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.d.ts +16 -0
  55. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.d.ts.map +1 -0
  56. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.js +70 -0
  57. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.d.ts +20 -0
  58. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.d.ts.map +1 -0
  59. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.js +63 -0
  60. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.d.ts +15 -0
  61. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.d.ts.map +1 -0
  62. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.js +19 -0
  63. package/dest/mem_pools/tx_pool_v2/index.d.ts +5 -0
  64. package/dest/mem_pools/tx_pool_v2/index.d.ts.map +1 -0
  65. package/dest/mem_pools/tx_pool_v2/index.js +4 -0
  66. package/dest/mem_pools/tx_pool_v2/interfaces.d.ts +197 -0
  67. package/dest/mem_pools/tx_pool_v2/interfaces.d.ts.map +1 -0
  68. package/dest/mem_pools/tx_pool_v2/interfaces.js +6 -0
  69. package/dest/mem_pools/tx_pool_v2/tx_metadata.d.ts +71 -0
  70. package/dest/mem_pools/tx_pool_v2/tx_metadata.d.ts.map +1 -0
  71. package/dest/mem_pools/tx_pool_v2/tx_metadata.js +95 -0
  72. package/dest/mem_pools/tx_pool_v2/tx_pool_bench_metrics.d.ts +26 -0
  73. package/dest/mem_pools/tx_pool_v2/tx_pool_bench_metrics.d.ts.map +1 -0
  74. package/dest/mem_pools/tx_pool_v2/tx_pool_bench_metrics.js +70 -0
  75. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.d.ts +99 -0
  76. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.d.ts.map +1 -0
  77. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.js +332 -0
  78. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.d.ts +55 -0
  79. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.d.ts.map +1 -0
  80. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.js +156 -0
  81. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.d.ts +69 -0
  82. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.d.ts.map +1 -0
  83. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.js +748 -0
  84. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.d.ts +3 -3
  85. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.d.ts.map +1 -1
  86. package/dest/services/dummy_service.d.ts +6 -2
  87. package/dest/services/dummy_service.d.ts.map +1 -1
  88. package/dest/services/dummy_service.js +3 -0
  89. package/dest/services/index.d.ts +2 -1
  90. package/dest/services/index.d.ts.map +1 -1
  91. package/dest/services/index.js +1 -0
  92. package/dest/services/libp2p/libp2p_service.d.ts +74 -33
  93. package/dest/services/libp2p/libp2p_service.d.ts.map +1 -1
  94. package/dest/services/libp2p/libp2p_service.js +299 -228
  95. package/dest/services/reqresp/batch-tx-requester/batch_tx_requester.d.ts +4 -4
  96. package/dest/services/reqresp/batch-tx-requester/batch_tx_requester.d.ts.map +1 -1
  97. package/dest/services/reqresp/batch-tx-requester/batch_tx_requester.js +8 -8
  98. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.d.ts +6 -4
  99. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.d.ts.map +1 -1
  100. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.js +16 -11
  101. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.d.ts +15 -10
  102. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.d.ts.map +1 -1
  103. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.js +12 -11
  104. package/dest/services/service.d.ts +18 -1
  105. package/dest/services/service.d.ts.map +1 -1
  106. package/dest/services/tx_collection/config.d.ts +3 -3
  107. package/dest/services/tx_collection/config.js +3 -3
  108. package/dest/services/tx_collection/fast_tx_collection.d.ts +4 -5
  109. package/dest/services/tx_collection/fast_tx_collection.d.ts.map +1 -1
  110. package/dest/services/tx_collection/fast_tx_collection.js +10 -14
  111. package/dest/services/tx_collection/index.d.ts +1 -1
  112. package/dest/services/tx_collection/proposal_tx_collector.d.ts +12 -12
  113. package/dest/services/tx_collection/proposal_tx_collector.d.ts.map +1 -1
  114. package/dest/services/tx_collection/proposal_tx_collector.js +4 -5
  115. package/dest/services/tx_file_store/config.d.ts +18 -0
  116. package/dest/services/tx_file_store/config.d.ts.map +1 -0
  117. package/dest/services/tx_file_store/config.js +26 -0
  118. package/dest/services/tx_file_store/index.d.ts +4 -0
  119. package/dest/services/tx_file_store/index.d.ts.map +1 -0
  120. package/dest/services/tx_file_store/index.js +3 -0
  121. package/dest/services/tx_file_store/instrumentation.d.ts +15 -0
  122. package/dest/services/tx_file_store/instrumentation.d.ts.map +1 -0
  123. package/dest/services/tx_file_store/instrumentation.js +29 -0
  124. package/dest/services/tx_file_store/tx_file_store.d.ts +47 -0
  125. package/dest/services/tx_file_store/tx_file_store.d.ts.map +1 -0
  126. package/dest/services/tx_file_store/tx_file_store.js +149 -0
  127. package/dest/test-helpers/testbench-utils.d.ts +10 -16
  128. package/dest/test-helpers/testbench-utils.d.ts.map +1 -1
  129. package/dest/test-helpers/testbench-utils.js +32 -30
  130. package/dest/testbench/p2p_client_testbench_worker.js +1 -1
  131. package/package.json +14 -14
  132. package/src/client/factory.ts +7 -4
  133. package/src/client/interface.ts +13 -1
  134. package/src/client/p2p_client.ts +30 -8
  135. package/src/client/test/tx_proposal_collector/proposal_tx_collector_worker.ts +1 -1
  136. package/src/config.ts +8 -1
  137. package/src/mem_pools/attestation_pool/attestation_pool.ts +444 -90
  138. package/src/mem_pools/attestation_pool/attestation_pool_test_suite.ts +436 -100
  139. package/src/mem_pools/attestation_pool/index.ts +9 -2
  140. package/src/mem_pools/index.ts +1 -1
  141. package/src/mem_pools/interface.ts +2 -2
  142. package/src/mem_pools/tx_pool_v2/README.md +209 -0
  143. package/src/mem_pools/tx_pool_v2/archive/index.ts +1 -0
  144. package/src/mem_pools/tx_pool_v2/archive/tx_archive.ts +120 -0
  145. package/src/mem_pools/tx_pool_v2/eviction/eviction_manager.ts +147 -0
  146. package/src/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.ts +118 -0
  147. package/src/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.ts +111 -0
  148. package/src/mem_pools/tx_pool_v2/eviction/index.ts +23 -0
  149. package/src/mem_pools/tx_pool_v2/eviction/interfaces.ts +164 -0
  150. package/src/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.ts +74 -0
  151. package/src/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.ts +101 -0
  152. package/src/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.ts +86 -0
  153. package/src/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.ts +72 -0
  154. package/src/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.ts +31 -0
  155. package/src/mem_pools/tx_pool_v2/index.ts +11 -0
  156. package/src/mem_pools/tx_pool_v2/interfaces.ts +227 -0
  157. package/src/mem_pools/tx_pool_v2/tx_metadata.ts +161 -0
  158. package/src/mem_pools/tx_pool_v2/tx_pool_bench_metrics.ts +77 -0
  159. package/src/mem_pools/tx_pool_v2/tx_pool_indices.ts +417 -0
  160. package/src/mem_pools/tx_pool_v2/tx_pool_v2.ts +212 -0
  161. package/src/mem_pools/tx_pool_v2/tx_pool_v2_impl.ts +882 -0
  162. package/src/msg_validators/attestation_validator/fisherman_attestation_validator.ts +2 -2
  163. package/src/services/dummy_service.ts +6 -0
  164. package/src/services/index.ts +1 -0
  165. package/src/services/libp2p/libp2p_service.ts +304 -230
  166. package/src/services/reqresp/batch-tx-requester/README.md +7 -7
  167. package/src/services/reqresp/batch-tx-requester/batch_tx_requester.ts +11 -11
  168. package/src/services/reqresp/protocols/block_txs/block_txs_handler.ts +22 -13
  169. package/src/services/reqresp/protocols/block_txs/block_txs_reqresp.ts +21 -15
  170. package/src/services/service.ts +20 -0
  171. package/src/services/tx_collection/config.ts +6 -6
  172. package/src/services/tx_collection/fast_tx_collection.ts +14 -24
  173. package/src/services/tx_collection/index.ts +1 -1
  174. package/src/services/tx_collection/proposal_tx_collector.ts +12 -14
  175. package/src/services/tx_file_store/config.ts +43 -0
  176. package/src/services/tx_file_store/index.ts +3 -0
  177. package/src/services/tx_file_store/instrumentation.ts +36 -0
  178. package/src/services/tx_file_store/tx_file_store.ts +173 -0
  179. package/src/test-helpers/testbench-utils.ts +18 -39
  180. package/src/testbench/p2p_client_testbench_worker.ts +1 -1
  181. package/dest/mem_pools/attestation_pool/kv_attestation_pool.d.ts +0 -40
  182. package/dest/mem_pools/attestation_pool/kv_attestation_pool.d.ts.map +0 -1
  183. package/dest/mem_pools/attestation_pool/kv_attestation_pool.js +0 -218
  184. package/dest/mem_pools/attestation_pool/memory_attestation_pool.d.ts +0 -31
  185. package/dest/mem_pools/attestation_pool/memory_attestation_pool.d.ts.map +0 -1
  186. package/dest/mem_pools/attestation_pool/memory_attestation_pool.js +0 -180
  187. package/src/mem_pools/attestation_pool/kv_attestation_pool.ts +0 -320
  188. package/src/mem_pools/attestation_pool/memory_attestation_pool.ts +0 -264
@@ -0,0 +1,111 @@
1
+ import { createLogger } from '@aztec/foundation/log';
2
+
3
+ import { type TxMetaData, comparePriority } from '../tx_metadata.js';
4
+ import type { PreAddPoolAccess, PreAddResult, PreAddRule } from './interfaces.js';
5
+
6
+ /**
7
+ * Pre-add rule that checks if a fee payer has sufficient balance to cover the incoming transaction.
8
+ *
9
+ * When an incoming tx is added:
10
+ * - Get the fee payer's on-chain balance
11
+ * - Get all existing pending txs for this fee payer
12
+ * - Insert incoming tx in priority order
13
+ * - Walk through in priority order, tracking running balance
14
+ * - If incoming tx can be covered: accept, mark lower-priority txs for eviction if needed
15
+ * - If incoming tx cannot be covered: ignore it
16
+ */
17
+ export class FeePayerBalancePreAddRule implements PreAddRule {
18
+ public readonly name = 'FeePayerBalancePreAdd';
19
+
20
+ private log = createLogger('p2p:tx_pool_v2:fee_payer_balance_pre_add_rule');
21
+
22
+ async check(incomingMeta: TxMetaData, poolAccess: PreAddPoolAccess): Promise<PreAddResult> {
23
+ // Get fee payer's on-chain balance
24
+ const initialBalance = await poolAccess.getFeePayerBalance(incomingMeta.feePayer);
25
+
26
+ // Get existing pending txs for this fee payer
27
+ const existingTxs = poolAccess.getFeePayerPendingTxs(incomingMeta.feePayer);
28
+
29
+ // Create combined list with incoming tx
30
+ const allTxs: Array<{
31
+ txHash: string;
32
+ priorityFee: bigint;
33
+ feeLimit: bigint;
34
+ claimAmount: bigint;
35
+ isIncoming: boolean;
36
+ }> = [
37
+ ...existingTxs.map(t => ({
38
+ txHash: t.txHash,
39
+ priorityFee: t.priorityFee,
40
+ feeLimit: t.feeLimit,
41
+ claimAmount: t.claimAmount,
42
+ isIncoming: false,
43
+ })),
44
+ {
45
+ txHash: incomingMeta.txHash,
46
+ priorityFee: incomingMeta.priorityFee,
47
+ feeLimit: incomingMeta.feeLimit,
48
+ claimAmount: incomingMeta.claimAmount,
49
+ isIncoming: true,
50
+ },
51
+ ];
52
+
53
+ // Sort by priority descending (highest first), with hash as tiebreaker
54
+ allTxs.sort((a, b) => comparePriority(b, a));
55
+
56
+ // Walk through in priority order, tracking balance
57
+ let balance = initialBalance;
58
+ let incomingTxCovered = false;
59
+ const txsToEvict: string[] = [];
60
+
61
+ for (const txInfo of allTxs) {
62
+ const available = balance + txInfo.claimAmount;
63
+
64
+ if (available >= txInfo.feeLimit) {
65
+ // This tx can be covered
66
+ balance = available - txInfo.feeLimit;
67
+ if (txInfo.isIncoming) {
68
+ incomingTxCovered = true;
69
+ }
70
+ } else {
71
+ // This tx cannot be covered
72
+ if (txInfo.isIncoming) {
73
+ // Incoming tx cannot be covered - ignore it
74
+ this.log.debug(
75
+ `Ignoring tx ${incomingMeta.txHash}: fee payer ${incomingMeta.feePayer} has insufficient balance`,
76
+ { balance: initialBalance, feeLimit: incomingMeta.feeLimit, claimAmount: incomingMeta.claimAmount },
77
+ );
78
+ return {
79
+ shouldIgnore: true,
80
+ txHashesToEvict: [],
81
+ reason: `fee payer ${incomingMeta.feePayer} has insufficient balance`,
82
+ };
83
+ } else {
84
+ // Existing tx cannot be covered after adding incoming - mark for eviction
85
+ txsToEvict.push(txInfo.txHash);
86
+ }
87
+ }
88
+ }
89
+
90
+ if (!incomingTxCovered) {
91
+ // This shouldn't happen if the logic above is correct, but just in case
92
+ this.log.warn(`Incoming tx ${incomingMeta.txHash} was not covered but also not ignored - this is a bug`);
93
+ return {
94
+ shouldIgnore: true,
95
+ txHashesToEvict: [],
96
+ reason: 'internal error: tx coverage not determined',
97
+ };
98
+ }
99
+
100
+ if (txsToEvict.length > 0) {
101
+ this.log.debug(
102
+ `Accepting tx ${incomingMeta.txHash}, evicting ${txsToEvict.length} lower-priority txs due to fee payer balance`,
103
+ );
104
+ }
105
+
106
+ return {
107
+ shouldIgnore: false,
108
+ txHashesToEvict: txsToEvict,
109
+ };
110
+ }
111
+ }
@@ -0,0 +1,23 @@
1
+ export { EvictionManager } from './eviction_manager.js';
2
+ export {
3
+ type EvictionConfig,
4
+ type EvictionContext,
5
+ EvictionEvent,
6
+ type EvictionResult,
7
+ type EvictionRule,
8
+ type PoolOperations,
9
+ type PreAddPoolAccess,
10
+ type PreAddResult,
11
+ type PreAddRule,
12
+ } from './interfaces.js';
13
+
14
+ // Pre-add rules
15
+ export { NullifierConflictRule } from './nullifier_conflict_rule.js';
16
+ export { FeePayerBalancePreAddRule } from './fee_payer_balance_pre_add_rule.js';
17
+ export { LowPriorityPreAddRule } from './low_priority_pre_add_rule.js';
18
+
19
+ // Post-event eviction rules
20
+ export { InvalidTxsAfterMiningRule } from './invalid_txs_after_mining_rule.js';
21
+ export { InvalidTxsAfterReorgRule } from './invalid_txs_after_reorg_rule.js';
22
+ export { FeePayerBalanceEvictionRule } from './fee_payer_balance_eviction_rule.js';
23
+ export { LowPriorityEvictionRule } from './low_priority_eviction_rule.js';
@@ -0,0 +1,164 @@
1
+ import type { BlockNumber } from '@aztec/foundation/branded-types';
2
+ import type { BlockHeader, TxHash } from '@aztec/stdlib/tx';
3
+
4
+ import type { TxMetaData } from '../tx_metadata.js';
5
+
6
+ /**
7
+ * Events that trigger eviction checks.
8
+ */
9
+ export const EvictionEvent = {
10
+ TXS_ADDED: 'txs_added',
11
+ BLOCK_MINED: 'block_mined',
12
+ CHAIN_PRUNED: 'chain_pruned',
13
+ } as const;
14
+
15
+ export type EvictionEventType = (typeof EvictionEvent)[keyof typeof EvictionEvent];
16
+
17
+ /**
18
+ * Context passed to eviction rules based on the triggering event.
19
+ */
20
+ export type EvictionContext =
21
+ | {
22
+ event: typeof EvictionEvent.TXS_ADDED;
23
+ newTxHashes: string[];
24
+ feePayers: string[];
25
+ }
26
+ | {
27
+ event: typeof EvictionEvent.CHAIN_PRUNED;
28
+ blockNumber: BlockNumber;
29
+ }
30
+ | {
31
+ event: typeof EvictionEvent.BLOCK_MINED;
32
+ block: BlockHeader;
33
+ newNullifiers: string[];
34
+ feePayers: string[];
35
+ };
36
+
37
+ /**
38
+ * Result of an eviction operation.
39
+ */
40
+ export interface EvictionResult {
41
+ readonly txsEvicted: string[];
42
+ readonly reason: string;
43
+ readonly success: boolean;
44
+ readonly error?: Error;
45
+ }
46
+
47
+ /**
48
+ * Read-only access to pool state for pre-add checks.
49
+ */
50
+ export interface PreAddPoolAccess {
51
+ /** Get metadata for a pending tx by its hash string */
52
+ getMetadata(txHashStr: string): TxMetaData | undefined;
53
+
54
+ /** Get the pending tx hash that uses a specific nullifier (as string) */
55
+ getTxHashByNullifier(nullifier: string): string | undefined;
56
+
57
+ /** Get on-chain balance for a fee payer address */
58
+ getFeePayerBalance(feePayer: string): Promise<bigint>;
59
+
60
+ /** Get metadata for all pending txs from a specific fee payer */
61
+ getFeePayerPendingTxs(feePayer: string): TxMetaData[];
62
+
63
+ /** Get current count of pending transactions */
64
+ getPendingTxCount(): number;
65
+
66
+ /** Get the lowest priority pending tx metadata */
67
+ getLowestPriorityPendingTx(): TxMetaData | undefined;
68
+ }
69
+
70
+ /**
71
+ * Result of a pre-add check for a single transaction.
72
+ */
73
+ export interface PreAddResult {
74
+ /** Whether the incoming tx should be ignored (valid but not desired) */
75
+ readonly shouldIgnore: boolean;
76
+ /** Tx hashes (as strings) that should be evicted if this tx is added */
77
+ readonly txHashesToEvict: string[];
78
+ /** Optional reason for ignoring */
79
+ readonly reason?: string;
80
+ }
81
+
82
+ /**
83
+ * Pre-add rule interface. Rules check incoming txs before they're added to the pool.
84
+ * All methods work with TxMetaData for efficiency.
85
+ */
86
+ export interface PreAddRule {
87
+ readonly name: string;
88
+
89
+ /**
90
+ * Check if incoming tx should be added and which existing txs to evict.
91
+ * @param incomingMeta - Metadata for the incoming transaction
92
+ * @param poolAccess - Read-only access to current pool state
93
+ * @returns Result indicating whether to ignore and what to evict
94
+ */
95
+ check(incomingMeta: TxMetaData, poolAccess: PreAddPoolAccess): Promise<PreAddResult>;
96
+
97
+ /**
98
+ * Updates the configuration for this rule.
99
+ */
100
+ updateConfig?(config: EvictionConfig): void;
101
+ }
102
+
103
+ /**
104
+ * Operations that post-event eviction rules can perform on the pool.
105
+ * All methods work with metadata and strings for efficiency.
106
+ */
107
+ export interface PoolOperations {
108
+ /** Get all pending tx metadata */
109
+ getPendingTxs(): TxMetaData[];
110
+
111
+ /** Get unique fee payers from pending transactions */
112
+ getPendingFeePayers(): string[];
113
+
114
+ /** Get metadata for all pending txs from a specific fee payer */
115
+ getFeePayerPendingTxs(feePayer: string): TxMetaData[];
116
+
117
+ /** Get current count of pending transactions */
118
+ getPendingTxCount(): number;
119
+
120
+ /** Get the N lowest priority pending tx hashes */
121
+ getLowestPriorityPending(limit: number): string[];
122
+
123
+ /** Delete transactions by hash */
124
+ deleteTxs(txHashes: string[]): Promise<void>;
125
+ }
126
+
127
+ /**
128
+ * Post-event eviction rule interface. Rules run after events to clean up the pool.
129
+ */
130
+ export interface EvictionRule {
131
+ readonly name: string;
132
+
133
+ /**
134
+ * Performs the eviction logic after an event.
135
+ */
136
+ evict(context: EvictionContext, pool: PoolOperations): Promise<EvictionResult>;
137
+
138
+ /**
139
+ * Updates the configuration for this rule.
140
+ */
141
+ updateConfig?(config: EvictionConfig): void;
142
+ }
143
+
144
+ /**
145
+ * Configuration options for eviction rules.
146
+ */
147
+ export interface EvictionConfig {
148
+ /** Maximum number of pending transactions (0 = unlimited) */
149
+ maxPendingTxCount?: number;
150
+ }
151
+
152
+ /**
153
+ * Converts a TxHash to its string representation for use in eviction results.
154
+ */
155
+ export function txHashToString(txHash: TxHash): string {
156
+ return txHash.toString();
157
+ }
158
+
159
+ /**
160
+ * Converts an array of TxHash to string array.
161
+ */
162
+ export function txHashesToStrings(txHashes: TxHash[]): string[] {
163
+ return txHashes.map(h => h.toString());
164
+ }
@@ -0,0 +1,74 @@
1
+ import { createLogger } from '@aztec/foundation/log';
2
+
3
+ import type { EvictionContext, EvictionResult, EvictionRule, PoolOperations } from './interfaces.js';
4
+ import { EvictionEvent } from './interfaces.js';
5
+
6
+ /**
7
+ * Eviction rule that removes invalid transactions after a block is mined.
8
+ * Only triggers on BLOCK_MINED events.
9
+ *
10
+ * Eviction criteria includes:
11
+ * - Transactions with nullifiers that are already included in the mined block
12
+ * - Transactions with an expiration timestamp less than or equal to the mined block timestamp
13
+ */
14
+ export class InvalidTxsAfterMiningRule implements EvictionRule {
15
+ public readonly name = 'InvalidTxsAfterMining';
16
+
17
+ private log = createLogger('p2p:tx_pool_v2:invalid_txs_after_mining_rule');
18
+
19
+ async evict(context: EvictionContext, pool: PoolOperations): Promise<EvictionResult> {
20
+ if (context.event !== EvictionEvent.BLOCK_MINED) {
21
+ return {
22
+ reason: 'block_mined_invalid_txs',
23
+ success: true,
24
+ txsEvicted: [],
25
+ };
26
+ }
27
+
28
+ try {
29
+ const { timestamp } = context.block.globalVariables;
30
+ const minedNullifiers = new Set(context.newNullifiers);
31
+
32
+ const txsToEvict: string[] = [];
33
+ const pendingTxs = pool.getPendingTxs();
34
+
35
+ for (const meta of pendingTxs) {
36
+ // Evict pending txs that share nullifiers with mined txs
37
+ if (meta.nullifiers.some(nullifier => minedNullifiers.has(nullifier))) {
38
+ this.log.verbose(`Evicting tx ${meta.txHash} from pool due to a duplicate nullifier with a mined tx`);
39
+ txsToEvict.push(meta.txHash);
40
+ continue;
41
+ }
42
+
43
+ // Evict pending txs with an expiration timestamp less than or equal to the mined block timestamp
44
+ if (meta.includeByTimestamp <= timestamp) {
45
+ this.log.verbose(
46
+ `Evicting tx ${meta.txHash} from pool due to the tx being expired (includeByTimestamp: ${meta.includeByTimestamp}, mined block timestamp: ${timestamp})`,
47
+ );
48
+ txsToEvict.push(meta.txHash);
49
+ continue;
50
+ }
51
+ }
52
+
53
+ if (txsToEvict.length > 0) {
54
+ await pool.deleteTxs(txsToEvict);
55
+ }
56
+
57
+ this.log.debug(`Evicted ${txsToEvict.length} invalid txs after block mined`);
58
+
59
+ return {
60
+ reason: 'block_mined_invalid_txs',
61
+ success: true,
62
+ txsEvicted: txsToEvict,
63
+ };
64
+ } catch (err) {
65
+ this.log.error('Failed to evict invalid transactions after mining', { err });
66
+ return {
67
+ reason: 'block_mined_invalid_txs',
68
+ success: false,
69
+ txsEvicted: [],
70
+ error: new Error('Failed to evict invalid txs after mining', { cause: err }),
71
+ };
72
+ }
73
+ }
74
+ }
@@ -0,0 +1,101 @@
1
+ import { Fr } from '@aztec/foundation/curves/bn254';
2
+ import { createLogger } from '@aztec/foundation/log';
3
+ import type { WorldStateSynchronizer } from '@aztec/stdlib/interfaces/server';
4
+ import { MerkleTreeId } from '@aztec/stdlib/trees';
5
+
6
+ import type { EvictionContext, EvictionResult, EvictionRule, PoolOperations } from './interfaces.js';
7
+ import { EvictionEvent } from './interfaces.js';
8
+
9
+ /**
10
+ * Eviction rule that removes invalid transactions after a blockchain reorganization.
11
+ * Only triggers on CHAIN_PRUNED events.
12
+ *
13
+ * Eviction criteria includes:
14
+ * - Transactions that reference pruned block hashes (invalid by definition)
15
+ */
16
+ export class InvalidTxsAfterReorgRule implements EvictionRule {
17
+ public readonly name = 'InvalidTxsAfterReorg';
18
+
19
+ private log = createLogger('p2p:tx_pool_v2:invalid_txs_after_reorg_rule');
20
+
21
+ constructor(private worldState: WorldStateSynchronizer) {}
22
+
23
+ async evict(context: EvictionContext, pool: PoolOperations): Promise<EvictionResult> {
24
+ if (context.event !== EvictionEvent.CHAIN_PRUNED) {
25
+ return {
26
+ reason: 'reorg_invalid_txs',
27
+ success: true,
28
+ txsEvicted: [],
29
+ };
30
+ }
31
+
32
+ try {
33
+ const pendingTxs = pool.getPendingTxs();
34
+
35
+ // Deduplicate block hashes to reduce redundant DB lookups
36
+ const uniqueBlockHashes = new Map<string, Fr>();
37
+ const txsByBlockHash = new Map<string, string[]>();
38
+
39
+ for (const meta of pendingTxs) {
40
+ const blockHashStr = meta.anchorBlockHeaderHash;
41
+ if (!txsByBlockHash.has(blockHashStr)) {
42
+ txsByBlockHash.set(blockHashStr, []);
43
+ uniqueBlockHashes.set(blockHashStr, Fr.fromHexString(blockHashStr));
44
+ }
45
+ txsByBlockHash.get(blockHashStr)!.push(meta.txHash);
46
+ }
47
+
48
+ // Ensure world state is synced to this block before accessing the snapshot
49
+ await this.worldState.syncImmediate(context.blockNumber);
50
+ const db = this.worldState.getSnapshot(context.blockNumber);
51
+
52
+ // Check which blocks exist in the archive
53
+ const blockHashArray = Array.from(uniqueBlockHashes.values());
54
+ const blocksFromDb = await db.findLeafIndices(MerkleTreeId.ARCHIVE, blockHashArray);
55
+
56
+ // Build set of pruned block hashes
57
+ const prunedBlockHashes = new Set<string>();
58
+ let i = 0;
59
+ for (const [blockHashStr] of uniqueBlockHashes) {
60
+ if (blocksFromDb[i] === undefined) {
61
+ prunedBlockHashes.add(blockHashStr);
62
+ }
63
+ i++;
64
+ }
65
+
66
+ // Identify txs whose anchor block was pruned
67
+ const txsToEvict: string[] = [];
68
+ for (const [blockHashStr, txHashes] of txsByBlockHash) {
69
+ if (prunedBlockHashes.has(blockHashStr)) {
70
+ txsToEvict.push(...txHashes);
71
+ }
72
+ }
73
+
74
+ if (txsToEvict.length > 0) {
75
+ this.log.verbose(`Evicting ${txsToEvict.length} txs from pool due to referencing pruned blocks`);
76
+ await pool.deleteTxs(txsToEvict);
77
+ }
78
+
79
+ const keptCount = pendingTxs.length - txsToEvict.length;
80
+ if (keptCount > 0) {
81
+ this.log.verbose(`Kept ${keptCount} txs that did not reference pruned blocks`);
82
+ }
83
+
84
+ this.log.debug(`Evicted ${txsToEvict.length} invalid txs after reorg`);
85
+
86
+ return {
87
+ reason: 'reorg_invalid_txs',
88
+ success: true,
89
+ txsEvicted: txsToEvict,
90
+ };
91
+ } catch (err) {
92
+ this.log.error('Failed to evict invalid transactions after reorg', { err });
93
+ return {
94
+ reason: 'reorg_invalid_txs',
95
+ success: false,
96
+ txsEvicted: [],
97
+ error: new Error('Failed to evict invalid txs after reorg', { cause: err }),
98
+ };
99
+ }
100
+ }
101
+ }
@@ -0,0 +1,86 @@
1
+ import { createLogger } from '@aztec/foundation/log';
2
+
3
+ import type { EvictionConfig, EvictionContext, EvictionResult, EvictionRule, PoolOperations } from './interfaces.js';
4
+ import { EvictionEvent } from './interfaces.js';
5
+
6
+ /**
7
+ * Eviction rule that removes low-priority transactions when the pool exceeds configured limits.
8
+ * Only triggers on TXS_ADDED events.
9
+ */
10
+ export class LowPriorityEvictionRule implements EvictionRule {
11
+ public readonly name = 'LowPriorityEviction';
12
+
13
+ private log = createLogger('p2p:tx_pool_v2:low_priority_eviction_rule');
14
+ private maxPoolSize: number;
15
+
16
+ constructor(config: { maxPoolSize: number }) {
17
+ this.maxPoolSize = config.maxPoolSize;
18
+ }
19
+
20
+ async evict(context: EvictionContext, pool: PoolOperations): Promise<EvictionResult> {
21
+ if (context.event !== EvictionEvent.TXS_ADDED) {
22
+ return {
23
+ reason: 'low_priority',
24
+ success: true,
25
+ txsEvicted: [],
26
+ };
27
+ }
28
+
29
+ if (this.maxPoolSize === 0) {
30
+ return {
31
+ reason: 'low_priority',
32
+ success: true,
33
+ txsEvicted: [],
34
+ };
35
+ }
36
+
37
+ try {
38
+ const currentTxCount = pool.getPendingTxCount();
39
+
40
+ if (currentTxCount <= this.maxPoolSize) {
41
+ this.log.trace(
42
+ `Not evicting low priority txs. Pending tx count below limit ${currentTxCount} <= ${this.maxPoolSize}`,
43
+ );
44
+ return {
45
+ reason: 'low_priority',
46
+ success: true,
47
+ txsEvicted: [],
48
+ };
49
+ }
50
+
51
+ this.log.verbose(
52
+ `Evicting low priority txs. Pending tx count above limit: ${currentTxCount} > ${this.maxPoolSize}`,
53
+ );
54
+ const numberToEvict = currentTxCount - this.maxPoolSize;
55
+ const txsToEvict = pool.getLowestPriorityPending(numberToEvict);
56
+
57
+ if (txsToEvict.length > 0) {
58
+ await pool.deleteTxs(txsToEvict);
59
+ }
60
+
61
+ const numNewTxsEvicted = context.newTxHashes.filter(newTxHash => txsToEvict.includes(newTxHash)).length;
62
+
63
+ this.log.verbose(`Evicted ${txsToEvict.length} low priority txs, including ${numNewTxsEvicted} newly added txs`);
64
+
65
+ return {
66
+ reason: 'low_priority',
67
+ success: true,
68
+ txsEvicted: txsToEvict,
69
+ };
70
+ } catch (err) {
71
+ this.log.error('Failed to evict low priority transactions', { err });
72
+ return {
73
+ reason: 'low_priority',
74
+ success: false,
75
+ txsEvicted: [],
76
+ error: new Error('Failed to evict low priority txs', { cause: err }),
77
+ };
78
+ }
79
+ }
80
+
81
+ updateConfig(config: EvictionConfig): void {
82
+ if (config.maxPendingTxCount !== undefined) {
83
+ this.maxPoolSize = config.maxPendingTxCount;
84
+ }
85
+ }
86
+ }
@@ -0,0 +1,72 @@
1
+ import { createLogger } from '@aztec/foundation/log';
2
+
3
+ import type { TxMetaData } from '../tx_metadata.js';
4
+ import type { EvictionConfig, PreAddPoolAccess, PreAddResult, PreAddRule } from './interfaces.js';
5
+
6
+ /**
7
+ * Pre-add rule that checks if the pool is at capacity and handles low-priority eviction.
8
+ *
9
+ * When the pool is at capacity:
10
+ * - If incoming tx has higher priority than the lowest priority tx, evict the lowest and accept incoming
11
+ * - If incoming tx has equal or lower priority than the lowest, ignore incoming (it would be evicted anyway)
12
+ */
13
+ export class LowPriorityPreAddRule implements PreAddRule {
14
+ public readonly name = 'LowPriorityPreAdd';
15
+
16
+ private log = createLogger('p2p:tx_pool_v2:low_priority_pre_add_rule');
17
+ private maxPoolSize: number;
18
+
19
+ constructor(config: { maxPoolSize: number }) {
20
+ this.maxPoolSize = config.maxPoolSize;
21
+ }
22
+
23
+ check(incomingMeta: TxMetaData, poolAccess: PreAddPoolAccess): Promise<PreAddResult> {
24
+ // Skip if max pool size is disabled (0 = unlimited)
25
+ if (this.maxPoolSize === 0) {
26
+ return Promise.resolve({ shouldIgnore: false, txHashesToEvict: [] });
27
+ }
28
+
29
+ const currentCount = poolAccess.getPendingTxCount();
30
+
31
+ // If pool is not at capacity, accept the tx
32
+ if (currentCount < this.maxPoolSize) {
33
+ return Promise.resolve({ shouldIgnore: false, txHashesToEvict: [] });
34
+ }
35
+
36
+ // Pool is at capacity - need to compare priorities
37
+ const lowestPriorityMeta = poolAccess.getLowestPriorityPendingTx();
38
+ if (!lowestPriorityMeta) {
39
+ // No pending txs (shouldn't happen if count > 0, but handle gracefully)
40
+ return Promise.resolve({ shouldIgnore: false, txHashesToEvict: [] });
41
+ }
42
+
43
+ // If incoming tx has strictly higher priority, evict the lowest priority tx
44
+ if (incomingMeta.priorityFee > lowestPriorityMeta.priorityFee) {
45
+ this.log.debug(
46
+ `Pool at capacity (${currentCount}/${this.maxPoolSize}), evicting ${lowestPriorityMeta.txHash} ` +
47
+ `(priority ${lowestPriorityMeta.priorityFee}) for ${incomingMeta.txHash} (priority ${incomingMeta.priorityFee})`,
48
+ );
49
+ return Promise.resolve({
50
+ shouldIgnore: false,
51
+ txHashesToEvict: [lowestPriorityMeta.txHash],
52
+ });
53
+ }
54
+
55
+ // Incoming tx has equal or lower priority - ignore it (it would be evicted anyway)
56
+ this.log.debug(
57
+ `Pool at capacity (${currentCount}/${this.maxPoolSize}), ignoring ${incomingMeta.txHash} ` +
58
+ `(priority ${incomingMeta.priorityFee}) - lower than existing minimum (priority ${lowestPriorityMeta.priorityFee})`,
59
+ );
60
+ return Promise.resolve({
61
+ shouldIgnore: true,
62
+ txHashesToEvict: [],
63
+ reason: `pool at capacity and tx has lower priority than existing transactions`,
64
+ });
65
+ }
66
+
67
+ updateConfig(config: EvictionConfig): void {
68
+ if (config.maxPendingTxCount !== undefined) {
69
+ this.maxPoolSize = config.maxPendingTxCount;
70
+ }
71
+ }
72
+ }
@@ -0,0 +1,31 @@
1
+ import { createLogger } from '@aztec/foundation/log';
2
+
3
+ import { type TxMetaData, checkNullifierConflict } from '../tx_metadata.js';
4
+ import type { PreAddPoolAccess, PreAddResult, PreAddRule } from './interfaces.js';
5
+
6
+ /**
7
+ * Pre-add rule that checks for nullifier conflicts between incoming and existing transactions.
8
+ *
9
+ * When an incoming tx shares nullifiers with existing pending txs:
10
+ * - If the incoming tx has strictly higher priority, evict all conflicting txs
11
+ * - If any conflicting tx has equal or higher priority, ignore the incoming tx
12
+ */
13
+ export class NullifierConflictRule implements PreAddRule {
14
+ public readonly name = 'NullifierConflict';
15
+
16
+ private log = createLogger('p2p:tx_pool_v2:nullifier_conflict_rule');
17
+
18
+ check(incomingMeta: TxMetaData, poolAccess: PreAddPoolAccess): Promise<PreAddResult> {
19
+ const result = checkNullifierConflict(
20
+ incomingMeta,
21
+ nullifier => poolAccess.getTxHashByNullifier(nullifier),
22
+ txHash => poolAccess.getMetadata(txHash),
23
+ );
24
+
25
+ if (result.shouldIgnore) {
26
+ this.log.debug(`Ignoring tx ${incomingMeta.txHash}: ${result.reason}`);
27
+ }
28
+
29
+ return Promise.resolve(result);
30
+ }
31
+ }
@@ -0,0 +1,11 @@
1
+ export { AztecKVTxPoolV2 } from './tx_pool_v2.js';
2
+ export {
3
+ type TxPoolV2,
4
+ type TxPoolV2Config,
5
+ type TxPoolV2Events,
6
+ type AddTxsResult,
7
+ type PoolReadAccess,
8
+ DEFAULT_TX_POOL_V2_CONFIG,
9
+ } from './interfaces.js';
10
+ export { type TxMetaData, type TxState, buildTxMetaData, comparePriority } from './tx_metadata.js';
11
+ export { TxArchive } from './archive/index.js';