@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,417 @@
1
+ import { SlotNumber } from '@aztec/foundation/branded-types';
2
+ import type { L2BlockId } from '@aztec/stdlib/block';
3
+
4
+ import { type TxMetaData, type TxState, compareFee, compareTxHash } from './tx_metadata.js';
5
+
6
+ /**
7
+ * Manages in-memory indices for the transaction pool.
8
+ *
9
+ * Tracks transaction metadata and maintains several indices for efficient querying:
10
+ * - Metadata by txHash (primary store)
11
+ * - Nullifier to txHash mapping (pending txs only)
12
+ * - Fee payer to txHashes mapping (pending txs only)
13
+ * - Priority-ordered pending txs
14
+ * - Protected transaction tracking
15
+ *
16
+ * Key invariant: Only pending txs appear in nullifier/feePayer/priority indices.
17
+ */
18
+ export class TxPoolIndices {
19
+ /** Primary metadata store: txHash -> TxMetaData */
20
+ #metadata: Map<string, TxMetaData> = new Map();
21
+ /** Nullifier to txHash index (pending txs only) */
22
+ #nullifierToTxHash: Map<string, string> = new Map();
23
+ /** Fee payer to txHashes index (pending txs only) */
24
+ #feePayerToTxHashes: Map<string, Set<string>> = new Map();
25
+ /** Pending txHashes grouped by priority fee */
26
+ #pendingByPriority: Map<bigint, Set<string>> = new Map();
27
+ /** Protected transactions: txHash -> slotNumber */
28
+ #protectedTransactions: Map<string, SlotNumber> = new Map();
29
+
30
+ // ============================================================================
31
+ // STATE QUERIES
32
+ // ============================================================================
33
+
34
+ /**
35
+ * Derives the transaction state from its metadata and protection status.
36
+ * A transaction is:
37
+ * - 'mined' if it has a minedL2BlockId
38
+ * - 'protected' if it's in the protectedTransactions map (but not mined)
39
+ * - 'pending' otherwise
40
+ */
41
+ getTxState(meta: TxMetaData): TxState {
42
+ if (meta.minedL2BlockId !== undefined) {
43
+ return 'mined';
44
+ } else if (this.#protectedTransactions.has(meta.txHash)) {
45
+ return 'protected';
46
+ } else {
47
+ return 'pending';
48
+ }
49
+ }
50
+
51
+ getMetadata(txHash: string): TxMetaData | undefined {
52
+ return this.#metadata.get(txHash);
53
+ }
54
+
55
+ has(txHash: string): boolean {
56
+ return this.#metadata.has(txHash);
57
+ }
58
+
59
+ isEmpty(): boolean {
60
+ return this.#metadata.size === 0;
61
+ }
62
+
63
+ getTxCount(): number {
64
+ return this.#metadata.size;
65
+ }
66
+
67
+ // ============================================================================
68
+ // ITERATION
69
+ // ============================================================================
70
+
71
+ /**
72
+ * Iterates pending transaction hashes in priority order.
73
+ * @param order - 'desc' for highest priority first, 'asc' for lowest priority first
74
+ */
75
+ *iteratePendingByPriority(order: 'asc' | 'desc'): Generator<string> {
76
+ // Use compareFee from tx_metadata, swap args for descending order
77
+ const feeCompareFn = order === 'desc' ? (a: bigint, b: bigint) => compareFee(b, a) : compareFee;
78
+ const hashCompareFn = order === 'desc' ? (a: string, b: string) => compareTxHash(b, a) : compareTxHash;
79
+
80
+ const sortedFees = [...this.#pendingByPriority.keys()].sort(feeCompareFn);
81
+
82
+ for (const fee of sortedFees) {
83
+ const hashesAtFee = this.#pendingByPriority.get(fee)!;
84
+ // Use compareTxHash from tx_metadata, swap args for descending order
85
+ const sortedHashes = [...hashesAtFee].sort(hashCompareFn);
86
+ for (const hash of sortedHashes) {
87
+ yield hash;
88
+ }
89
+ }
90
+ }
91
+
92
+ /** Iterates all metadata entries */
93
+ *iterateMetadata(): Generator<[string, TxMetaData]> {
94
+ yield* this.#metadata;
95
+ }
96
+
97
+ // ============================================================================
98
+ // INDEX MODIFICATIONS
99
+ // ============================================================================
100
+
101
+ /** Adds a new pending transaction to all indices */
102
+ addPending(meta: TxMetaData): void {
103
+ this.#metadata.set(meta.txHash, meta);
104
+ this.#addToPendingIndices(meta);
105
+ }
106
+
107
+ /** Adds a new protected transaction (not added to pending indices) */
108
+ addProtected(meta: TxMetaData, slot: SlotNumber): void {
109
+ this.#metadata.set(meta.txHash, meta);
110
+ this.#protectedTransactions.set(meta.txHash, slot);
111
+ }
112
+
113
+ /** Adds a new mined transaction (not added to pending indices) */
114
+ addMined(meta: TxMetaData): void {
115
+ this.#metadata.set(meta.txHash, meta);
116
+ }
117
+
118
+ /** Marks an existing transaction as mined and removes from pending indices */
119
+ markAsMined(meta: TxMetaData, blockId: L2BlockId): void {
120
+ meta.minedL2BlockId = blockId;
121
+ // Safe to call unconditionally - removeFromPendingIndices is idempotent
122
+ this.#removeFromPendingIndices(meta);
123
+ }
124
+
125
+ /** Clears the mined status from a transaction */
126
+ markAsUnmined(meta: TxMetaData): void {
127
+ meta.minedL2BlockId = undefined;
128
+ }
129
+
130
+ /**
131
+ * Updates protection status for an existing transaction.
132
+ * Removes from pending indices if transitioning from pending to protected.
133
+ */
134
+ updateProtection(txHash: string, slotNumber: SlotNumber): void {
135
+ const currentSlot = this.#protectedTransactions.get(txHash);
136
+
137
+ // Only update if not already protected at an equal or later slot
138
+ if (currentSlot !== undefined && currentSlot >= slotNumber) {
139
+ return;
140
+ }
141
+
142
+ // Remove from pending indices if transitioning from pending to protected
143
+ if (currentSlot === undefined) {
144
+ const meta = this.#metadata.get(txHash);
145
+ if (meta) {
146
+ this.#removeFromPendingIndices(meta);
147
+ }
148
+ }
149
+
150
+ this.#protectedTransactions.set(txHash, slotNumber);
151
+ }
152
+
153
+ /** Sets protection for a txHash that may not have metadata yet */
154
+ setProtection(txHash: string, slotNumber: SlotNumber): void {
155
+ this.#protectedTransactions.set(txHash, slotNumber);
156
+ }
157
+
158
+ /** Gets the protection slot for a txHash, if protected */
159
+ getProtectionSlot(txHash: string): SlotNumber | undefined {
160
+ return this.#protectedTransactions.get(txHash);
161
+ }
162
+
163
+ /** Removes protection from tx hashes */
164
+ clearProtection(txHashes: string[]): void {
165
+ for (const txHash of txHashes) {
166
+ this.#protectedTransactions.delete(txHash);
167
+ }
168
+ }
169
+
170
+ /** Removes a transaction from all indices */
171
+ remove(txHash: string): void {
172
+ const meta = this.#metadata.get(txHash);
173
+ if (!meta) {
174
+ return;
175
+ }
176
+
177
+ this.#metadata.delete(txHash);
178
+ this.#protectedTransactions.delete(txHash);
179
+ this.#removeFromPendingIndices(meta);
180
+ }
181
+
182
+ /** Removes a transaction from pending indices only (not metadata) */
183
+ removeFromPendingIndices(meta: TxMetaData): void {
184
+ this.#removeFromPendingIndices(meta);
185
+ }
186
+
187
+ /** Adds a transaction to pending indices (used during conflict resolution) */
188
+ addToPendingIndices(meta: TxMetaData): void {
189
+ this.#addToPendingIndices(meta);
190
+ }
191
+
192
+ // ============================================================================
193
+ // QUERIES FOR EVICTION RULES
194
+ // ============================================================================
195
+
196
+ /** Gets all pending transactions for a given fee payer */
197
+ getFeePayerPendingTxs(feePayer: string): TxMetaData[] {
198
+ const txHashes = this.#feePayerToTxHashes.get(feePayer);
199
+ if (!txHashes) {
200
+ return [];
201
+ }
202
+ const result: TxMetaData[] = [];
203
+ for (const txHash of txHashes) {
204
+ const meta = this.#metadata.get(txHash);
205
+ if (meta && this.getTxState(meta) === 'pending') {
206
+ result.push(meta);
207
+ }
208
+ }
209
+ return result;
210
+ }
211
+
212
+ /** Gets the count of pending transactions */
213
+ getPendingTxCount(): number {
214
+ let count = 0;
215
+ for (const hashes of this.#pendingByPriority.values()) {
216
+ count += hashes.size;
217
+ }
218
+ return count;
219
+ }
220
+
221
+ /** Gets the lowest priority pending transaction hashes (up to limit) */
222
+ getLowestPriorityPending(limit: number): string[] {
223
+ if (limit <= 0) {
224
+ return [];
225
+ }
226
+
227
+ const result: string[] = [];
228
+ for (const hash of this.iteratePendingByPriority('asc')) {
229
+ result.push(hash);
230
+ if (result.length >= limit) {
231
+ break;
232
+ }
233
+ }
234
+ return result;
235
+ }
236
+
237
+ /** Gets the lowest priority pending transaction */
238
+ getLowestPriorityPendingTx(): TxMetaData | undefined {
239
+ for (const txHash of this.iteratePendingByPriority('asc')) {
240
+ const meta = this.#metadata.get(txHash);
241
+ if (meta) {
242
+ return meta;
243
+ }
244
+ }
245
+ return undefined;
246
+ }
247
+
248
+ /** Gets all pending transactions */
249
+ getPendingTxs(): TxMetaData[] {
250
+ const result: TxMetaData[] = [];
251
+ for (const hashSet of this.#pendingByPriority.values()) {
252
+ for (const txHash of hashSet) {
253
+ const meta = this.#metadata.get(txHash);
254
+ if (meta) {
255
+ result.push(meta);
256
+ }
257
+ }
258
+ }
259
+ return result;
260
+ }
261
+
262
+ /** Gets all fee payers with pending transactions */
263
+ getPendingFeePayers(): string[] {
264
+ return Array.from(this.#feePayerToTxHashes.keys());
265
+ }
266
+
267
+ /** Gets the txHash that uses a given nullifier (pending txs only) */
268
+ getTxHashByNullifier(nullifier: string): string | undefined {
269
+ return this.#nullifierToTxHash.get(nullifier);
270
+ }
271
+
272
+ /** Gets txHashes for a fee payer */
273
+ getTxHashesByFeePayer(feePayer: string): Set<string> | undefined {
274
+ return this.#feePayerToTxHashes.get(feePayer);
275
+ }
276
+
277
+ // ============================================================================
278
+ // FIND/FILTER OPERATIONS
279
+ // ============================================================================
280
+
281
+ /** Finds all transactions mined in blocks after the given block number */
282
+ findTxsMinedAfter(blockNumber: number): TxMetaData[] {
283
+ const result: TxMetaData[] = [];
284
+ for (const meta of this.#metadata.values()) {
285
+ if (meta.minedL2BlockId !== undefined && meta.minedL2BlockId.number > blockNumber) {
286
+ result.push(meta);
287
+ }
288
+ }
289
+ return result;
290
+ }
291
+
292
+ /** Finds tx hashes mined at or before the given block number */
293
+ findTxsMinedAtOrBefore(blockNumber: number): string[] {
294
+ const result: string[] = [];
295
+ for (const [txHash, meta] of this.#metadata) {
296
+ if (meta.minedL2BlockId !== undefined && meta.minedL2BlockId.number <= blockNumber) {
297
+ result.push(txHash);
298
+ }
299
+ }
300
+ return result;
301
+ }
302
+
303
+ /** Finds protected tx hashes from slots earlier than the given slot number */
304
+ findExpiredProtectedTxs(slotNumber: SlotNumber): string[] {
305
+ const result: string[] = [];
306
+ for (const [txHash, protectedSlot] of this.#protectedTransactions) {
307
+ if (protectedSlot < slotNumber) {
308
+ result.push(txHash);
309
+ }
310
+ }
311
+ return result;
312
+ }
313
+
314
+ /** Filters out transactions that are currently protected */
315
+ filterUnprotected(txs: TxMetaData[]): TxMetaData[] {
316
+ return txs.filter(meta => !this.#protectedTransactions.has(meta.txHash));
317
+ }
318
+
319
+ /** Filters to transactions that have metadata and are not mined */
320
+ filterRestorable(txHashes: string[]): TxMetaData[] {
321
+ const result: TxMetaData[] = [];
322
+ for (const txHash of txHashes) {
323
+ const meta = this.#metadata.get(txHash);
324
+ if (meta && meta.minedL2BlockId === undefined) {
325
+ result.push(meta);
326
+ }
327
+ }
328
+ return result;
329
+ }
330
+
331
+ // ============================================================================
332
+ // METRICS
333
+ // ============================================================================
334
+
335
+ /** Counts transactions by state */
336
+ countTxs(): { pending: number; protected: number; mined: number } {
337
+ let pending = 0;
338
+ let protected_ = 0;
339
+ let mined = 0;
340
+
341
+ for (const meta of this.#metadata.values()) {
342
+ const state = this.getTxState(meta);
343
+ if (state === 'pending') {
344
+ pending++;
345
+ } else if (state === 'protected') {
346
+ protected_++;
347
+ } else if (state === 'mined') {
348
+ mined++;
349
+ }
350
+ }
351
+
352
+ return { pending, protected: protected_, mined };
353
+ }
354
+
355
+ /** Gets all mined transactions with their block IDs */
356
+ getMinedTxs(): [string, L2BlockId][] {
357
+ const result: [string, L2BlockId][] = [];
358
+ for (const [txHash, meta] of this.#metadata) {
359
+ if (meta.minedL2BlockId !== undefined) {
360
+ result.push([txHash, meta.minedL2BlockId]);
361
+ }
362
+ }
363
+ return result;
364
+ }
365
+
366
+ // ============================================================================
367
+ // PRIVATE HELPERS
368
+ // ============================================================================
369
+
370
+ #addToPendingIndices(meta: TxMetaData): void {
371
+ // Add to nullifier index
372
+ for (const nullifier of meta.nullifiers) {
373
+ this.#nullifierToTxHash.set(nullifier, meta.txHash);
374
+ }
375
+
376
+ // Add to fee payer index
377
+ let feePayerSet = this.#feePayerToTxHashes.get(meta.feePayer);
378
+ if (!feePayerSet) {
379
+ feePayerSet = new Set();
380
+ this.#feePayerToTxHashes.set(meta.feePayer, feePayerSet);
381
+ }
382
+ feePayerSet.add(meta.txHash);
383
+
384
+ // Add to priority bucket
385
+ let prioritySet = this.#pendingByPriority.get(meta.priorityFee);
386
+ if (!prioritySet) {
387
+ prioritySet = new Set();
388
+ this.#pendingByPriority.set(meta.priorityFee, prioritySet);
389
+ }
390
+ prioritySet.add(meta.txHash);
391
+ }
392
+
393
+ #removeFromPendingIndices(meta: TxMetaData): void {
394
+ // Remove from nullifier index
395
+ for (const nullifier of meta.nullifiers) {
396
+ this.#nullifierToTxHash.delete(nullifier);
397
+ }
398
+
399
+ // Remove from fee payer index
400
+ const feePayerSet = this.#feePayerToTxHashes.get(meta.feePayer);
401
+ if (feePayerSet) {
402
+ feePayerSet.delete(meta.txHash);
403
+ if (feePayerSet.size === 0) {
404
+ this.#feePayerToTxHashes.delete(meta.feePayer);
405
+ }
406
+ }
407
+
408
+ // Remove from priority map
409
+ const hashSet = this.#pendingByPriority.get(meta.priorityFee);
410
+ if (hashSet) {
411
+ hashSet.delete(meta.txHash);
412
+ if (hashSet.size === 0) {
413
+ this.#pendingByPriority.delete(meta.priorityFee);
414
+ }
415
+ }
416
+ }
417
+ }
@@ -0,0 +1,212 @@
1
+ import { SlotNumber } from '@aztec/foundation/branded-types';
2
+ import { type Logger, createLogger } from '@aztec/foundation/log';
3
+ import { SerialQueue } from '@aztec/foundation/queue';
4
+ import type { TypedEventEmitter } from '@aztec/foundation/types';
5
+ import type { AztecAsyncKVStore } from '@aztec/kv-store';
6
+ import type { L2Block, L2BlockId } from '@aztec/stdlib/block';
7
+ import { BlockHeader, Tx, TxHash } from '@aztec/stdlib/tx';
8
+ import { type TelemetryClient, getTelemetryClient } from '@aztec/telemetry-client';
9
+
10
+ import EventEmitter from 'node:events';
11
+
12
+ import { PoolInstrumentation, PoolName } from '../instrumentation.js';
13
+ import type { AddTxsResult, TxPoolV2, TxPoolV2Config, TxPoolV2Dependencies, TxPoolV2Events } from './interfaces.js';
14
+ import type { TxState } from './tx_metadata.js';
15
+ import { TxPoolV2Impl } from './tx_pool_v2_impl.js';
16
+
17
+ /**
18
+ * Implementation of TxPoolV2 with explicit state management.
19
+ *
20
+ * This class is a thin wrapper that manages the serial queue and delegates
21
+ * all operations to TxPoolV2Impl.
22
+ */
23
+ export class AztecKVTxPoolV2 extends (EventEmitter as new () => TypedEventEmitter<TxPoolV2Events>) implements TxPoolV2 {
24
+ #queue: SerialQueue;
25
+ #impl: TxPoolV2Impl;
26
+ #metrics?: PoolInstrumentation<Tx>;
27
+ #store: AztecAsyncKVStore;
28
+ #telemetry: TelemetryClient;
29
+ #log: Logger;
30
+ #started = false;
31
+
32
+ constructor(
33
+ store: AztecAsyncKVStore,
34
+ archiveStore: AztecAsyncKVStore,
35
+ deps: TxPoolV2Dependencies,
36
+ telemetry: TelemetryClient = getTelemetryClient(),
37
+ config: Partial<TxPoolV2Config> = {},
38
+ log = createLogger('p2p:tx_pool_v2'),
39
+ ) {
40
+ super();
41
+
42
+ this.#store = store;
43
+ this.#telemetry = telemetry;
44
+ this.#log = log;
45
+ this.#queue = new SerialQueue();
46
+
47
+ // Create callbacks that the impl uses to notify us about events and metrics
48
+ const callbacks = {
49
+ onTxsAdded: (txs: Tx[], opts: { source?: string }) => {
50
+ this.#metrics?.transactionsAdded(txs);
51
+ this.emit('txs-added', { txs, ...opts });
52
+ },
53
+ onTxsRemoved: (txHashes: string[] | bigint[]) => {
54
+ this.#metrics?.transactionsRemoved(txHashes);
55
+ // Convert to TxHash objects for the event
56
+ const hashes = txHashes.map(h => (typeof h === 'string' ? TxHash.fromString(h) : TxHash.fromBigInt(h)));
57
+ this.emit('txs-removed', { txHashes: hashes });
58
+ },
59
+ };
60
+
61
+ // Create the implementation
62
+ this.#impl = new TxPoolV2Impl(store, archiveStore, deps, callbacks, config, log);
63
+ }
64
+
65
+ // ============================================================================
66
+ // PUBLIC API - All methods queue to the implementation
67
+ // ============================================================================
68
+
69
+ // === Core Operations ===
70
+
71
+ addPendingTxs(txs: Tx[], opts: { source?: string } = {}): Promise<AddTxsResult> {
72
+ return this.#queue.put(() => this.#impl.addPendingTxs(txs, opts));
73
+ }
74
+
75
+ canAddPendingTx(tx: Tx): Promise<'accepted' | 'ignored' | 'rejected'> {
76
+ return this.#queue.put(() => this.#impl.canAddPendingTx(tx));
77
+ }
78
+
79
+ addProtectedTxs(txs: Tx[], block: BlockHeader, opts: { source?: string } = {}): Promise<void> {
80
+ return this.#queue.put(() => this.#impl.addProtectedTxs(txs, block, opts));
81
+ }
82
+
83
+ protectTxs(txHashes: TxHash[], block: BlockHeader): Promise<TxHash[]> {
84
+ return this.#queue.put(() => Promise.resolve(this.#impl.protectTxs(txHashes, block)));
85
+ }
86
+
87
+ addMinedTxs(txs: Tx[], block: BlockHeader, opts: { source?: string } = {}): Promise<void> {
88
+ return this.#queue.put(() => this.#impl.addMinedTxs(txs, block, opts));
89
+ }
90
+
91
+ // === State Transition Handlers ===
92
+
93
+ handleMinedBlock(block: L2Block): Promise<void> {
94
+ return this.#queue.put(() => this.#impl.handleMinedBlock(block));
95
+ }
96
+
97
+ prepareForSlot(slotNumber: SlotNumber): Promise<void> {
98
+ return this.#queue.put(() => this.#impl.prepareForSlot(slotNumber));
99
+ }
100
+
101
+ handlePrunedBlocks(latestBlock: L2BlockId): Promise<void> {
102
+ return this.#queue.put(() => this.#impl.handlePrunedBlocks(latestBlock));
103
+ }
104
+
105
+ handleFailedExecution(txHashes: TxHash[]): Promise<void> {
106
+ return this.#queue.put(() => this.#impl.handleFailedExecution(txHashes));
107
+ }
108
+
109
+ handleFinalizedBlock(block: BlockHeader): Promise<void> {
110
+ return this.#queue.put(() => this.#impl.handleFinalizedBlock(block));
111
+ }
112
+
113
+ // === Queries ===
114
+
115
+ getTxByHash(txHash: TxHash): Promise<Tx | undefined> {
116
+ return this.#queue.put(() => this.#impl.getTxByHash(txHash));
117
+ }
118
+
119
+ getTxsByHash(txHashes: TxHash[]): Promise<(Tx | undefined)[]> {
120
+ return this.#queue.put(() => this.#impl.getTxsByHash(txHashes));
121
+ }
122
+
123
+ hasTxs(txHashes: TxHash[]): Promise<boolean[]> {
124
+ return this.#queue.put(() => this.#impl.hasTxs(txHashes));
125
+ }
126
+
127
+ getTxStatus(txHash: TxHash): Promise<TxState | 'deleted' | undefined> {
128
+ return this.#queue.put(() => Promise.resolve(this.#impl.getTxStatus(txHash)));
129
+ }
130
+
131
+ getPendingTxHashes(): Promise<TxHash[]> {
132
+ return this.#queue.put(() => Promise.resolve(this.#impl.getPendingTxHashes()));
133
+ }
134
+
135
+ getPendingTxCount(): Promise<number> {
136
+ return this.#queue.put(() => Promise.resolve(this.#impl.getPendingTxCount()));
137
+ }
138
+
139
+ getMinedTxHashes(): Promise<[TxHash, L2BlockId][]> {
140
+ return this.#queue.put(() => Promise.resolve(this.#impl.getMinedTxHashes()));
141
+ }
142
+
143
+ getMinedTxCount(): Promise<number> {
144
+ return this.#queue.put(() => Promise.resolve(this.#impl.getMinedTxCount()));
145
+ }
146
+
147
+ isEmpty(): Promise<boolean> {
148
+ return this.#queue.put(() => Promise.resolve(this.#impl.isEmpty()));
149
+ }
150
+
151
+ getArchivedTxByHash(txHash: TxHash): Promise<Tx | undefined> {
152
+ return this.#queue.put(() => this.#impl.getArchivedTxByHash(txHash));
153
+ }
154
+
155
+ getLowestPriorityPending(limit: number): Promise<TxHash[]> {
156
+ return this.#queue.put(() => Promise.resolve(this.#impl.getLowestPriorityPending(limit)));
157
+ }
158
+
159
+ // === Configuration ===
160
+
161
+ updateConfig(config: Partial<TxPoolV2Config>): Promise<void> {
162
+ return this.#queue.put(() => {
163
+ this.#impl.updateConfig(config);
164
+ return Promise.resolve();
165
+ });
166
+ }
167
+
168
+ // === Lifecycle ===
169
+
170
+ /**
171
+ * Starts the pool and initializes state from persistence.
172
+ */
173
+ async start(): Promise<void> {
174
+ if (this.#started) {
175
+ return;
176
+ }
177
+
178
+ this.#log.info('Starting transaction pool...');
179
+
180
+ // Start the serial queue
181
+ this.#queue.start();
182
+ this.#started = true;
183
+
184
+ // Setup metrics - created after queue is started so callbacks can safely queue
185
+ this.#metrics = new PoolInstrumentation(
186
+ this.#telemetry,
187
+ PoolName.TX_POOL,
188
+ () =>
189
+ this.#queue.put(() => {
190
+ const counts = this.#impl.countTxs();
191
+ return Promise.resolve({
192
+ itemCount: { pending: counts.pending, protected: counts.protected, mined: counts.mined },
193
+ });
194
+ }),
195
+ () => this.#store.estimateSize(),
196
+ );
197
+
198
+ // Hydrate state from persistence (runs in queue)
199
+ await this.#queue.put(() => this.#impl.hydrateFromDatabase());
200
+
201
+ this.#log.info(
202
+ `Transaction pool started with ${this.#impl.getTxCount()} transactions (${this.#impl.getPendingTxCount()} pending, ${this.#impl.getMinedTxCount()} mined)`,
203
+ );
204
+ }
205
+
206
+ async stop(): Promise<void> {
207
+ if (this.#started) {
208
+ await this.#queue.end();
209
+ this.#started = false;
210
+ }
211
+ }
212
+ }