@aztec/p2p 0.0.1-commit.f1df4d2 → 0.0.1-commit.f224bb98b

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