@aztec/p2p 0.0.1-commit.8afd444 → 0.0.1-commit.8f9871590

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 (277) hide show
  1. package/dest/client/factory.d.ts +5 -5
  2. package/dest/client/factory.d.ts.map +1 -1
  3. package/dest/client/factory.js +44 -10
  4. package/dest/client/interface.d.ts +37 -15
  5. package/dest/client/interface.d.ts.map +1 -1
  6. package/dest/client/p2p_client.d.ts +35 -36
  7. package/dest/client/p2p_client.d.ts.map +1 -1
  8. package/dest/client/p2p_client.js +114 -138
  9. package/dest/client/test/tx_proposal_collector/proposal_tx_collector_worker.js +1 -1
  10. package/dest/config.d.ts +23 -5
  11. package/dest/config.d.ts.map +1 -1
  12. package/dest/config.js +16 -1
  13. package/dest/index.d.ts +2 -1
  14. package/dest/index.d.ts.map +1 -1
  15. package/dest/index.js +1 -0
  16. package/dest/mem_pools/attestation_pool/attestation_pool.d.ts +104 -88
  17. package/dest/mem_pools/attestation_pool/attestation_pool.d.ts.map +1 -1
  18. package/dest/mem_pools/attestation_pool/attestation_pool.js +441 -3
  19. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.d.ts +2 -2
  20. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.d.ts.map +1 -1
  21. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.js +353 -87
  22. package/dest/mem_pools/attestation_pool/index.d.ts +2 -3
  23. package/dest/mem_pools/attestation_pool/index.d.ts.map +1 -1
  24. package/dest/mem_pools/attestation_pool/index.js +1 -2
  25. package/dest/mem_pools/attestation_pool/mocks.d.ts +2 -2
  26. package/dest/mem_pools/attestation_pool/mocks.d.ts.map +1 -1
  27. package/dest/mem_pools/attestation_pool/mocks.js +2 -2
  28. package/dest/mem_pools/index.d.ts +3 -2
  29. package/dest/mem_pools/index.d.ts.map +1 -1
  30. package/dest/mem_pools/index.js +1 -1
  31. package/dest/mem_pools/interface.d.ts +5 -5
  32. package/dest/mem_pools/interface.d.ts.map +1 -1
  33. package/dest/mem_pools/tx_pool/eviction/invalid_txs_after_mining_rule.js +3 -3
  34. package/dest/mem_pools/tx_pool_v2/archive/index.d.ts +2 -0
  35. package/dest/mem_pools/tx_pool_v2/archive/index.d.ts.map +1 -0
  36. package/dest/mem_pools/tx_pool_v2/archive/index.js +1 -0
  37. package/dest/mem_pools/tx_pool_v2/archive/tx_archive.d.ts +43 -0
  38. package/dest/mem_pools/tx_pool_v2/archive/tx_archive.d.ts.map +1 -0
  39. package/dest/mem_pools/tx_pool_v2/archive/tx_archive.js +103 -0
  40. package/dest/mem_pools/tx_pool_v2/deleted_pool.d.ts +102 -0
  41. package/dest/mem_pools/tx_pool_v2/deleted_pool.d.ts.map +1 -0
  42. package/dest/mem_pools/tx_pool_v2/deleted_pool.js +242 -0
  43. package/dest/mem_pools/tx_pool_v2/eviction/eviction_manager.d.ts +47 -0
  44. package/dest/mem_pools/tx_pool_v2/eviction/eviction_manager.d.ts.map +1 -0
  45. package/dest/mem_pools/tx_pool_v2/eviction/eviction_manager.js +119 -0
  46. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.d.ts +17 -0
  47. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.d.ts.map +1 -0
  48. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.js +93 -0
  49. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.d.ts +19 -0
  50. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.d.ts.map +1 -0
  51. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.js +89 -0
  52. package/dest/mem_pools/tx_pool_v2/eviction/index.d.ts +10 -0
  53. package/dest/mem_pools/tx_pool_v2/eviction/index.d.ts.map +1 -0
  54. package/dest/mem_pools/tx_pool_v2/eviction/index.js +11 -0
  55. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.d.ts +131 -0
  56. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.d.ts.map +1 -0
  57. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.js +17 -0
  58. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.d.ts +15 -0
  59. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.d.ts.map +1 -0
  60. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.js +65 -0
  61. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.d.ts +17 -0
  62. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.d.ts.map +1 -0
  63. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.js +93 -0
  64. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.d.ts +16 -0
  65. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.d.ts.map +1 -0
  66. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.js +72 -0
  67. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.d.ts +20 -0
  68. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.d.ts.map +1 -0
  69. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.js +63 -0
  70. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.d.ts +15 -0
  71. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.d.ts.map +1 -0
  72. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.js +19 -0
  73. package/dest/mem_pools/tx_pool_v2/index.d.ts +6 -0
  74. package/dest/mem_pools/tx_pool_v2/index.d.ts.map +1 -0
  75. package/dest/mem_pools/tx_pool_v2/index.js +5 -0
  76. package/dest/mem_pools/tx_pool_v2/interfaces.d.ts +201 -0
  77. package/dest/mem_pools/tx_pool_v2/interfaces.d.ts.map +1 -0
  78. package/dest/mem_pools/tx_pool_v2/interfaces.js +7 -0
  79. package/dest/mem_pools/tx_pool_v2/tx_metadata.d.ts +95 -0
  80. package/dest/mem_pools/tx_pool_v2/tx_metadata.d.ts.map +1 -0
  81. package/dest/mem_pools/tx_pool_v2/tx_metadata.js +128 -0
  82. package/dest/mem_pools/tx_pool_v2/tx_pool_bench_metrics.d.ts +26 -0
  83. package/dest/mem_pools/tx_pool_v2/tx_pool_bench_metrics.d.ts.map +1 -0
  84. package/dest/mem_pools/tx_pool_v2/tx_pool_bench_metrics.js +70 -0
  85. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.d.ts +105 -0
  86. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.d.ts.map +1 -0
  87. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.js +345 -0
  88. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.d.ts +57 -0
  89. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.d.ts.map +1 -0
  90. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.js +160 -0
  91. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.d.ts +71 -0
  92. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.d.ts.map +1 -0
  93. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.js +780 -0
  94. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.d.ts +3 -3
  95. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.d.ts.map +1 -1
  96. package/dest/msg_validators/tx_validator/aggregate_tx_validator.d.ts +3 -3
  97. package/dest/msg_validators/tx_validator/aggregate_tx_validator.d.ts.map +1 -1
  98. package/dest/msg_validators/tx_validator/block_header_validator.d.ts +16 -3
  99. package/dest/msg_validators/tx_validator/block_header_validator.d.ts.map +1 -1
  100. package/dest/msg_validators/tx_validator/block_header_validator.js +1 -1
  101. package/dest/msg_validators/tx_validator/double_spend_validator.d.ts +13 -3
  102. package/dest/msg_validators/tx_validator/double_spend_validator.d.ts.map +1 -1
  103. package/dest/msg_validators/tx_validator/double_spend_validator.js +4 -4
  104. package/dest/msg_validators/tx_validator/timestamp_validator.d.ts +20 -4
  105. package/dest/msg_validators/tx_validator/timestamp_validator.d.ts.map +1 -1
  106. package/dest/msg_validators/tx_validator/timestamp_validator.js +6 -6
  107. package/dest/services/dummy_service.d.ts +10 -2
  108. package/dest/services/dummy_service.d.ts.map +1 -1
  109. package/dest/services/dummy_service.js +6 -0
  110. package/dest/services/encoding.d.ts +2 -2
  111. package/dest/services/encoding.d.ts.map +1 -1
  112. package/dest/services/encoding.js +2 -2
  113. package/dest/services/gossipsub/index.d.ts +3 -0
  114. package/dest/services/gossipsub/index.d.ts.map +1 -0
  115. package/dest/services/gossipsub/index.js +2 -0
  116. package/dest/services/gossipsub/scoring.d.ts +21 -3
  117. package/dest/services/gossipsub/scoring.d.ts.map +1 -1
  118. package/dest/services/gossipsub/scoring.js +24 -7
  119. package/dest/services/gossipsub/topic_score_params.d.ts +161 -0
  120. package/dest/services/gossipsub/topic_score_params.d.ts.map +1 -0
  121. package/dest/services/gossipsub/topic_score_params.js +324 -0
  122. package/dest/services/libp2p/libp2p_service.d.ts +84 -35
  123. package/dest/services/libp2p/libp2p_service.d.ts.map +1 -1
  124. package/dest/services/libp2p/libp2p_service.js +370 -275
  125. package/dest/services/peer-manager/peer_scoring.d.ts +1 -1
  126. package/dest/services/peer-manager/peer_scoring.d.ts.map +1 -1
  127. package/dest/services/peer-manager/peer_scoring.js +25 -2
  128. package/dest/services/reqresp/batch-tx-requester/batch_tx_requester.d.ts +4 -4
  129. package/dest/services/reqresp/batch-tx-requester/batch_tx_requester.d.ts.map +1 -1
  130. package/dest/services/reqresp/batch-tx-requester/batch_tx_requester.js +8 -8
  131. package/dest/services/reqresp/interface.d.ts +10 -1
  132. package/dest/services/reqresp/interface.d.ts.map +1 -1
  133. package/dest/services/reqresp/interface.js +15 -1
  134. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.d.ts +7 -5
  135. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.d.ts.map +1 -1
  136. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.js +16 -11
  137. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.d.ts +21 -10
  138. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.d.ts.map +1 -1
  139. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.js +27 -11
  140. package/dest/services/reqresp/protocols/tx.d.ts +7 -1
  141. package/dest/services/reqresp/protocols/tx.d.ts.map +1 -1
  142. package/dest/services/reqresp/protocols/tx.js +20 -0
  143. package/dest/services/reqresp/reqresp.d.ts +1 -1
  144. package/dest/services/reqresp/reqresp.d.ts.map +1 -1
  145. package/dest/services/reqresp/reqresp.js +11 -4
  146. package/dest/services/service.d.ts +35 -1
  147. package/dest/services/service.d.ts.map +1 -1
  148. package/dest/services/tx_collection/config.d.ts +22 -4
  149. package/dest/services/tx_collection/config.d.ts.map +1 -1
  150. package/dest/services/tx_collection/config.js +49 -3
  151. package/dest/services/tx_collection/fast_tx_collection.d.ts +6 -5
  152. package/dest/services/tx_collection/fast_tx_collection.d.ts.map +1 -1
  153. package/dest/services/tx_collection/fast_tx_collection.js +27 -17
  154. package/dest/services/tx_collection/file_store_tx_collection.d.ts +53 -0
  155. package/dest/services/tx_collection/file_store_tx_collection.d.ts.map +1 -0
  156. package/dest/services/tx_collection/file_store_tx_collection.js +165 -0
  157. package/dest/services/tx_collection/file_store_tx_source.d.ts +28 -0
  158. package/dest/services/tx_collection/file_store_tx_source.d.ts.map +1 -0
  159. package/dest/services/tx_collection/file_store_tx_source.js +59 -0
  160. package/dest/services/tx_collection/index.d.ts +3 -2
  161. package/dest/services/tx_collection/index.d.ts.map +1 -1
  162. package/dest/services/tx_collection/index.js +1 -0
  163. package/dest/services/tx_collection/proposal_tx_collector.d.ts +12 -12
  164. package/dest/services/tx_collection/proposal_tx_collector.d.ts.map +1 -1
  165. package/dest/services/tx_collection/proposal_tx_collector.js +4 -5
  166. package/dest/services/tx_collection/slow_tx_collection.d.ts +6 -2
  167. package/dest/services/tx_collection/slow_tx_collection.d.ts.map +1 -1
  168. package/dest/services/tx_collection/slow_tx_collection.js +55 -23
  169. package/dest/services/tx_collection/tx_collection.d.ts +19 -7
  170. package/dest/services/tx_collection/tx_collection.d.ts.map +1 -1
  171. package/dest/services/tx_collection/tx_collection.js +75 -3
  172. package/dest/services/tx_collection/tx_collection_sink.d.ts +15 -6
  173. package/dest/services/tx_collection/tx_collection_sink.d.ts.map +1 -1
  174. package/dest/services/tx_collection/tx_collection_sink.js +13 -7
  175. package/dest/services/tx_file_store/config.d.ts +1 -3
  176. package/dest/services/tx_file_store/config.d.ts.map +1 -1
  177. package/dest/services/tx_file_store/config.js +0 -4
  178. package/dest/services/tx_file_store/tx_file_store.d.ts +4 -3
  179. package/dest/services/tx_file_store/tx_file_store.d.ts.map +1 -1
  180. package/dest/services/tx_file_store/tx_file_store.js +8 -5
  181. package/dest/services/tx_provider.d.ts +3 -3
  182. package/dest/services/tx_provider.d.ts.map +1 -1
  183. package/dest/services/tx_provider.js +5 -4
  184. package/dest/test-helpers/make-test-p2p-clients.d.ts +3 -3
  185. package/dest/test-helpers/make-test-p2p-clients.d.ts.map +1 -1
  186. package/dest/test-helpers/mock-pubsub.d.ts +27 -1
  187. package/dest/test-helpers/mock-pubsub.d.ts.map +1 -1
  188. package/dest/test-helpers/mock-pubsub.js +97 -2
  189. package/dest/test-helpers/reqresp-nodes.d.ts +1 -1
  190. package/dest/test-helpers/reqresp-nodes.d.ts.map +1 -1
  191. package/dest/test-helpers/reqresp-nodes.js +2 -1
  192. package/dest/test-helpers/testbench-utils.d.ts +40 -38
  193. package/dest/test-helpers/testbench-utils.d.ts.map +1 -1
  194. package/dest/test-helpers/testbench-utils.js +128 -59
  195. package/dest/testbench/p2p_client_testbench_worker.js +4 -4
  196. package/package.json +14 -14
  197. package/src/client/factory.ts +81 -13
  198. package/src/client/interface.ts +45 -14
  199. package/src/client/p2p_client.ts +151 -161
  200. package/src/client/test/tx_proposal_collector/proposal_tx_collector_worker.ts +1 -1
  201. package/src/config.ts +34 -2
  202. package/src/index.ts +1 -0
  203. package/src/mem_pools/attestation_pool/attestation_pool.ts +496 -91
  204. package/src/mem_pools/attestation_pool/attestation_pool_test_suite.ts +442 -102
  205. package/src/mem_pools/attestation_pool/index.ts +9 -2
  206. package/src/mem_pools/attestation_pool/mocks.ts +2 -1
  207. package/src/mem_pools/index.ts +4 -1
  208. package/src/mem_pools/interface.ts +4 -4
  209. package/src/mem_pools/tx_pool/README.md +1 -1
  210. package/src/mem_pools/tx_pool/eviction/invalid_txs_after_mining_rule.ts +3 -3
  211. package/src/mem_pools/tx_pool_v2/README.md +275 -0
  212. package/src/mem_pools/tx_pool_v2/archive/index.ts +1 -0
  213. package/src/mem_pools/tx_pool_v2/archive/tx_archive.ts +120 -0
  214. package/src/mem_pools/tx_pool_v2/deleted_pool.ts +310 -0
  215. package/src/mem_pools/tx_pool_v2/eviction/eviction_manager.ts +147 -0
  216. package/src/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.ts +121 -0
  217. package/src/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.ts +111 -0
  218. package/src/mem_pools/tx_pool_v2/eviction/index.ts +23 -0
  219. package/src/mem_pools/tx_pool_v2/eviction/interfaces.ts +164 -0
  220. package/src/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.ts +74 -0
  221. package/src/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.ts +101 -0
  222. package/src/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.ts +88 -0
  223. package/src/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.ts +72 -0
  224. package/src/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.ts +31 -0
  225. package/src/mem_pools/tx_pool_v2/index.ts +12 -0
  226. package/src/mem_pools/tx_pool_v2/interfaces.ts +233 -0
  227. package/src/mem_pools/tx_pool_v2/tx_metadata.ts +211 -0
  228. package/src/mem_pools/tx_pool_v2/tx_pool_bench_metrics.ts +77 -0
  229. package/src/mem_pools/tx_pool_v2/tx_pool_indices.ts +433 -0
  230. package/src/mem_pools/tx_pool_v2/tx_pool_v2.ts +218 -0
  231. package/src/mem_pools/tx_pool_v2/tx_pool_v2_impl.ts +924 -0
  232. package/src/msg_validators/attestation_validator/fisherman_attestation_validator.ts +2 -2
  233. package/src/msg_validators/tx_validator/aggregate_tx_validator.ts +2 -2
  234. package/src/msg_validators/tx_validator/block_header_validator.ts +15 -3
  235. package/src/msg_validators/tx_validator/double_spend_validator.ts +11 -6
  236. package/src/msg_validators/tx_validator/timestamp_validator.ts +23 -18
  237. package/src/services/dummy_service.ts +12 -0
  238. package/src/services/encoding.ts +2 -2
  239. package/src/services/gossipsub/README.md +626 -0
  240. package/src/services/gossipsub/index.ts +2 -0
  241. package/src/services/gossipsub/scoring.ts +29 -5
  242. package/src/services/gossipsub/topic_score_params.ts +451 -0
  243. package/src/services/libp2p/libp2p_service.ts +372 -277
  244. package/src/services/peer-manager/peer_scoring.ts +25 -0
  245. package/src/services/reqresp/batch-tx-requester/README.md +7 -7
  246. package/src/services/reqresp/batch-tx-requester/batch_tx_requester.ts +11 -11
  247. package/src/services/reqresp/interface.ts +26 -1
  248. package/src/services/reqresp/protocols/block_txs/block_txs_handler.ts +23 -14
  249. package/src/services/reqresp/protocols/block_txs/block_txs_reqresp.ts +38 -15
  250. package/src/services/reqresp/protocols/tx.ts +22 -0
  251. package/src/services/reqresp/reqresp.ts +13 -3
  252. package/src/services/service.ts +40 -0
  253. package/src/services/tx_collection/config.ts +74 -6
  254. package/src/services/tx_collection/fast_tx_collection.ts +28 -26
  255. package/src/services/tx_collection/file_store_tx_collection.ts +198 -0
  256. package/src/services/tx_collection/file_store_tx_source.ts +73 -0
  257. package/src/services/tx_collection/index.ts +2 -1
  258. package/src/services/tx_collection/proposal_tx_collector.ts +12 -14
  259. package/src/services/tx_collection/slow_tx_collection.ts +64 -30
  260. package/src/services/tx_collection/tx_collection.ts +109 -13
  261. package/src/services/tx_collection/tx_collection_sink.ts +17 -7
  262. package/src/services/tx_file_store/config.ts +0 -6
  263. package/src/services/tx_file_store/tx_file_store.ts +9 -7
  264. package/src/services/tx_provider.ts +8 -7
  265. package/src/test-helpers/make-test-p2p-clients.ts +3 -3
  266. package/src/test-helpers/mock-pubsub.ts +133 -3
  267. package/src/test-helpers/reqresp-nodes.ts +2 -1
  268. package/src/test-helpers/testbench-utils.ts +127 -71
  269. package/src/testbench/p2p_client_testbench_worker.ts +4 -4
  270. package/dest/mem_pools/attestation_pool/kv_attestation_pool.d.ts +0 -40
  271. package/dest/mem_pools/attestation_pool/kv_attestation_pool.d.ts.map +0 -1
  272. package/dest/mem_pools/attestation_pool/kv_attestation_pool.js +0 -218
  273. package/dest/mem_pools/attestation_pool/memory_attestation_pool.d.ts +0 -31
  274. package/dest/mem_pools/attestation_pool/memory_attestation_pool.d.ts.map +0 -1
  275. package/dest/mem_pools/attestation_pool/memory_attestation_pool.js +0 -180
  276. package/src/mem_pools/attestation_pool/kv_attestation_pool.ts +0 -320
  277. package/src/mem_pools/attestation_pool/memory_attestation_pool.ts +0 -264
@@ -0,0 +1,924 @@
1
+ import { BlockNumber, SlotNumber } from '@aztec/foundation/branded-types';
2
+ import type { Logger } from '@aztec/foundation/log';
3
+ import type { DateProvider } from '@aztec/foundation/timer';
4
+ import type { AztecAsyncKVStore, AztecAsyncMap } from '@aztec/kv-store';
5
+ import { ProtocolContractAddress } from '@aztec/protocol-contracts';
6
+ import { computeFeePayerBalanceStorageSlot } from '@aztec/protocol-contracts/fee-juice';
7
+ import { AztecAddress } from '@aztec/stdlib/aztec-address';
8
+ import type { L2Block, L2BlockId, L2BlockSource } from '@aztec/stdlib/block';
9
+ import type { WorldStateSynchronizer } from '@aztec/stdlib/interfaces/server';
10
+ import { DatabasePublicStateSource } from '@aztec/stdlib/trees';
11
+ import { BlockHeader, Tx, TxHash, type TxValidator } from '@aztec/stdlib/tx';
12
+
13
+ import { TxArchive } from './archive/index.js';
14
+ import { DeletedPool } from './deleted_pool.js';
15
+ import {
16
+ EvictionManager,
17
+ FeePayerBalanceEvictionRule,
18
+ FeePayerBalancePreAddRule,
19
+ InvalidTxsAfterMiningRule,
20
+ InvalidTxsAfterReorgRule,
21
+ LowPriorityEvictionRule,
22
+ LowPriorityPreAddRule,
23
+ NullifierConflictRule,
24
+ type PoolOperations,
25
+ type PreAddPoolAccess,
26
+ } from './eviction/index.js';
27
+ import {
28
+ type AddTxsResult,
29
+ DEFAULT_TX_POOL_V2_CONFIG,
30
+ type PoolReadAccess,
31
+ type TxPoolV2Config,
32
+ type TxPoolV2Dependencies,
33
+ } from './interfaces.js';
34
+ import { type TxMetaData, type TxState, buildTxMetaData, checkNullifierConflict } from './tx_metadata.js';
35
+ import { TxPoolIndices } from './tx_pool_indices.js';
36
+
37
+ /**
38
+ * Callbacks for the implementation to notify the outer class about events and metrics.
39
+ */
40
+ export interface TxPoolV2Callbacks {
41
+ onTxsAdded: (txs: Tx[], opts: { source?: string }) => void;
42
+ onTxsRemoved: (txHashes: string[] | bigint[]) => void;
43
+ }
44
+
45
+ /**
46
+ * Implementation of TxPoolV2 logic.
47
+ *
48
+ * This class contains all the actual transaction pool logic.
49
+ */
50
+ export class TxPoolV2Impl {
51
+ // === Persistence ===
52
+ #store: AztecAsyncKVStore;
53
+ #txsDB: AztecAsyncMap<string, Buffer>;
54
+
55
+ // === Dependencies ===
56
+ #l2BlockSource: L2BlockSource;
57
+ #worldStateSynchronizer: WorldStateSynchronizer;
58
+ #createTxValidator: TxPoolV2Dependencies['createTxValidator'];
59
+
60
+ // === In-Memory Indices ===
61
+ #indices: TxPoolIndices = new TxPoolIndices();
62
+
63
+ // === Config & Services ===
64
+ #config: TxPoolV2Config;
65
+ #archive: TxArchive;
66
+ #deletedPool: DeletedPool;
67
+ #evictionManager: EvictionManager;
68
+ #dateProvider: DateProvider;
69
+ #log: Logger;
70
+ #callbacks: TxPoolV2Callbacks;
71
+
72
+ constructor(
73
+ store: AztecAsyncKVStore,
74
+ archiveStore: AztecAsyncKVStore,
75
+ deps: TxPoolV2Dependencies,
76
+ callbacks: TxPoolV2Callbacks,
77
+ config: Partial<TxPoolV2Config> = {},
78
+ dateProvider: DateProvider,
79
+ log: Logger,
80
+ ) {
81
+ this.#store = store;
82
+ this.#txsDB = store.openMap('txs');
83
+
84
+ this.#l2BlockSource = deps.l2BlockSource;
85
+ this.#worldStateSynchronizer = deps.worldStateSynchronizer;
86
+ this.#createTxValidator = deps.createTxValidator;
87
+
88
+ this.#config = { ...DEFAULT_TX_POOL_V2_CONFIG, ...config };
89
+ this.#archive = new TxArchive(archiveStore, this.#config.archivedTxLimit, log);
90
+ this.#deletedPool = new DeletedPool(store, this.#txsDB, log);
91
+ this.#dateProvider = dateProvider;
92
+ this.#log = log;
93
+ this.#callbacks = callbacks;
94
+
95
+ // Setup eviction manager with rules
96
+ this.#evictionManager = new EvictionManager(this.#createPoolOperations(), log);
97
+
98
+ // Pre-add rules (run during addPendingTxs) - work with TxMetaData
99
+ this.#evictionManager.registerPreAddRule(new NullifierConflictRule());
100
+ this.#evictionManager.registerPreAddRule(new FeePayerBalancePreAddRule());
101
+ this.#evictionManager.registerPreAddRule(
102
+ new LowPriorityPreAddRule({ maxPoolSize: this.#config.maxPendingTxCount }),
103
+ );
104
+
105
+ // Post-event eviction rules (run after events to check ALL pending txs)
106
+ this.#evictionManager.registerRule(new InvalidTxsAfterMiningRule());
107
+ this.#evictionManager.registerRule(new InvalidTxsAfterReorgRule(deps.worldStateSynchronizer));
108
+ this.#evictionManager.registerRule(new FeePayerBalanceEvictionRule(deps.worldStateSynchronizer));
109
+ // LowPriorityEvictionRule handles cases where txs become pending via prepareForSlot (unprotect)
110
+ // The pre-add rule handles the addPendingTxs case, but post-event is needed for unprotect
111
+ this.#evictionManager.registerRule(new LowPriorityEvictionRule({ maxPoolSize: this.#config.maxPendingTxCount }));
112
+ }
113
+
114
+ // ============================================================================
115
+ // PUBLIC IMPLEMENTATION METHODS
116
+ // ============================================================================
117
+
118
+ /**
119
+ * Hydrates the in-memory state from the database on startup.
120
+ * Pipeline: Load → Check Mined Status → Partition → Validate Non-Mined → Rebuild Pending Pool → Delete Invalid
121
+ *
122
+ * Note: Protected status is lost on restart. All non-mined txs are rebuilt as pending
123
+ * by running pre-add rules to resolve nullifier conflicts, balance checks, and pool size limits.
124
+ */
125
+ async hydrateFromDatabase(): Promise<void> {
126
+ // Step 0: Hydrate deleted pool state
127
+ await this.#deletedPool.hydrateFromDatabase();
128
+
129
+ // Step 1: Load all transactions from DB (excluding soft-deleted)
130
+ const { loaded, errors: deserializationErrors } = await this.#loadAllTxsFromDb();
131
+
132
+ // Step 2: Check mined status for each tx
133
+ await this.#markMinedStatusBatch(loaded.map(l => l.meta));
134
+
135
+ // Step 3: Partition by mined status
136
+ const mined: TxMetaData[] = [];
137
+ const nonMined: { tx: Tx; meta: TxMetaData }[] = [];
138
+ for (const entry of loaded) {
139
+ if (entry.meta.minedL2BlockId !== undefined) {
140
+ mined.push(entry.meta);
141
+ } else {
142
+ nonMined.push(entry);
143
+ }
144
+ }
145
+
146
+ // Step 4: Validate non-mined transactions
147
+ const { valid, invalid } = await this.#revalidateMetadata(
148
+ nonMined.map(e => e.meta),
149
+ 'on startup',
150
+ );
151
+
152
+ // Step 5: Populate mined indices (these don't need conflict resolution)
153
+ for (const meta of mined) {
154
+ this.#indices.addMined(meta);
155
+ }
156
+
157
+ // Step 6: Rebuild pending pool by running pre-add rules for each tx
158
+ // This resolves nullifier conflicts, fee payer balance issues, and pool size limits
159
+ const { rejected } = await this.#rebuildPendingPool(valid);
160
+
161
+ // Step 7: Delete invalid and rejected txs from DB only (indices were never populated for these)
162
+ const toDelete = [...deserializationErrors, ...invalid, ...rejected];
163
+ if (toDelete.length === 0) {
164
+ return;
165
+ }
166
+ await this.#store.transactionAsync(async () => {
167
+ for (const txHashStr of toDelete) {
168
+ await this.#txsDB.delete(txHashStr);
169
+ }
170
+ });
171
+ this.#log.info(`Deleted ${toDelete.length} invalid/rejected transactions on startup`, { txHashes: toDelete });
172
+ }
173
+
174
+ async addPendingTxs(txs: Tx[], opts: { source?: string }): Promise<AddTxsResult> {
175
+ const accepted: TxHash[] = [];
176
+ const ignored: TxHash[] = [];
177
+ const rejected: TxHash[] = [];
178
+ const acceptedPending = new Set<string>();
179
+
180
+ const poolAccess = this.#createPreAddPoolAccess();
181
+
182
+ await this.#store.transactionAsync(async () => {
183
+ for (const tx of txs) {
184
+ const txHash = tx.getTxHash();
185
+ const txHashStr = txHash.toString();
186
+
187
+ // Skip duplicates
188
+ if (this.#indices.has(txHashStr)) {
189
+ ignored.push(txHash);
190
+ continue;
191
+ }
192
+
193
+ // Check mined status first (applies to all paths)
194
+ const minedBlockId = await this.#getMinedBlockId(txHash);
195
+ const preProtectedSlot = this.#indices.getProtectionSlot(txHashStr);
196
+
197
+ if (minedBlockId) {
198
+ // Already mined - add directly (protection already set if pre-protected)
199
+ await this.#addTx(tx, { mined: minedBlockId }, opts);
200
+ accepted.push(txHash);
201
+ } else if (preProtectedSlot !== undefined) {
202
+ // Pre-protected and not mined - add as protected (bypass validation)
203
+ await this.#addTx(tx, { protected: preProtectedSlot }, opts);
204
+ accepted.push(txHash);
205
+ } else {
206
+ // Regular pending tx - validate and run pre-add rules
207
+ const result = await this.#tryAddRegularPendingTx(tx, opts, poolAccess, acceptedPending, ignored);
208
+ if (result.status === 'accepted') {
209
+ acceptedPending.add(txHashStr);
210
+ } else if (result.status === 'rejected') {
211
+ rejected.push(txHash);
212
+ } else {
213
+ ignored.push(txHash);
214
+ }
215
+ }
216
+ }
217
+ });
218
+
219
+ // Build final accepted list for pending txs (excludes intra-batch evictions)
220
+ for (const txHashStr of acceptedPending) {
221
+ accepted.push(TxHash.fromString(txHashStr));
222
+ }
223
+
224
+ // Run post-add eviction rules for pending txs
225
+ if (acceptedPending.size > 0) {
226
+ const feePayers = Array.from(acceptedPending).map(txHash => this.#indices.getMetadata(txHash)!.feePayer);
227
+ const uniqueFeePayers = new Set<string>(feePayers);
228
+ await this.#evictionManager.evictAfterNewTxs(Array.from(acceptedPending), [...uniqueFeePayers]);
229
+ }
230
+
231
+ return { accepted, ignored, rejected };
232
+ }
233
+
234
+ /** Validates and adds a regular pending tx. Returns status. */
235
+ async #tryAddRegularPendingTx(
236
+ tx: Tx,
237
+ opts: { source?: string },
238
+ poolAccess: PreAddPoolAccess,
239
+ acceptedPending: Set<string>,
240
+ ignored: TxHash[],
241
+ ): Promise<{ status: 'accepted' | 'ignored' | 'rejected' }> {
242
+ const txHash = tx.getTxHash();
243
+ const txHashStr = txHash.toString();
244
+
245
+ // Build metadata and validate using metadata
246
+ const meta = await buildTxMetaData(tx);
247
+ if (!(await this.#validateMeta(meta))) {
248
+ return { status: 'rejected' };
249
+ }
250
+
251
+ // Run pre-add rules
252
+ const preAddResult = await this.#evictionManager.runPreAddRules(meta, poolAccess);
253
+
254
+ if (preAddResult.shouldIgnore) {
255
+ this.#log.debug(`Ignoring tx ${txHashStr}: ${preAddResult.reason}`);
256
+ return { status: 'ignored' };
257
+ }
258
+
259
+ // Evict conflicts
260
+ for (const evictHashStr of preAddResult.txHashesToEvict) {
261
+ await this.#deleteTx(evictHashStr);
262
+ this.#log.debug(`Evicted tx ${evictHashStr} due to higher-fee tx ${txHashStr}`, {
263
+ evictedTxHash: evictHashStr,
264
+ replacementTxHash: txHashStr,
265
+ });
266
+ if (acceptedPending.has(evictHashStr)) {
267
+ // Evicted tx was from this batch - mark as ignored in result
268
+ acceptedPending.delete(evictHashStr);
269
+ ignored.push(TxHash.fromString(evictHashStr));
270
+ }
271
+ }
272
+
273
+ // Add the transaction
274
+ await this.#addTx(tx, 'pending', opts);
275
+ return { status: 'accepted' };
276
+ }
277
+
278
+ async canAddPendingTx(tx: Tx): Promise<'accepted' | 'ignored' | 'rejected'> {
279
+ const txHashStr = tx.getTxHash().toString();
280
+
281
+ // Check if already in pool
282
+ if (this.#indices.has(txHashStr)) {
283
+ return 'ignored';
284
+ }
285
+
286
+ // Build metadata and validate using metadata
287
+ const meta = await buildTxMetaData(tx);
288
+ const validationResult = await this.#validateMeta(meta, undefined, 'can add pending');
289
+ if (validationResult !== true) {
290
+ return 'rejected';
291
+ }
292
+
293
+ // Use pre-add rules
294
+ const poolAccess = this.#createPreAddPoolAccess();
295
+ const preAddResult = await this.#evictionManager.runPreAddRules(meta, poolAccess);
296
+
297
+ return preAddResult.shouldIgnore ? 'ignored' : 'accepted';
298
+ }
299
+
300
+ async addProtectedTxs(txs: Tx[], block: BlockHeader, opts: { source?: string }): Promise<void> {
301
+ const slotNumber = block.globalVariables.slotNumber;
302
+
303
+ await this.#store.transactionAsync(async () => {
304
+ for (const tx of txs) {
305
+ const txHash = tx.getTxHash();
306
+ const txHashStr = txHash.toString();
307
+ const isNew = !this.#indices.has(txHashStr);
308
+ const minedBlockId = await this.#getMinedBlockId(txHash);
309
+
310
+ if (isNew) {
311
+ // New tx - add as mined or protected (callback emitted by #addTx)
312
+ if (minedBlockId) {
313
+ await this.#addTx(tx, { mined: minedBlockId }, opts);
314
+ this.#indices.setProtection(txHashStr, slotNumber);
315
+ } else {
316
+ await this.#addTx(tx, { protected: slotNumber }, opts);
317
+ }
318
+ } else {
319
+ // Existing tx - update protection and mined status
320
+ this.#indices.updateProtection(txHashStr, slotNumber);
321
+ if (minedBlockId) {
322
+ const meta = this.#indices.getMetadata(txHashStr)!;
323
+ this.#indices.markAsMined(meta, minedBlockId);
324
+ }
325
+ }
326
+ }
327
+ });
328
+ }
329
+
330
+ protectTxs(txHashes: TxHash[], block: BlockHeader): TxHash[] {
331
+ const slotNumber = block.globalVariables.slotNumber;
332
+ const missing: TxHash[] = [];
333
+
334
+ for (const txHash of txHashes) {
335
+ const txHashStr = txHash.toString();
336
+
337
+ if (this.#indices.has(txHashStr)) {
338
+ // Update protection for existing tx
339
+ this.#indices.updateProtection(txHashStr, slotNumber);
340
+ } else {
341
+ // Pre-record protection for tx we don't have yet
342
+ this.#indices.setProtection(txHashStr, slotNumber);
343
+ missing.push(txHash);
344
+ }
345
+ }
346
+
347
+ return missing;
348
+ }
349
+
350
+ async addMinedTxs(txs: Tx[], block: BlockHeader, opts: { source?: string }): Promise<void> {
351
+ // Step 1: Build block ID
352
+ const blockId = await this.#buildBlockId(block);
353
+
354
+ await this.#store.transactionAsync(async () => {
355
+ for (const tx of txs) {
356
+ const txHashStr = tx.getTxHash().toString();
357
+ const existingMeta = this.#indices.getMetadata(txHashStr);
358
+
359
+ if (existingMeta) {
360
+ // Mark existing tx as mined
361
+ this.#indices.markAsMined(existingMeta, blockId);
362
+ } else {
363
+ // Add new mined tx (callback emitted by #addTx)
364
+ await this.#addTx(tx, { mined: blockId }, opts);
365
+ }
366
+ await this.#deletedPool.clearIfMinedHigher(txHashStr, blockId.number);
367
+ }
368
+ });
369
+ }
370
+
371
+ async handleMinedBlock(block: L2Block): Promise<void> {
372
+ // Step 1: Build block ID
373
+ const blockId = await this.#buildBlockId(block.header);
374
+
375
+ // Step 2: Extract tx hashes and nullifiers directly from the block
376
+ const txHashes = block.body.txEffects.map(tx => tx.txHash);
377
+ const nullifiers = block.body.txEffects.flatMap(tx => tx.nullifiers.map(n => n.toString()));
378
+
379
+ // Step 3: Collect fee payers from txs we have in the pool (for balance-based eviction)
380
+ const feePayers: string[] = [];
381
+ const found: TxMetaData[] = [];
382
+ for (const txHash of txHashes) {
383
+ const meta = this.#indices.getMetadata(txHash.toString());
384
+ if (meta) {
385
+ feePayers.push(meta.feePayer);
386
+ found.push(meta);
387
+ }
388
+ }
389
+
390
+ // Step 4: Mark txs as mined (only those we have in the pool)
391
+ for (const meta of found) {
392
+ this.#indices.markAsMined(meta, blockId);
393
+ await this.#deletedPool.clearIfMinedHigher(meta.txHash, blockId.number);
394
+ }
395
+
396
+ // Step 5: Run eviction rules (remove pending txs with conflicting nullifiers/expired timestamps)
397
+ await this.#evictionManager.evictAfterNewBlock(block.header, nullifiers, feePayers);
398
+
399
+ this.#log.info(`Marked ${found.length} txs as mined in block ${blockId.number}`);
400
+ }
401
+
402
+ async prepareForSlot(slotNumber: SlotNumber): Promise<void> {
403
+ // Step 0: Clean up slot-deleted txs from previous slots
404
+ await this.#deletedPool.cleanupSlotDeleted(slotNumber);
405
+
406
+ // Step 1: Find expired protected txs
407
+ const expiredProtected = this.#indices.findExpiredProtectedTxs(slotNumber);
408
+
409
+ // Step 2: Clear protection for all expired entries (including those without metadata)
410
+ this.#indices.clearProtection(expiredProtected);
411
+
412
+ // Step 3: Filter to only txs that have metadata and are not mined
413
+ const txsToRestore = this.#indices.filterRestorable(expiredProtected);
414
+ if (txsToRestore.length === 0) {
415
+ return;
416
+ }
417
+
418
+ this.#log.info(`Preparing for slot ${slotNumber}: unprotecting ${txsToRestore.length} txs`);
419
+
420
+ // Step 4: Validate for pending pool
421
+ const { valid, invalid } = await this.#revalidateMetadata(txsToRestore, 'during prepareForSlot');
422
+
423
+ // Step 5: Resolve nullifier conflicts and add winners to pending indices
424
+ const { added, toEvict } = this.#applyNullifierConflictResolution(valid);
425
+
426
+ // Step 6: Delete invalid and evicted txs
427
+ await this.#deleteTxsBatch([...invalid, ...toEvict]);
428
+
429
+ // Step 7: Run eviction rules (enforce pool size limit)
430
+ if (added.length > 0) {
431
+ const feePayers = added.map(meta => meta.feePayer);
432
+ const uniqueFeePayers = new Set<string>(feePayers);
433
+ await this.#evictionManager.evictAfterNewTxs(
434
+ added.map(m => m.txHash),
435
+ [...uniqueFeePayers],
436
+ );
437
+ }
438
+ }
439
+
440
+ async handlePrunedBlocks(latestBlock: L2BlockId): Promise<void> {
441
+ // Step 1: Find transactions mined after the prune point
442
+ const txsToUnmine = this.#indices.findTxsMinedAfter(latestBlock.number);
443
+ if (txsToUnmine.length === 0) {
444
+ this.#log.debug(`No transactions to un-mine for prune to block ${latestBlock.number}`);
445
+ return;
446
+ }
447
+
448
+ this.#log.info(`Handling prune to block ${latestBlock.number}: un-mining ${txsToUnmine.length} txs`);
449
+
450
+ // Step 2: Mark ALL un-mined txs with their original mined block number
451
+ // This ensures they get soft-deleted if removed later, and only hard-deleted
452
+ // when their original mined block is finalized
453
+ await this.#deletedPool.markFromPrunedBlock(
454
+ txsToUnmine.map(m => ({
455
+ txHash: m.txHash,
456
+ minedAtBlock: BlockNumber(m.minedL2BlockId!.number),
457
+ })),
458
+ );
459
+
460
+ // Step 3: Unmine - clear mined status from metadata
461
+ for (const meta of txsToUnmine) {
462
+ this.#indices.markAsUnmined(meta);
463
+ }
464
+
465
+ // Step 4: Filter out protected txs (they'll be handled by prepareForSlot)
466
+ const unprotectedTxs = this.#indices.filterUnprotected(txsToUnmine);
467
+
468
+ // Step 4: Validate for pending pool
469
+ const { valid, invalid } = await this.#revalidateMetadata(unprotectedTxs, 'during handlePrunedBlocks');
470
+
471
+ // Step 6: Resolve nullifier conflicts and add winners to pending indices
472
+ const { toEvict } = this.#applyNullifierConflictResolution(valid);
473
+
474
+ // Step 7: Delete invalid and evicted txs
475
+ await this.#deleteTxsBatch([...invalid, ...toEvict]);
476
+
477
+ this.#log.info(
478
+ `Handled prune to block ${latestBlock.number}: ${valid.length} txs restored to pending, ${invalid.length} invalid, ${toEvict.length} evicted due to nullifier conflicts`,
479
+ { txHashesRestored: valid.map(m => m.txHash), txHashesInvalid: invalid, txHashesEvicted: toEvict },
480
+ );
481
+
482
+ // Step 8: Run eviction rules for ALL pending txs (not just restored ones)
483
+ // This handles cases like existing pending txs with invalid fee payer balances
484
+ await this.#evictionManager.evictAfterChainPrune(latestBlock.number);
485
+ }
486
+
487
+ async handleFailedExecution(txHashes: TxHash[]): Promise<void> {
488
+ // Delete failed txs
489
+ await this.#deleteTxsBatch(txHashes.map(h => h.toString()));
490
+
491
+ this.#log.info(`Deleted ${txHashes.length} failed txs`, { txHashes: txHashes.map(h => h.toString()) });
492
+ }
493
+
494
+ async handleFinalizedBlock(block: BlockHeader): Promise<void> {
495
+ const blockNumber = block.globalVariables.blockNumber;
496
+
497
+ // Step 1: Find mined txs at or before finalized block
498
+ const minedTxsToFinalize = this.#indices.findTxsMinedAtOrBefore(blockNumber);
499
+
500
+ // Step 2: Collect mined txs for archiving (before deletion)
501
+ const txsToArchive: Tx[] = [];
502
+ if (this.#archive.isEnabled()) {
503
+ for (const txHashStr of minedTxsToFinalize) {
504
+ const buffer = await this.#txsDB.getAsync(txHashStr);
505
+ if (buffer) {
506
+ txsToArchive.push(Tx.fromBuffer(buffer));
507
+ }
508
+ }
509
+ }
510
+
511
+ // Step 3: Delete mined txs from active pool
512
+ await this.#deleteTxsBatch(minedTxsToFinalize);
513
+
514
+ // Step 4: Finalize soft-deleted txs
515
+ await this.#deletedPool.finalizeBlock(blockNumber);
516
+
517
+ // Step 5: Archive mined txs
518
+ if (txsToArchive.length > 0) {
519
+ await this.#archive.archiveTxs(txsToArchive);
520
+ }
521
+
522
+ if (minedTxsToFinalize.length > 0) {
523
+ this.#log.info(`Finalized ${minedTxsToFinalize.length} mined txs from blocks up to ${blockNumber}`, {
524
+ txHashes: minedTxsToFinalize,
525
+ });
526
+ }
527
+ }
528
+
529
+ // === Query Methods ===
530
+
531
+ async getTxByHash(txHash: TxHash): Promise<Tx | undefined> {
532
+ const buffer = await this.#txsDB.getAsync(txHash.toString());
533
+ return buffer ? Tx.fromBuffer(buffer) : undefined;
534
+ }
535
+
536
+ async getTxsByHash(txHashes: TxHash[]): Promise<(Tx | undefined)[]> {
537
+ const results: (Tx | undefined)[] = [];
538
+ for (const h of txHashes) {
539
+ const buffer = await this.#txsDB.getAsync(h.toString());
540
+ results.push(buffer ? Tx.fromBuffer(buffer) : undefined);
541
+ }
542
+ return results;
543
+ }
544
+
545
+ hasTxs(txHashes: TxHash[]): boolean[] {
546
+ return txHashes.map(h => {
547
+ const hashStr = h.toString();
548
+ return this.#indices.has(hashStr) || this.#deletedPool.isSoftDeleted(hashStr);
549
+ });
550
+ }
551
+
552
+ getTxStatus(txHash: TxHash): TxState | undefined {
553
+ const txHashStr = txHash.toString();
554
+ const meta = this.#indices.getMetadata(txHashStr);
555
+ if (meta) {
556
+ return this.#indices.getTxState(meta);
557
+ }
558
+ // Check if soft-deleted
559
+ if (this.#deletedPool.isSoftDeleted(txHashStr)) {
560
+ return 'deleted';
561
+ }
562
+ return undefined;
563
+ }
564
+
565
+ getPendingTxHashes(): TxHash[] {
566
+ return [...this.#indices.iteratePendingByPriority('desc')].map(hash => TxHash.fromString(hash));
567
+ }
568
+
569
+ getEligiblePendingTxHashes(): TxHash[] {
570
+ const maxReceivedAt = this.#dateProvider.now() - this.#config.minTxPoolAgeMs;
571
+ return [...this.#indices.iterateEligiblePendingByPriority('desc', maxReceivedAt)].map(hash =>
572
+ TxHash.fromString(hash),
573
+ );
574
+ }
575
+
576
+ getPendingTxCount(): number {
577
+ return this.#indices.getPendingTxCount();
578
+ }
579
+
580
+ getMinedTxHashes(): [TxHash, L2BlockId][] {
581
+ return this.#indices.getMinedTxs().map(([hash, blockId]) => [TxHash.fromString(hash), blockId]);
582
+ }
583
+
584
+ getMinedTxCount(): number {
585
+ let count = 0;
586
+ for (const [, meta] of this.#indices.iterateMetadata()) {
587
+ if (meta.minedL2BlockId !== undefined) {
588
+ count++;
589
+ }
590
+ }
591
+ return count;
592
+ }
593
+
594
+ isEmpty(): boolean {
595
+ return this.#indices.isEmpty();
596
+ }
597
+
598
+ getTxCount(): number {
599
+ return this.#indices.getTxCount();
600
+ }
601
+
602
+ getArchivedTxByHash(txHash: TxHash): Promise<Tx | undefined> {
603
+ return this.#archive.getTxByHash(txHash);
604
+ }
605
+
606
+ getLowestPriorityPending(limit: number): TxHash[] {
607
+ return this.#indices.getLowestPriorityPending(limit).map(h => TxHash.fromString(h));
608
+ }
609
+
610
+ // === Configuration ===
611
+
612
+ updateConfig(config: Partial<TxPoolV2Config>): void {
613
+ if (config.maxPendingTxCount !== undefined) {
614
+ this.#config.maxPendingTxCount = config.maxPendingTxCount;
615
+ }
616
+ if (config.archivedTxLimit !== undefined) {
617
+ this.#config.archivedTxLimit = config.archivedTxLimit;
618
+ this.#archive.updateLimit(config.archivedTxLimit);
619
+ }
620
+ if (config.minTxPoolAgeMs !== undefined) {
621
+ this.#config.minTxPoolAgeMs = config.minTxPoolAgeMs;
622
+ }
623
+ // Update eviction rules with new config
624
+ this.#evictionManager.updateConfig(config);
625
+ }
626
+
627
+ // === Pool Read Access ===
628
+
629
+ getPoolReadAccess(): PoolReadAccess {
630
+ return {
631
+ getMetadata: (txHash: string) => this.#indices.getMetadata(txHash),
632
+ getTxHashByNullifier: (nullifier: string) => this.#indices.getTxHashByNullifier(nullifier),
633
+ getTxHashesByFeePayer: (feePayer: string) => this.#indices.getTxHashesByFeePayer(feePayer),
634
+ getPendingTxCount: () => this.#indices.getPendingTxCount(),
635
+ };
636
+ }
637
+
638
+ // === Metrics ===
639
+
640
+ countTxs(): { pending: number; protected: number; mined: number } {
641
+ return this.#indices.countTxs();
642
+ }
643
+
644
+ // ============================================================================
645
+ // PRIVATE HELPERS - Transaction Management
646
+ // ============================================================================
647
+
648
+ /**
649
+ * Adds a new transaction to the pool with the specified state.
650
+ * Emits onTxsAdded callback immediately after DB write.
651
+ */
652
+ async #addTx(
653
+ tx: Tx,
654
+ state: 'pending' | { protected: SlotNumber } | { mined: L2BlockId },
655
+ opts: { source?: string } = {},
656
+ ): Promise<TxMetaData> {
657
+ const txHashStr = tx.getTxHash().toString();
658
+ const meta = await buildTxMetaData(tx);
659
+ meta.receivedAt = this.#dateProvider.now();
660
+
661
+ await this.#txsDB.set(txHashStr, tx.toBuffer());
662
+ await this.#deletedPool.clearSoftDeleted(txHashStr);
663
+ this.#callbacks.onTxsAdded([tx], opts);
664
+
665
+ if (state === 'pending') {
666
+ this.#indices.addPending(meta);
667
+ } else if ('protected' in state) {
668
+ this.#indices.addProtected(meta, state.protected);
669
+ } else {
670
+ meta.minedL2BlockId = state.mined;
671
+ this.#indices.addMined(meta);
672
+ }
673
+
674
+ const stateStr = typeof state === 'string' ? state : Object.keys(state)[0];
675
+ this.#log.verbose(`Added ${stateStr} tx ${txHashStr}`, {
676
+ eventName: 'tx-added-to-pool',
677
+ state: stateStr,
678
+ });
679
+
680
+ return meta;
681
+ }
682
+
683
+ /**
684
+ * Deletes a transaction from both indices and DB.
685
+ * Emits onTxsRemoved callback immediately after DB delete.
686
+ */
687
+ /**
688
+ * Deletes a transaction from the pool.
689
+ * Delegates to DeletedPool which decides soft vs hard delete based on whether
690
+ * the tx is from a pruned block.
691
+ */
692
+ async #deleteTx(txHashStr: string): Promise<void> {
693
+ this.#indices.remove(txHashStr);
694
+ this.#callbacks.onTxsRemoved([txHashStr]);
695
+ await this.#deletedPool.deleteTx(txHashStr);
696
+ }
697
+
698
+ /** Deletes a batch of transactions, emitting callbacks individually for each. */
699
+ async #deleteTxsBatch(txHashes: string[]): Promise<void> {
700
+ for (const txHashStr of txHashes) {
701
+ await this.#deleteTx(txHashStr);
702
+ }
703
+ }
704
+
705
+ // ============================================================================
706
+ // PRIVATE HELPERS - Validation & Conflict Resolution
707
+ // ============================================================================
708
+
709
+ /** Validates transaction metadata, returning true if valid */
710
+ async #validateMeta(meta: TxMetaData, validator?: TxValidator<TxMetaData>, context?: string): Promise<boolean> {
711
+ const txValidator = validator ?? (await this.#createTxValidator());
712
+ const result = await txValidator.validateTx(meta);
713
+ if (result.result !== 'valid') {
714
+ const contextStr = context ? ` ${context}` : '';
715
+ this.#log.info(`Tx ${meta.txHash}${contextStr} failed validation: ${result.reason?.join(', ')}`);
716
+ return false;
717
+ }
718
+ return true;
719
+ }
720
+
721
+ /** Validates metadata directly */
722
+ async #revalidateMetadata(
723
+ metas: TxMetaData[],
724
+ context?: string,
725
+ ): Promise<{ valid: TxMetaData[]; invalid: string[] }> {
726
+ const valid: TxMetaData[] = [];
727
+ const invalid: string[] = [];
728
+ const validator = await this.#createTxValidator();
729
+ for (const meta of metas) {
730
+ if (await this.#validateMeta(meta, validator, context)) {
731
+ valid.push(meta);
732
+ } else {
733
+ invalid.push(meta.txHash);
734
+ }
735
+ }
736
+ return { valid, invalid };
737
+ }
738
+
739
+ /**
740
+ * Resolves nullifier conflicts between incoming txs and existing pending txs.
741
+ * Modifies the pending indices during iteration to maintain consistent state
742
+ * for subsequent conflict checks within the same batch.
743
+ */
744
+ #applyNullifierConflictResolution(txs: TxMetaData[]): { added: TxMetaData[]; toEvict: string[] } {
745
+ const added: TxMetaData[] = [];
746
+ const toEvict: string[] = [];
747
+
748
+ for (const meta of txs) {
749
+ const conflict = checkNullifierConflict(
750
+ meta,
751
+ nullifier => this.#indices.getTxHashByNullifier(nullifier),
752
+ txHash => this.#indices.getMetadata(txHash),
753
+ );
754
+ if (conflict.shouldIgnore) {
755
+ // Lower priority than existing - don't add, mark for deletion
756
+ toEvict.push(meta.txHash);
757
+ } else {
758
+ // Higher priority - evict existing conflicts
759
+ toEvict.push(...conflict.txHashesToEvict);
760
+ // Remove evicted from indices immediately for subsequent checks
761
+ for (const evictHash of conflict.txHashesToEvict) {
762
+ const evictMeta = this.#indices.getMetadata(evictHash);
763
+ if (evictMeta) {
764
+ this.#indices.removeFromPendingIndices(evictMeta);
765
+ }
766
+ }
767
+ // Add to pending indices immediately so subsequent txs in the batch see this tx
768
+ this.#indices.addToPendingIndices(meta);
769
+ added.push(meta);
770
+ }
771
+ }
772
+
773
+ return { added, toEvict };
774
+ }
775
+
776
+ // ============================================================================
777
+ // PRIVATE HELPERS - Block & Hydration
778
+ // ============================================================================
779
+
780
+ async #buildBlockId(block: BlockHeader): Promise<L2BlockId> {
781
+ return {
782
+ number: block.globalVariables.blockNumber,
783
+ hash: (await block.hash()).toString(),
784
+ };
785
+ }
786
+
787
+ /** Checks if a tx is already mined and returns its block ID if so */
788
+ async #getMinedBlockId(txHash: TxHash): Promise<L2BlockId | undefined> {
789
+ const txEffect = await this.#l2BlockSource.getTxEffect(txHash);
790
+ if (!txEffect) {
791
+ return undefined;
792
+ }
793
+ return {
794
+ number: txEffect.l2BlockNumber,
795
+ hash: txEffect.l2BlockHash.toString(),
796
+ };
797
+ }
798
+
799
+ /** Loads all transactions from the database, returning loaded txs and deserialization errors */
800
+ async #loadAllTxsFromDb(): Promise<{
801
+ loaded: { tx: Tx; meta: TxMetaData }[];
802
+ errors: string[];
803
+ }> {
804
+ const loaded: { tx: Tx; meta: TxMetaData }[] = [];
805
+ const errors: string[] = [];
806
+
807
+ for await (const [txHashStr, buffer] of this.#txsDB.entriesAsync()) {
808
+ // Skip soft-deleted transactions - they stay in DB but not in indices
809
+ if (this.#deletedPool.isSoftDeleted(txHashStr)) {
810
+ continue;
811
+ }
812
+
813
+ try {
814
+ const tx = Tx.fromBuffer(buffer);
815
+ const meta = await buildTxMetaData(tx);
816
+ loaded.push({ tx, meta });
817
+ } catch (err) {
818
+ this.#log.warn(`Failed to deserialize tx ${txHashStr}, deleting`, { err });
819
+ errors.push(txHashStr);
820
+ }
821
+ }
822
+
823
+ return { loaded, errors };
824
+ }
825
+
826
+ /** Queries block source and marks mined status on transaction metadata */
827
+ async #markMinedStatusBatch(metas: TxMetaData[]): Promise<void> {
828
+ for (const meta of metas) {
829
+ try {
830
+ const txEffect = await this.#l2BlockSource.getTxEffect(TxHash.fromString(meta.txHash));
831
+ if (txEffect) {
832
+ meta.minedL2BlockId = {
833
+ number: txEffect.l2BlockNumber,
834
+ hash: txEffect.l2BlockHash.toString(),
835
+ };
836
+ }
837
+ } catch (err) {
838
+ this.#log.warn(`Failed to check mined status for tx ${meta.txHash}`, { err });
839
+ }
840
+ }
841
+ }
842
+
843
+ /**
844
+ * Rebuilds the pending pool by processing each tx through pre-add rules.
845
+ * Starts with an empty pending pool and adds txs one by one, resolving conflicts.
846
+ * Returns the list of accepted and rejected tx hashes.
847
+ */
848
+ async #rebuildPendingPool(metas: TxMetaData[]): Promise<{ accepted: string[]; rejected: string[] }> {
849
+ const accepted = new Set<string>();
850
+ const rejected: string[] = [];
851
+ const poolAccess = this.#createPreAddPoolAccess();
852
+
853
+ for (const meta of metas) {
854
+ // Run pre-add rules against current pending pool state (metadata not yet in pool)
855
+ const preAddResult = await this.#evictionManager.runPreAddRules(meta, poolAccess);
856
+
857
+ if (preAddResult.shouldIgnore) {
858
+ // Transaction rejected - mark for deletion from DB
859
+ rejected.push(meta.txHash);
860
+ this.#log.debug(`Rejected tx ${meta.txHash} during rebuild: ${preAddResult.reason}`);
861
+ continue;
862
+ }
863
+
864
+ // Evict any conflicting txs identified by pre-add rules
865
+ for (const evictHashStr of preAddResult.txHashesToEvict) {
866
+ const evictMeta = this.#indices.getMetadata(evictHashStr);
867
+ if (evictMeta) {
868
+ this.#indices.removeFromPendingIndices(evictMeta);
869
+ this.#indices.remove(evictHashStr);
870
+ rejected.push(evictHashStr);
871
+ accepted.delete(evictHashStr);
872
+ this.#log.debug(`Evicted tx ${evictHashStr} during rebuild due to conflict with ${meta.txHash}`);
873
+ }
874
+ }
875
+
876
+ // Add to indices
877
+ this.#indices.addPending(meta);
878
+ accepted.add(meta.txHash);
879
+ }
880
+
881
+ this.#log.info(`Rebuilt pending pool: ${accepted.size} accepted, ${rejected.length} rejected`);
882
+ return { accepted: [...accepted], rejected };
883
+ }
884
+
885
+ // ============================================================================
886
+ // PRIVATE HELPERS - Pool Access Adapters
887
+ // ============================================================================
888
+
889
+ #createPoolOperations(): PoolOperations {
890
+ return {
891
+ getPendingTxs: () => this.#indices.getPendingTxs(),
892
+ getPendingFeePayers: () => this.#indices.getPendingFeePayers(),
893
+ getFeePayerPendingTxs: (feePayer: string) => this.#indices.getFeePayerPendingTxs(feePayer),
894
+ getPendingTxCount: () => this.#indices.getPendingTxCount(),
895
+ getLowestPriorityPending: (limit: number) => this.#indices.getLowestPriorityPending(limit),
896
+ deleteTxs: (txHashes: string[]) => this.#deleteTxsBatch(txHashes),
897
+ };
898
+ }
899
+
900
+ #createPreAddPoolAccess(): PreAddPoolAccess {
901
+ return {
902
+ getMetadata: (txHashStr: string) => {
903
+ const meta = this.#indices.getMetadata(txHashStr);
904
+ if (!meta || this.#indices.getTxState(meta) !== 'pending') {
905
+ return undefined;
906
+ }
907
+ return meta;
908
+ },
909
+ getTxHashByNullifier: (nullifier: string) => this.#indices.getTxHashByNullifier(nullifier),
910
+ getFeePayerBalance: async (feePayer: string) => {
911
+ const db = this.#worldStateSynchronizer.getCommitted();
912
+ const publicStateSource = new DatabasePublicStateSource(db);
913
+ const balance = await publicStateSource.storageRead(
914
+ ProtocolContractAddress.FeeJuice,
915
+ await computeFeePayerBalanceStorageSlot(AztecAddress.fromString(feePayer)),
916
+ );
917
+ return balance.toBigInt();
918
+ },
919
+ getFeePayerPendingTxs: (feePayer: string) => this.#indices.getFeePayerPendingTxs(feePayer),
920
+ getPendingTxCount: () => this.#indices.getPendingTxCount(),
921
+ getLowestPriorityPendingTx: () => this.#indices.getLowestPriorityPendingTx(),
922
+ };
923
+ }
924
+ }