@aztec-labs/p2p 6.0.0-nightly.20260829

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 (607) hide show
  1. package/README.md +134 -0
  2. package/dest/bootstrap/bootstrap.d.ts +39 -0
  3. package/dest/bootstrap/bootstrap.d.ts.map +1 -0
  4. package/dest/bootstrap/bootstrap.js +152 -0
  5. package/dest/client/factory.d.ts +32 -0
  6. package/dest/client/factory.d.ts.map +1 -0
  7. package/dest/client/factory.js +125 -0
  8. package/dest/client/index.d.ts +4 -0
  9. package/dest/client/index.d.ts.map +1 -0
  10. package/dest/client/index.js +3 -0
  11. package/dest/client/interface.d.ts +223 -0
  12. package/dest/client/interface.d.ts.map +1 -0
  13. package/dest/client/interface.js +9 -0
  14. package/dest/client/p2p_client.d.ts +202 -0
  15. package/dest/client/p2p_client.d.ts.map +1 -0
  16. package/dest/client/p2p_client.js +1051 -0
  17. package/dest/config.d.ts +295 -0
  18. package/dest/config.d.ts.map +1 -0
  19. package/dest/config.js +458 -0
  20. package/dest/enr/generate-enr.d.ts +17 -0
  21. package/dest/enr/generate-enr.d.ts.map +1 -0
  22. package/dest/enr/generate-enr.js +52 -0
  23. package/dest/enr/index.d.ts +2 -0
  24. package/dest/enr/index.d.ts.map +1 -0
  25. package/dest/enr/index.js +1 -0
  26. package/dest/errors/attestation-pool.error.d.ts +7 -0
  27. package/dest/errors/attestation-pool.error.d.ts.map +1 -0
  28. package/dest/errors/attestation-pool.error.js +12 -0
  29. package/dest/errors/p2p-service.error.d.ts +9 -0
  30. package/dest/errors/p2p-service.error.d.ts.map +1 -0
  31. package/dest/errors/p2p-service.error.js +10 -0
  32. package/dest/errors/reqresp.error.d.ts +21 -0
  33. package/dest/errors/reqresp.error.d.ts.map +1 -0
  34. package/dest/errors/reqresp.error.js +23 -0
  35. package/dest/errors/tx-pool.error.d.ts +8 -0
  36. package/dest/errors/tx-pool.error.d.ts.map +1 -0
  37. package/dest/errors/tx-pool.error.js +9 -0
  38. package/dest/index.d.ts +11 -0
  39. package/dest/index.d.ts.map +1 -0
  40. package/dest/index.js +9 -0
  41. package/dest/mem_pools/attestation_pool/attestation_pool.d.ts +194 -0
  42. package/dest/mem_pools/attestation_pool/attestation_pool.d.ts.map +1 -0
  43. package/dest/mem_pools/attestation_pool/attestation_pool.js +521 -0
  44. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.d.ts +3 -0
  45. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.d.ts.map +1 -0
  46. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.js +745 -0
  47. package/dest/mem_pools/attestation_pool/index.d.ts +2 -0
  48. package/dest/mem_pools/attestation_pool/index.d.ts.map +1 -0
  49. package/dest/mem_pools/attestation_pool/index.js +1 -0
  50. package/dest/mem_pools/attestation_pool/mocks.d.ts +242 -0
  51. package/dest/mem_pools/attestation_pool/mocks.d.ts.map +1 -0
  52. package/dest/mem_pools/attestation_pool/mocks.js +33 -0
  53. package/dest/mem_pools/index.d.ts +4 -0
  54. package/dest/mem_pools/index.d.ts.map +1 -0
  55. package/dest/mem_pools/index.js +1 -0
  56. package/dest/mem_pools/instrumentation.d.ts +41 -0
  57. package/dest/mem_pools/instrumentation.d.ts.map +1 -0
  58. package/dest/mem_pools/instrumentation.js +120 -0
  59. package/dest/mem_pools/interface.d.ts +10 -0
  60. package/dest/mem_pools/interface.d.ts.map +1 -0
  61. package/dest/mem_pools/interface.js +3 -0
  62. package/dest/mem_pools/tx_pool_v2/archive/index.d.ts +2 -0
  63. package/dest/mem_pools/tx_pool_v2/archive/index.d.ts.map +1 -0
  64. package/dest/mem_pools/tx_pool_v2/archive/index.js +1 -0
  65. package/dest/mem_pools/tx_pool_v2/archive/tx_archive.d.ts +48 -0
  66. package/dest/mem_pools/tx_pool_v2/archive/tx_archive.d.ts.map +1 -0
  67. package/dest/mem_pools/tx_pool_v2/archive/tx_archive.js +112 -0
  68. package/dest/mem_pools/tx_pool_v2/deleted_pool.d.ts +104 -0
  69. package/dest/mem_pools/tx_pool_v2/deleted_pool.d.ts.map +1 -0
  70. package/dest/mem_pools/tx_pool_v2/deleted_pool.js +251 -0
  71. package/dest/mem_pools/tx_pool_v2/eviction/eviction_manager.d.ts +47 -0
  72. package/dest/mem_pools/tx_pool_v2/eviction/eviction_manager.d.ts.map +1 -0
  73. package/dest/mem_pools/tx_pool_v2/eviction/eviction_manager.js +128 -0
  74. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.d.ts +17 -0
  75. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.d.ts.map +1 -0
  76. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.js +94 -0
  77. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.d.ts +19 -0
  78. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.d.ts.map +1 -0
  79. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.js +99 -0
  80. package/dest/mem_pools/tx_pool_v2/eviction/index.d.ts +11 -0
  81. package/dest/mem_pools/tx_pool_v2/eviction/index.d.ts.map +1 -0
  82. package/dest/mem_pools/tx_pool_v2/eviction/index.js +12 -0
  83. package/dest/mem_pools/tx_pool_v2/eviction/insufficient_fee_per_gas_eviction_rule.d.ts +16 -0
  84. package/dest/mem_pools/tx_pool_v2/eviction/insufficient_fee_per_gas_eviction_rule.d.ts.map +1 -0
  85. package/dest/mem_pools/tx_pool_v2/eviction/insufficient_fee_per_gas_eviction_rule.js +64 -0
  86. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.d.ts +180 -0
  87. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.d.ts.map +1 -0
  88. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.js +25 -0
  89. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.d.ts +15 -0
  90. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.d.ts.map +1 -0
  91. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.js +64 -0
  92. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.d.ts +17 -0
  93. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.d.ts.map +1 -0
  94. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.js +92 -0
  95. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.d.ts +16 -0
  96. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.d.ts.map +1 -0
  97. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.js +79 -0
  98. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.d.ts +20 -0
  99. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.d.ts.map +1 -0
  100. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.js +75 -0
  101. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.d.ts +15 -0
  102. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.d.ts.map +1 -0
  103. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.js +19 -0
  104. package/dest/mem_pools/tx_pool_v2/index.d.ts +6 -0
  105. package/dest/mem_pools/tx_pool_v2/index.d.ts.map +1 -0
  106. package/dest/mem_pools/tx_pool_v2/index.js +5 -0
  107. package/dest/mem_pools/tx_pool_v2/instrumentation.d.ts +25 -0
  108. package/dest/mem_pools/tx_pool_v2/instrumentation.d.ts.map +1 -0
  109. package/dest/mem_pools/tx_pool_v2/instrumentation.js +67 -0
  110. package/dest/mem_pools/tx_pool_v2/interfaces.d.ts +243 -0
  111. package/dest/mem_pools/tx_pool_v2/interfaces.d.ts.map +1 -0
  112. package/dest/mem_pools/tx_pool_v2/interfaces.js +11 -0
  113. package/dest/mem_pools/tx_pool_v2/tx_metadata.d.ts +137 -0
  114. package/dest/mem_pools/tx_pool_v2/tx_metadata.d.ts.map +1 -0
  115. package/dest/mem_pools/tx_pool_v2/tx_metadata.js +223 -0
  116. package/dest/mem_pools/tx_pool_v2/tx_pool_bench_metrics.d.ts +26 -0
  117. package/dest/mem_pools/tx_pool_v2/tx_pool_bench_metrics.d.ts.map +1 -0
  118. package/dest/mem_pools/tx_pool_v2/tx_pool_bench_metrics.js +70 -0
  119. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.d.ts +122 -0
  120. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.d.ts.map +1 -0
  121. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.js +368 -0
  122. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.d.ts +75 -0
  123. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.d.ts.map +1 -0
  124. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.js +218 -0
  125. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.d.ts +122 -0
  126. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.d.ts.map +1 -0
  127. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.js +1039 -0
  128. package/dest/msg_validators/attestation_validator/attestation_validator.d.ts +17 -0
  129. package/dest/msg_validators/attestation_validator/attestation_validator.d.ts.map +1 -0
  130. package/dest/msg_validators/attestation_validator/attestation_validator.js +111 -0
  131. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.d.ts +24 -0
  132. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.d.ts.map +1 -0
  133. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.js +75 -0
  134. package/dest/msg_validators/attestation_validator/index.d.ts +3 -0
  135. package/dest/msg_validators/attestation_validator/index.d.ts.map +1 -0
  136. package/dest/msg_validators/attestation_validator/index.js +2 -0
  137. package/dest/msg_validators/index.d.ts +4 -0
  138. package/dest/msg_validators/index.d.ts.map +1 -0
  139. package/dest/msg_validators/index.js +3 -0
  140. package/dest/msg_validators/msg_seen_validator/msg_seen_validator.d.ts +10 -0
  141. package/dest/msg_validators/msg_seen_validator/msg_seen_validator.d.ts.map +1 -0
  142. package/dest/msg_validators/msg_seen_validator/msg_seen_validator.js +36 -0
  143. package/dest/msg_validators/proposal_validator/block_proposal_validator.d.ts +16 -0
  144. package/dest/msg_validators/proposal_validator/block_proposal_validator.d.ts.map +1 -0
  145. package/dest/msg_validators/proposal_validator/block_proposal_validator.js +14 -0
  146. package/dest/msg_validators/proposal_validator/checkpoint_proposal_validator.d.ts +16 -0
  147. package/dest/msg_validators/proposal_validator/checkpoint_proposal_validator.d.ts.map +1 -0
  148. package/dest/msg_validators/proposal_validator/checkpoint_proposal_validator.js +26 -0
  149. package/dest/msg_validators/proposal_validator/index.d.ts +4 -0
  150. package/dest/msg_validators/proposal_validator/index.d.ts.map +1 -0
  151. package/dest/msg_validators/proposal_validator/index.js +3 -0
  152. package/dest/msg_validators/proposal_validator/proposal_validator.d.ts +40 -0
  153. package/dest/msg_validators/proposal_validator/proposal_validator.d.ts.map +1 -0
  154. package/dest/msg_validators/proposal_validator/proposal_validator.js +186 -0
  155. package/dest/msg_validators/tx_validator/aggregate_tx_validator.d.ts +7 -0
  156. package/dest/msg_validators/tx_validator/aggregate_tx_validator.d.ts.map +1 -0
  157. package/dest/msg_validators/tx_validator/aggregate_tx_validator.js +25 -0
  158. package/dest/msg_validators/tx_validator/allowed_public_setup.d.ts +4 -0
  159. package/dest/msg_validators/tx_validator/allowed_public_setup.d.ts.map +1 -0
  160. package/dest/msg_validators/tx_validator/allowed_public_setup.js +31 -0
  161. package/dest/msg_validators/tx_validator/allowed_setup_helpers.d.ts +17 -0
  162. package/dest/msg_validators/tx_validator/allowed_setup_helpers.d.ts.map +1 -0
  163. package/dest/msg_validators/tx_validator/allowed_setup_helpers.js +24 -0
  164. package/dest/msg_validators/tx_validator/archive_cache.d.ts +14 -0
  165. package/dest/msg_validators/tx_validator/archive_cache.d.ts.map +1 -0
  166. package/dest/msg_validators/tx_validator/archive_cache.js +22 -0
  167. package/dest/msg_validators/tx_validator/block_header_validator.d.ts +25 -0
  168. package/dest/msg_validators/tx_validator/block_header_validator.d.ts.map +1 -0
  169. package/dest/msg_validators/tx_validator/block_header_validator.js +27 -0
  170. package/dest/msg_validators/tx_validator/cached_tx_validator.d.ts +15 -0
  171. package/dest/msg_validators/tx_validator/cached_tx_validator.d.ts.map +1 -0
  172. package/dest/msg_validators/tx_validator/cached_tx_validator.js +19 -0
  173. package/dest/msg_validators/tx_validator/contract_instance_validator.d.ts +9 -0
  174. package/dest/msg_validators/tx_validator/contract_instance_validator.d.ts.map +1 -0
  175. package/dest/msg_validators/tx_validator/contract_instance_validator.js +48 -0
  176. package/dest/msg_validators/tx_validator/data_validator.d.ts +9 -0
  177. package/dest/msg_validators/tx_validator/data_validator.d.ts.map +1 -0
  178. package/dest/msg_validators/tx_validator/data_validator.js +114 -0
  179. package/dest/msg_validators/tx_validator/double_spend_validator.d.ts +21 -0
  180. package/dest/msg_validators/tx_validator/double_spend_validator.d.ts.map +1 -0
  181. package/dest/msg_validators/tx_validator/double_spend_validator.js +36 -0
  182. package/dest/msg_validators/tx_validator/factory.d.ts +148 -0
  183. package/dest/msg_validators/tx_validator/factory.d.ts.map +1 -0
  184. package/dest/msg_validators/tx_validator/factory.js +302 -0
  185. package/dest/msg_validators/tx_validator/fee_payer_balance.d.ts +10 -0
  186. package/dest/msg_validators/tx_validator/fee_payer_balance.d.ts.map +1 -0
  187. package/dest/msg_validators/tx_validator/fee_payer_balance.js +24 -0
  188. package/dest/msg_validators/tx_validator/gas_limits_validator.d.ts +73 -0
  189. package/dest/msg_validators/tx_validator/gas_limits_validator.d.ts.map +1 -0
  190. package/dest/msg_validators/tx_validator/gas_limits_validator.js +107 -0
  191. package/dest/msg_validators/tx_validator/gas_validator.d.ts +65 -0
  192. package/dest/msg_validators/tx_validator/gas_validator.d.ts.map +1 -0
  193. package/dest/msg_validators/tx_validator/gas_validator.js +107 -0
  194. package/dest/msg_validators/tx_validator/index.d.ts +20 -0
  195. package/dest/msg_validators/tx_validator/index.d.ts.map +1 -0
  196. package/dest/msg_validators/tx_validator/index.js +19 -0
  197. package/dest/msg_validators/tx_validator/metadata_validator.d.ts +15 -0
  198. package/dest/msg_validators/tx_validator/metadata_validator.d.ts.map +1 -0
  199. package/dest/msg_validators/tx_validator/metadata_validator.js +63 -0
  200. package/dest/msg_validators/tx_validator/nullifier_cache.d.ts +14 -0
  201. package/dest/msg_validators/tx_validator/nullifier_cache.d.ts.map +1 -0
  202. package/dest/msg_validators/tx_validator/nullifier_cache.js +24 -0
  203. package/dest/msg_validators/tx_validator/phases_validator.d.ts +35 -0
  204. package/dest/msg_validators/tx_validator/phases_validator.d.ts.map +1 -0
  205. package/dest/msg_validators/tx_validator/phases_validator.js +141 -0
  206. package/dest/msg_validators/tx_validator/size_validator.d.ts +8 -0
  207. package/dest/msg_validators/tx_validator/size_validator.d.ts.map +1 -0
  208. package/dest/msg_validators/tx_validator/size_validator.js +23 -0
  209. package/dest/msg_validators/tx_validator/test_utils.d.ts +17 -0
  210. package/dest/msg_validators/tx_validator/test_utils.d.ts.map +1 -0
  211. package/dest/msg_validators/tx_validator/test_utils.js +22 -0
  212. package/dest/msg_validators/tx_validator/timestamp_validator.d.ts +30 -0
  213. package/dest/msg_validators/tx_validator/timestamp_validator.d.ts.map +1 -0
  214. package/dest/msg_validators/tx_validator/timestamp_validator.js +32 -0
  215. package/dest/msg_validators/tx_validator/tx_permitted_validator.d.ts +9 -0
  216. package/dest/msg_validators/tx_validator/tx_permitted_validator.d.ts.map +1 -0
  217. package/dest/msg_validators/tx_validator/tx_permitted_validator.js +24 -0
  218. package/dest/msg_validators/tx_validator/tx_proof_validator.d.ts +11 -0
  219. package/dest/msg_validators/tx_validator/tx_proof_validator.d.ts.map +1 -0
  220. package/dest/msg_validators/tx_validator/tx_proof_validator.js +28 -0
  221. package/dest/msg_validators/tx_validator/tx_validation_cache.d.ts +48 -0
  222. package/dest/msg_validators/tx_validator/tx_validation_cache.d.ts.map +1 -0
  223. package/dest/msg_validators/tx_validator/tx_validation_cache.js +68 -0
  224. package/dest/services/data_store.d.ts +27 -0
  225. package/dest/services/data_store.d.ts.map +1 -0
  226. package/dest/services/data_store.js +192 -0
  227. package/dest/services/discv5/discV5_service.d.ts +54 -0
  228. package/dest/services/discv5/discV5_service.d.ts.map +1 -0
  229. package/dest/services/discv5/discV5_service.js +337 -0
  230. package/dest/services/discv5/persisted_enr_store.d.ts +38 -0
  231. package/dest/services/discv5/persisted_enr_store.d.ts.map +1 -0
  232. package/dest/services/discv5/persisted_enr_store.js +145 -0
  233. package/dest/services/dummy_service.d.ts +150 -0
  234. package/dest/services/dummy_service.d.ts.map +1 -0
  235. package/dest/services/dummy_service.js +228 -0
  236. package/dest/services/encoding.d.ts +67 -0
  237. package/dest/services/encoding.d.ts.map +1 -0
  238. package/dest/services/encoding.js +152 -0
  239. package/dest/services/gossipsub/index.d.ts +3 -0
  240. package/dest/services/gossipsub/index.d.ts.map +1 -0
  241. package/dest/services/gossipsub/index.js +2 -0
  242. package/dest/services/gossipsub/scoring.d.ts +25 -0
  243. package/dest/services/gossipsub/scoring.d.ts.map +1 -0
  244. package/dest/services/gossipsub/scoring.js +27 -0
  245. package/dest/services/gossipsub/topic_score_params.d.ts +167 -0
  246. package/dest/services/gossipsub/topic_score_params.d.ts.map +1 -0
  247. package/dest/services/gossipsub/topic_score_params.js +336 -0
  248. package/dest/services/index.d.ts +8 -0
  249. package/dest/services/index.d.ts.map +1 -0
  250. package/dest/services/index.js +7 -0
  251. package/dest/services/libp2p/instrumentation.d.ts +25 -0
  252. package/dest/services/libp2p/instrumentation.d.ts.map +1 -0
  253. package/dest/services/libp2p/instrumentation.js +143 -0
  254. package/dest/services/libp2p/libp2p_service.d.ts +250 -0
  255. package/dest/services/libp2p/libp2p_service.d.ts.map +1 -0
  256. package/dest/services/libp2p/libp2p_service.js +1983 -0
  257. package/dest/services/peer-manager/interface.d.ts +23 -0
  258. package/dest/services/peer-manager/interface.d.ts.map +1 -0
  259. package/dest/services/peer-manager/interface.js +1 -0
  260. package/dest/services/peer-manager/metrics.d.ts +23 -0
  261. package/dest/services/peer-manager/metrics.d.ts.map +1 -0
  262. package/dest/services/peer-manager/metrics.js +71 -0
  263. package/dest/services/peer-manager/peer_manager.d.ts +202 -0
  264. package/dest/services/peer-manager/peer_manager.d.ts.map +1 -0
  265. package/dest/services/peer-manager/peer_manager.js +1015 -0
  266. package/dest/services/peer-manager/peer_scoring.d.ts +65 -0
  267. package/dest/services/peer-manager/peer_scoring.d.ts.map +1 -0
  268. package/dest/services/peer-manager/peer_scoring.js +239 -0
  269. package/dest/services/reqresp/batch-tx-requester/batch_tx_requester.d.ts +44 -0
  270. package/dest/services/reqresp/batch-tx-requester/batch_tx_requester.d.ts.map +1 -0
  271. package/dest/services/reqresp/batch-tx-requester/batch_tx_requester.js +534 -0
  272. package/dest/services/reqresp/batch-tx-requester/config.d.ts +17 -0
  273. package/dest/services/reqresp/batch-tx-requester/config.d.ts.map +1 -0
  274. package/dest/services/reqresp/batch-tx-requester/config.js +27 -0
  275. package/dest/services/reqresp/batch-tx-requester/interface.d.ts +50 -0
  276. package/dest/services/reqresp/batch-tx-requester/interface.d.ts.map +1 -0
  277. package/dest/services/reqresp/batch-tx-requester/interface.js +1 -0
  278. package/dest/services/reqresp/batch-tx-requester/missing_txs.d.ts +35 -0
  279. package/dest/services/reqresp/batch-tx-requester/missing_txs.d.ts.map +1 -0
  280. package/dest/services/reqresp/batch-tx-requester/missing_txs.js +136 -0
  281. package/dest/services/reqresp/batch-tx-requester/peer_collection.d.ts +62 -0
  282. package/dest/services/reqresp/batch-tx-requester/peer_collection.d.ts.map +1 -0
  283. package/dest/services/reqresp/batch-tx-requester/peer_collection.js +176 -0
  284. package/dest/services/reqresp/batch-tx-requester/tx_validator.d.ts +11 -0
  285. package/dest/services/reqresp/batch-tx-requester/tx_validator.d.ts.map +1 -0
  286. package/dest/services/reqresp/batch-tx-requester/tx_validator.js +7 -0
  287. package/dest/services/reqresp/config.d.ts +30 -0
  288. package/dest/services/reqresp/config.d.ts.map +1 -0
  289. package/dest/services/reqresp/config.js +45 -0
  290. package/dest/services/reqresp/connection-sampler/connection_sampler.d.ts +76 -0
  291. package/dest/services/reqresp/connection-sampler/connection_sampler.d.ts.map +1 -0
  292. package/dest/services/reqresp/connection-sampler/connection_sampler.js +251 -0
  293. package/dest/services/reqresp/constants.d.ts +12 -0
  294. package/dest/services/reqresp/constants.d.ts.map +1 -0
  295. package/dest/services/reqresp/constants.js +7 -0
  296. package/dest/services/reqresp/index.d.ts +7 -0
  297. package/dest/services/reqresp/index.d.ts.map +1 -0
  298. package/dest/services/reqresp/index.js +5 -0
  299. package/dest/services/reqresp/interface.d.ts +174 -0
  300. package/dest/services/reqresp/interface.d.ts.map +1 -0
  301. package/dest/services/reqresp/interface.js +107 -0
  302. package/dest/services/reqresp/metrics.d.ts +16 -0
  303. package/dest/services/reqresp/metrics.d.ts.map +1 -0
  304. package/dest/services/reqresp/metrics.js +50 -0
  305. package/dest/services/reqresp/protocols/auth.d.ts +43 -0
  306. package/dest/services/reqresp/protocols/auth.d.ts.map +1 -0
  307. package/dest/services/reqresp/protocols/auth.js +71 -0
  308. package/dest/services/reqresp/protocols/block_txs/bitvector.d.ts +35 -0
  309. package/dest/services/reqresp/protocols/block_txs/bitvector.d.ts.map +1 -0
  310. package/dest/services/reqresp/protocols/block_txs/bitvector.js +88 -0
  311. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.d.ts +13 -0
  312. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.d.ts.map +1 -0
  313. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.js +60 -0
  314. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.d.ts +75 -0
  315. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.d.ts.map +1 -0
  316. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.js +139 -0
  317. package/dest/services/reqresp/protocols/block_txs/index.d.ts +4 -0
  318. package/dest/services/reqresp/protocols/block_txs/index.d.ts.map +1 -0
  319. package/dest/services/reqresp/protocols/block_txs/index.js +3 -0
  320. package/dest/services/reqresp/protocols/goodbye.d.ts +49 -0
  321. package/dest/services/reqresp/protocols/goodbye.d.ts.map +1 -0
  322. package/dest/services/reqresp/protocols/goodbye.js +87 -0
  323. package/dest/services/reqresp/protocols/index.d.ts +10 -0
  324. package/dest/services/reqresp/protocols/index.d.ts.map +1 -0
  325. package/dest/services/reqresp/protocols/index.js +8 -0
  326. package/dest/services/reqresp/protocols/ping.d.ts +7 -0
  327. package/dest/services/reqresp/protocols/ping.d.ts.map +1 -0
  328. package/dest/services/reqresp/protocols/ping.js +7 -0
  329. package/dest/services/reqresp/protocols/status.d.ts +42 -0
  330. package/dest/services/reqresp/protocols/status.d.ts.map +1 -0
  331. package/dest/services/reqresp/protocols/status.js +78 -0
  332. package/dest/services/reqresp/protocols/tx.d.ts +29 -0
  333. package/dest/services/reqresp/protocols/tx.d.ts.map +1 -0
  334. package/dest/services/reqresp/protocols/tx.js +66 -0
  335. package/dest/services/reqresp/rate-limiter/index.d.ts +2 -0
  336. package/dest/services/reqresp/rate-limiter/index.d.ts.map +1 -0
  337. package/dest/services/reqresp/rate-limiter/index.js +1 -0
  338. package/dest/services/reqresp/rate-limiter/rate_limiter.d.ts +105 -0
  339. package/dest/services/reqresp/rate-limiter/rate_limiter.d.ts.map +1 -0
  340. package/dest/services/reqresp/rate-limiter/rate_limiter.js +194 -0
  341. package/dest/services/reqresp/rate-limiter/rate_limits.d.ts +3 -0
  342. package/dest/services/reqresp/rate-limiter/rate_limits.d.ts.map +1 -0
  343. package/dest/services/reqresp/rate-limiter/rate_limits.js +64 -0
  344. package/dest/services/reqresp/reqresp.d.ts +107 -0
  345. package/dest/services/reqresp/reqresp.d.ts.map +1 -0
  346. package/dest/services/reqresp/reqresp.js +887 -0
  347. package/dest/services/reqresp/status.d.ts +37 -0
  348. package/dest/services/reqresp/status.d.ts.map +1 -0
  349. package/dest/services/reqresp/status.js +58 -0
  350. package/dest/services/service.d.ts +168 -0
  351. package/dest/services/service.d.ts.map +1 -0
  352. package/dest/services/service.js +5 -0
  353. package/dest/services/tx_collection/config.d.ts +25 -0
  354. package/dest/services/tx_collection/config.d.ts.map +1 -0
  355. package/dest/services/tx_collection/config.js +59 -0
  356. package/dest/services/tx_collection/file_store_tx_collection.d.ts +37 -0
  357. package/dest/services/tx_collection/file_store_tx_collection.d.ts.map +1 -0
  358. package/dest/services/tx_collection/file_store_tx_collection.js +127 -0
  359. package/dest/services/tx_collection/file_store_tx_source.d.ts +38 -0
  360. package/dest/services/tx_collection/file_store_tx_source.d.ts.map +1 -0
  361. package/dest/services/tx_collection/file_store_tx_source.js +100 -0
  362. package/dest/services/tx_collection/index.d.ts +4 -0
  363. package/dest/services/tx_collection/index.d.ts.map +1 -0
  364. package/dest/services/tx_collection/index.js +3 -0
  365. package/dest/services/tx_collection/instrumentation.d.ts +10 -0
  366. package/dest/services/tx_collection/instrumentation.d.ts.map +1 -0
  367. package/dest/services/tx_collection/instrumentation.js +30 -0
  368. package/dest/services/tx_collection/request_tracker.d.ts +53 -0
  369. package/dest/services/tx_collection/request_tracker.d.ts.map +1 -0
  370. package/dest/services/tx_collection/request_tracker.js +84 -0
  371. package/dest/services/tx_collection/tx_collection.d.ts +104 -0
  372. package/dest/services/tx_collection/tx_collection.d.ts.map +1 -0
  373. package/dest/services/tx_collection/tx_collection.js +356 -0
  374. package/dest/services/tx_collection/tx_collection_sink.d.ts +40 -0
  375. package/dest/services/tx_collection/tx_collection_sink.d.ts.map +1 -0
  376. package/dest/services/tx_collection/tx_collection_sink.js +108 -0
  377. package/dest/services/tx_collection/tx_source.d.ts +24 -0
  378. package/dest/services/tx_collection/tx_source.d.ts.map +1 -0
  379. package/dest/services/tx_collection/tx_source.js +56 -0
  380. package/dest/services/tx_file_store/config.d.ts +16 -0
  381. package/dest/services/tx_file_store/config.d.ts.map +1 -0
  382. package/dest/services/tx_file_store/config.js +22 -0
  383. package/dest/services/tx_file_store/index.d.ts +4 -0
  384. package/dest/services/tx_file_store/index.d.ts.map +1 -0
  385. package/dest/services/tx_file_store/index.js +3 -0
  386. package/dest/services/tx_file_store/instrumentation.d.ts +15 -0
  387. package/dest/services/tx_file_store/instrumentation.d.ts.map +1 -0
  388. package/dest/services/tx_file_store/instrumentation.js +29 -0
  389. package/dest/services/tx_file_store/tx_file_store.d.ts +46 -0
  390. package/dest/services/tx_file_store/tx_file_store.d.ts.map +1 -0
  391. package/dest/services/tx_file_store/tx_file_store.js +142 -0
  392. package/dest/services/tx_provider.d.ts +53 -0
  393. package/dest/services/tx_provider.d.ts.map +1 -0
  394. package/dest/services/tx_provider.js +223 -0
  395. package/dest/services/tx_provider_instrumentation.d.ts +16 -0
  396. package/dest/services/tx_provider_instrumentation.d.ts.map +1 -0
  397. package/dest/services/tx_provider_instrumentation.js +34 -0
  398. package/dest/test-helpers/generate-peer-id-private-keys.d.ts +7 -0
  399. package/dest/test-helpers/generate-peer-id-private-keys.d.ts.map +1 -0
  400. package/dest/test-helpers/generate-peer-id-private-keys.js +13 -0
  401. package/dest/test-helpers/get-ports.d.ts +7 -0
  402. package/dest/test-helpers/get-ports.d.ts.map +1 -0
  403. package/dest/test-helpers/get-ports.js +8 -0
  404. package/dest/test-helpers/index.d.ts +9 -0
  405. package/dest/test-helpers/index.d.ts.map +1 -0
  406. package/dest/test-helpers/index.js +8 -0
  407. package/dest/test-helpers/make-enrs.d.ts +16 -0
  408. package/dest/test-helpers/make-enrs.d.ts.map +1 -0
  409. package/dest/test-helpers/make-enrs.js +31 -0
  410. package/dest/test-helpers/make-test-p2p-clients.d.ts +63 -0
  411. package/dest/test-helpers/make-test-p2p-clients.d.ts.map +1 -0
  412. package/dest/test-helpers/make-test-p2p-clients.js +140 -0
  413. package/dest/test-helpers/mock-pubsub.d.ts +109 -0
  414. package/dest/test-helpers/mock-pubsub.d.ts.map +1 -0
  415. package/dest/test-helpers/mock-pubsub.js +244 -0
  416. package/dest/test-helpers/mock-tx-helpers.d.ts +12 -0
  417. package/dest/test-helpers/mock-tx-helpers.d.ts.map +1 -0
  418. package/dest/test-helpers/mock-tx-helpers.js +19 -0
  419. package/dest/test-helpers/reqresp-nodes.d.ts +68 -0
  420. package/dest/test-helpers/reqresp-nodes.d.ts.map +1 -0
  421. package/dest/test-helpers/reqresp-nodes.js +240 -0
  422. package/dest/test-helpers/test_tx_provider.d.ts +42 -0
  423. package/dest/test-helpers/test_tx_provider.d.ts.map +1 -0
  424. package/dest/test-helpers/test_tx_provider.js +44 -0
  425. package/dest/test-helpers/testbench-utils.d.ts +164 -0
  426. package/dest/test-helpers/testbench-utils.d.ts.map +1 -0
  427. package/dest/test-helpers/testbench-utils.js +401 -0
  428. package/dest/testbench/p2p_client_testbench_worker.d.ts +26 -0
  429. package/dest/testbench/p2p_client_testbench_worker.d.ts.map +1 -0
  430. package/dest/testbench/p2p_client_testbench_worker.js +364 -0
  431. package/dest/testbench/parse_log_file.d.ts +2 -0
  432. package/dest/testbench/parse_log_file.d.ts.map +1 -0
  433. package/dest/testbench/parse_log_file.js +131 -0
  434. package/dest/testbench/testbench.d.ts +2 -0
  435. package/dest/testbench/testbench.d.ts.map +1 -0
  436. package/dest/testbench/testbench.js +62 -0
  437. package/dest/testbench/worker_client_manager.d.ts +102 -0
  438. package/dest/testbench/worker_client_manager.d.ts.map +1 -0
  439. package/dest/testbench/worker_client_manager.js +492 -0
  440. package/dest/types/index.d.ts +34 -0
  441. package/dest/types/index.d.ts.map +1 -0
  442. package/dest/types/index.js +30 -0
  443. package/dest/util.d.ts +66 -0
  444. package/dest/util.d.ts.map +1 -0
  445. package/dest/util.js +167 -0
  446. package/dest/versioning.d.ts +9 -0
  447. package/dest/versioning.d.ts.map +1 -0
  448. package/dest/versioning.js +17 -0
  449. package/package.json +131 -0
  450. package/src/bootstrap/bootstrap.ts +178 -0
  451. package/src/client/factory.ts +282 -0
  452. package/src/client/index.ts +3 -0
  453. package/src/client/interface.ts +264 -0
  454. package/src/client/p2p_client.ts +846 -0
  455. package/src/client/test/p2p_client.batch_tx_requester.bench.README.md +197 -0
  456. package/src/config.ts +787 -0
  457. package/src/enr/generate-enr.ts +71 -0
  458. package/src/enr/index.ts +1 -0
  459. package/src/errors/attestation-pool.error.ts +13 -0
  460. package/src/errors/p2p-service.error.ts +11 -0
  461. package/src/errors/reqresp.error.ts +29 -0
  462. package/src/errors/tx-pool.error.ts +12 -0
  463. package/src/index.ts +11 -0
  464. package/src/mem_pools/attestation_pool/attestation_pool.ts +648 -0
  465. package/src/mem_pools/attestation_pool/attestation_pool_test_suite.ts +896 -0
  466. package/src/mem_pools/attestation_pool/index.ts +9 -0
  467. package/src/mem_pools/attestation_pool/mocks.ts +56 -0
  468. package/src/mem_pools/index.ts +3 -0
  469. package/src/mem_pools/instrumentation.ts +160 -0
  470. package/src/mem_pools/interface.ts +10 -0
  471. package/src/mem_pools/tx_pool_v2/README.md +283 -0
  472. package/src/mem_pools/tx_pool_v2/archive/index.ts +1 -0
  473. package/src/mem_pools/tx_pool_v2/archive/tx_archive.ts +130 -0
  474. package/src/mem_pools/tx_pool_v2/deleted_pool.ts +321 -0
  475. package/src/mem_pools/tx_pool_v2/eviction/eviction_manager.ts +160 -0
  476. package/src/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.ts +120 -0
  477. package/src/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.ts +126 -0
  478. package/src/mem_pools/tx_pool_v2/eviction/index.ts +28 -0
  479. package/src/mem_pools/tx_pool_v2/eviction/insufficient_fee_per_gas_eviction_rule.ts +67 -0
  480. package/src/mem_pools/tx_pool_v2/eviction/interfaces.ts +219 -0
  481. package/src/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.ts +72 -0
  482. package/src/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.ts +99 -0
  483. package/src/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.ts +90 -0
  484. package/src/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.ts +99 -0
  485. package/src/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.ts +32 -0
  486. package/src/mem_pools/tx_pool_v2/index.ts +12 -0
  487. package/src/mem_pools/tx_pool_v2/instrumentation.ts +96 -0
  488. package/src/mem_pools/tx_pool_v2/interfaces.ts +274 -0
  489. package/src/mem_pools/tx_pool_v2/tx_metadata.ts +349 -0
  490. package/src/mem_pools/tx_pool_v2/tx_pool_bench_metrics.ts +77 -0
  491. package/src/mem_pools/tx_pool_v2/tx_pool_indices.ts +465 -0
  492. package/src/mem_pools/tx_pool_v2/tx_pool_v2.ts +300 -0
  493. package/src/mem_pools/tx_pool_v2/tx_pool_v2_impl.ts +1242 -0
  494. package/src/msg_validators/attestation_validator/README.md +49 -0
  495. package/src/msg_validators/attestation_validator/attestation_validator.ts +116 -0
  496. package/src/msg_validators/attestation_validator/fisherman_attestation_validator.ts +107 -0
  497. package/src/msg_validators/attestation_validator/index.ts +2 -0
  498. package/src/msg_validators/index.ts +3 -0
  499. package/src/msg_validators/msg_seen_validator/msg_seen_validator.ts +36 -0
  500. package/src/msg_validators/proposal_validator/README.md +123 -0
  501. package/src/msg_validators/proposal_validator/block_proposal_validator.ts +37 -0
  502. package/src/msg_validators/proposal_validator/checkpoint_proposal_validator.ts +49 -0
  503. package/src/msg_validators/proposal_validator/index.ts +3 -0
  504. package/src/msg_validators/proposal_validator/proposal_validator.ts +198 -0
  505. package/src/msg_validators/tx_validator/README.md +137 -0
  506. package/src/msg_validators/tx_validator/aggregate_tx_validator.ts +24 -0
  507. package/src/msg_validators/tx_validator/allowed_public_setup.ts +30 -0
  508. package/src/msg_validators/tx_validator/allowed_setup_helpers.ts +31 -0
  509. package/src/msg_validators/tx_validator/archive_cache.ts +28 -0
  510. package/src/msg_validators/tx_validator/block_header_validator.ts +38 -0
  511. package/src/msg_validators/tx_validator/cached_tx_validator.ts +31 -0
  512. package/src/msg_validators/tx_validator/contract_instance_validator.ts +56 -0
  513. package/src/msg_validators/tx_validator/data_validator.ts +173 -0
  514. package/src/msg_validators/tx_validator/double_spend_validator.ts +46 -0
  515. package/src/msg_validators/tx_validator/factory.ts +490 -0
  516. package/src/msg_validators/tx_validator/fee_payer_balance.ts +44 -0
  517. package/src/msg_validators/tx_validator/gas_limits_validator.ts +148 -0
  518. package/src/msg_validators/tx_validator/gas_validator.ts +149 -0
  519. package/src/msg_validators/tx_validator/index.ts +19 -0
  520. package/src/msg_validators/tx_validator/metadata_validator.ts +104 -0
  521. package/src/msg_validators/tx_validator/nullifier_cache.ts +30 -0
  522. package/src/msg_validators/tx_validator/phases_validator.ts +173 -0
  523. package/src/msg_validators/tx_validator/size_validator.ts +22 -0
  524. package/src/msg_validators/tx_validator/test_utils.ts +43 -0
  525. package/src/msg_validators/tx_validator/timestamp_validator.ts +61 -0
  526. package/src/msg_validators/tx_validator/tx_permitted_validator.ts +22 -0
  527. package/src/msg_validators/tx_validator/tx_proof_validator.ts +26 -0
  528. package/src/msg_validators/tx_validator/tx_validation_cache.ts +100 -0
  529. package/src/services/data_store.ts +229 -0
  530. package/src/services/discv5/discV5_service.ts +413 -0
  531. package/src/services/discv5/persisted_enr_store.ts +157 -0
  532. package/src/services/dummy_service.ts +320 -0
  533. package/src/services/encoding.ts +170 -0
  534. package/src/services/gossipsub/README.md +663 -0
  535. package/src/services/gossipsub/index.ts +2 -0
  536. package/src/services/gossipsub/scoring.ts +37 -0
  537. package/src/services/gossipsub/topic_score_params.ts +477 -0
  538. package/src/services/index.ts +7 -0
  539. package/src/services/libp2p/instrumentation.ts +147 -0
  540. package/src/services/libp2p/libp2p_service.ts +1972 -0
  541. package/src/services/peer-manager/interface.ts +28 -0
  542. package/src/services/peer-manager/metrics.ts +90 -0
  543. package/src/services/peer-manager/peer_manager.ts +1221 -0
  544. package/src/services/peer-manager/peer_scoring.ts +265 -0
  545. package/src/services/reqresp/README.md +194 -0
  546. package/src/services/reqresp/batch-tx-requester/README.md +344 -0
  547. package/src/services/reqresp/batch-tx-requester/batch_tx_requester.ts +659 -0
  548. package/src/services/reqresp/batch-tx-requester/config.ts +40 -0
  549. package/src/services/reqresp/batch-tx-requester/interface.ts +60 -0
  550. package/src/services/reqresp/batch-tx-requester/missing_txs.ts +167 -0
  551. package/src/services/reqresp/batch-tx-requester/peer_collection.ts +248 -0
  552. package/src/services/reqresp/batch-tx-requester/tx_validator.ts +24 -0
  553. package/src/services/reqresp/config.ts +69 -0
  554. package/src/services/reqresp/connection-sampler/connection_sampler.ts +287 -0
  555. package/src/services/reqresp/constants.ts +14 -0
  556. package/src/services/reqresp/index.ts +6 -0
  557. package/src/services/reqresp/interface.ts +241 -0
  558. package/src/services/reqresp/metrics.ts +68 -0
  559. package/src/services/reqresp/protocols/auth.ts +83 -0
  560. package/src/services/reqresp/protocols/block_txs/bitvector.ts +107 -0
  561. package/src/services/reqresp/protocols/block_txs/block_txs_handler.ts +79 -0
  562. package/src/services/reqresp/protocols/block_txs/block_txs_reqresp.ts +170 -0
  563. package/src/services/reqresp/protocols/block_txs/index.ts +3 -0
  564. package/src/services/reqresp/protocols/goodbye.ts +102 -0
  565. package/src/services/reqresp/protocols/index.ts +9 -0
  566. package/src/services/reqresp/protocols/ping.ts +8 -0
  567. package/src/services/reqresp/protocols/status.ts +123 -0
  568. package/src/services/reqresp/protocols/tx.ts +76 -0
  569. package/src/services/reqresp/rate-limiter/index.ts +1 -0
  570. package/src/services/reqresp/rate-limiter/rate_limiter.ts +240 -0
  571. package/src/services/reqresp/rate-limiter/rate_limits.ts +65 -0
  572. package/src/services/reqresp/reqresp.ts +675 -0
  573. package/src/services/reqresp/status.ts +68 -0
  574. package/src/services/service.ts +219 -0
  575. package/src/services/tx_collection/config.ts +89 -0
  576. package/src/services/tx_collection/file_store_tx_collection.ts +153 -0
  577. package/src/services/tx_collection/file_store_tx_source.ts +129 -0
  578. package/src/services/tx_collection/index.ts +3 -0
  579. package/src/services/tx_collection/instrumentation.ts +35 -0
  580. package/src/services/tx_collection/request_tracker.ts +127 -0
  581. package/src/services/tx_collection/tx_collection.ts +467 -0
  582. package/src/services/tx_collection/tx_collection_sink.ts +124 -0
  583. package/src/services/tx_collection/tx_source.ts +61 -0
  584. package/src/services/tx_file_store/config.ts +37 -0
  585. package/src/services/tx_file_store/index.ts +3 -0
  586. package/src/services/tx_file_store/instrumentation.ts +42 -0
  587. package/src/services/tx_file_store/tx_file_store.ts +163 -0
  588. package/src/services/tx_provider.ts +237 -0
  589. package/src/services/tx_provider_instrumentation.ts +54 -0
  590. package/src/test-helpers/generate-peer-id-private-keys.ts +15 -0
  591. package/src/test-helpers/get-ports.ts +8 -0
  592. package/src/test-helpers/index.ts +8 -0
  593. package/src/test-helpers/make-enrs.ts +42 -0
  594. package/src/test-helpers/make-test-p2p-clients.ts +213 -0
  595. package/src/test-helpers/mock-pubsub.ts +325 -0
  596. package/src/test-helpers/mock-tx-helpers.ts +24 -0
  597. package/src/test-helpers/reqresp-nodes.ts +327 -0
  598. package/src/test-helpers/test_tx_provider.ts +68 -0
  599. package/src/test-helpers/testbench-utils.ts +465 -0
  600. package/src/testbench/README.md +20 -0
  601. package/src/testbench/p2p_client_testbench_worker.ts +553 -0
  602. package/src/testbench/parse_log_file.ts +174 -0
  603. package/src/testbench/testbench.ts +66 -0
  604. package/src/testbench/worker_client_manager.ts +621 -0
  605. package/src/types/index.ts +38 -0
  606. package/src/util.ts +230 -0
  607. package/src/versioning.ts +26 -0
@@ -0,0 +1,1242 @@
1
+ import { BlockNumber, SlotNumber } from '@aztec-labs/foundation/branded-types';
2
+ import { FifoSet } from '@aztec-labs/foundation/fifo-set';
3
+ import type { Logger } from '@aztec-labs/foundation/log';
4
+ import type { DateProvider } from '@aztec-labs/foundation/timer';
5
+ import type { AztecAsyncKVStore, AztecAsyncMap } from '@aztec-labs/kv-store';
6
+ import { ProtocolContractAddress } from '@aztec-labs/protocol-contracts';
7
+ import { computeFeePayerBalanceStorageSlot } from '@aztec-labs/protocol-contracts/fee-juice';
8
+ import { AztecAddress } from '@aztec-labs/stdlib/aztec-address';
9
+ import type { L2Block, L2BlockId, L2BlockSource } from '@aztec-labs/stdlib/block';
10
+ import type { WorldStateSynchronizer } from '@aztec-labs/stdlib/interfaces/server';
11
+ import { DatabasePublicStateSource } from '@aztec-labs/stdlib/trees';
12
+ import { BlockHeader, Tx, TxHash, type TxValidator } from '@aztec-labs/stdlib/tx';
13
+ import type { TelemetryClient } from '@aztec-labs/telemetry-client';
14
+
15
+ import { TxArchive } from './archive/index.js';
16
+ import { DeletedPool } from './deleted_pool.js';
17
+ import {
18
+ EvictionManager,
19
+ FeePayerBalanceEvictionRule,
20
+ FeePayerBalancePreAddRule,
21
+ InsufficientFeePerGasEvictionRule,
22
+ InvalidTxsAfterMiningRule,
23
+ InvalidTxsAfterReorgRule,
24
+ LowPriorityEvictionRule,
25
+ LowPriorityPreAddRule,
26
+ NullifierConflictRule,
27
+ type PoolOperations,
28
+ type PreAddContext,
29
+ type PreAddPoolAccess,
30
+ TxPoolRejectionCode,
31
+ type TxPoolRejectionError,
32
+ } from './eviction/index.js';
33
+ import { TxPoolV2Instrumentation } from './instrumentation.js';
34
+ import {
35
+ type AddTxsResult,
36
+ DEFAULT_TX_POOL_V2_CONFIG,
37
+ type PoolReadAccess,
38
+ type TxPoolV2Config,
39
+ type TxPoolV2Dependencies,
40
+ } from './interfaces.js';
41
+ import { type TxMetaData, type TxState, buildTxMetaData, checkNullifierConflict } from './tx_metadata.js';
42
+ import { TxPoolIndices } from './tx_pool_indices.js';
43
+
44
+ /**
45
+ * Maximum number of finalized txs to archive or hard-delete per serial-queue item. Bounds both
46
+ * peak memory (~23k txs/epoch at 10 TPS would otherwise OOM the node) and, more importantly, how
47
+ * long finalization occupies the pool's serial queue per item: gossip tx validation waits on that
48
+ * queue, so each item must stay well under the gossipsub mcache eviction window.
49
+ */
50
+ export const FINALIZE_BLOCK_CHUNK_SIZE = 16;
51
+
52
+ /**
53
+ * Callbacks for the implementation to notify the outer class about events and metrics.
54
+ */
55
+ /** A tx that has just transitioned to mined, with the time it spent in the pool. */
56
+ export interface MinedTxInfo {
57
+ txHash: string;
58
+ /** Wall-clock ms from receipt into the pool to being marked mined. Undefined when the
59
+ * receive time is unknown (e.g. a tx hydrated from the DB on restart, receivedAt === 0). */
60
+ minedDelayMs?: number;
61
+ }
62
+
63
+ export interface TxPoolV2Callbacks {
64
+ onTxsAdded: (txs: Tx[], opts: { source?: string }) => void;
65
+ onTxsRemoved: (txHashes: string[] | bigint[]) => void;
66
+ onTxsMined: (minedTxs: MinedTxInfo[]) => void;
67
+ }
68
+
69
+ /**
70
+ * Implementation of TxPoolV2 logic.
71
+ *
72
+ * This class contains all the actual transaction pool logic.
73
+ */
74
+ export class TxPoolV2Impl {
75
+ // === Persistence ===
76
+ #store: AztecAsyncKVStore;
77
+ /** Tx data without its proof. Proofs live in #proofsDB so a tx can be read without loading its proof. */
78
+ #txsDB: AztecAsyncMap<string, Buffer>;
79
+ /** Tx proofs, keyed by tx hash. Written and deleted in lockstep with #txsDB. */
80
+ #proofsDB: AztecAsyncMap<string, Buffer>;
81
+
82
+ // === Dependencies ===
83
+ #l2BlockSource: L2BlockSource;
84
+ #worldStateSynchronizer: WorldStateSynchronizer;
85
+ #createTxValidator: TxPoolV2Dependencies['createTxValidator'];
86
+ #checkAllowedSetupCalls: TxPoolV2Dependencies['checkAllowedSetupCalls'];
87
+
88
+ // === In-Memory Indices ===
89
+ #indices: TxPoolIndices = new TxPoolIndices();
90
+
91
+ // === Config & Services ===
92
+ #config: TxPoolV2Config;
93
+ #archive: TxArchive;
94
+ #deletedPool: DeletedPool;
95
+ #evictionManager: EvictionManager;
96
+ #dateProvider: DateProvider;
97
+ #instrumentation: TxPoolV2Instrumentation;
98
+ #evictedTxHashes: FifoSet<string>;
99
+ #log: Logger;
100
+ #callbacks: TxPoolV2Callbacks;
101
+
102
+ constructor(
103
+ store: AztecAsyncKVStore,
104
+ archiveStore: AztecAsyncKVStore,
105
+ deps: TxPoolV2Dependencies,
106
+ callbacks: TxPoolV2Callbacks,
107
+ telemetry: TelemetryClient,
108
+ config: Partial<TxPoolV2Config> = {},
109
+ dateProvider: DateProvider,
110
+ log: Logger,
111
+ ) {
112
+ this.#store = store;
113
+ this.#txsDB = store.openMap('txs');
114
+ this.#proofsDB = store.openMap('tx_proofs');
115
+
116
+ this.#l2BlockSource = deps.l2BlockSource;
117
+ this.#worldStateSynchronizer = deps.worldStateSynchronizer;
118
+ this.#createTxValidator = deps.createTxValidator;
119
+ this.#checkAllowedSetupCalls = deps.checkAllowedSetupCalls;
120
+
121
+ this.#config = { ...DEFAULT_TX_POOL_V2_CONFIG, ...config };
122
+ this.#evictedTxHashes = FifoSet.withLimit<string>(this.#config.evictedTxCacheSize);
123
+ this.#archive = new TxArchive(archiveStore, this.#config.archivedTxLimit, log);
124
+ this.#deletedPool = new DeletedPool(store, txHashStr => this.#deleteTxData(txHashStr), log);
125
+ this.#dateProvider = dateProvider;
126
+ this.#instrumentation = new TxPoolV2Instrumentation(telemetry, () => this.#indices.getTotalMetadataBytes());
127
+ this.#log = log;
128
+ this.#callbacks = callbacks;
129
+
130
+ // Setup eviction manager with rules
131
+ this.#evictionManager = new EvictionManager(this.#createPoolOperations(), log);
132
+
133
+ // Pre-add rules (run during addPendingTxs) - work with TxMetaData
134
+ this.#evictionManager.registerPreAddRule(new NullifierConflictRule());
135
+ this.#evictionManager.registerPreAddRule(new FeePayerBalancePreAddRule());
136
+ this.#evictionManager.registerPreAddRule(
137
+ new LowPriorityPreAddRule({ maxPoolSize: this.#config.maxPendingTxCount }),
138
+ );
139
+
140
+ // Post-event eviction rules (run after events to check ALL pending txs)
141
+ this.#evictionManager.registerRule(new InvalidTxsAfterMiningRule());
142
+ this.#evictionManager.registerRule(new InsufficientFeePerGasEvictionRule(deps.blockMinFeesProvider));
143
+ this.#evictionManager.registerRule(new InvalidTxsAfterReorgRule(deps.worldStateSynchronizer));
144
+ this.#evictionManager.registerRule(new FeePayerBalanceEvictionRule(deps.worldStateSynchronizer));
145
+ // LowPriorityEvictionRule handles cases where txs become pending via prepareForSlot (unprotect)
146
+ // The pre-add rule handles the addPendingTxs case, but post-event is needed for unprotect
147
+ this.#evictionManager.registerRule(new LowPriorityEvictionRule({ maxPoolSize: this.#config.maxPendingTxCount }));
148
+ }
149
+
150
+ // ============================================================================
151
+ // PUBLIC IMPLEMENTATION METHODS
152
+ // ============================================================================
153
+
154
+ /**
155
+ * Hydrates the in-memory state from the database on startup.
156
+ * Pipeline: Load → Check Mined Status → Partition → Validate Non-Mined → Rebuild Pending Pool → Delete Invalid
157
+ *
158
+ * Note: Protected status is lost on restart. All non-mined txs are rebuilt as pending
159
+ * by running pre-add rules to resolve nullifier conflicts, balance checks, and pool size limits.
160
+ */
161
+ async hydrateFromDatabase(): Promise<void> {
162
+ // Step 0: Hydrate deleted pool state
163
+ await this.#deletedPool.hydrateFromDatabase();
164
+
165
+ // Step 1: Stream txs from DB, building metadata and mined status one at a time.
166
+ const minedMetas: TxMetaData[] = [];
167
+ const pendingMetas: TxMetaData[] = [];
168
+ const deserializationErrors: string[] = [];
169
+
170
+ for await (const [txHashStr, buffer] of this.#txsDB.entriesAsync()) {
171
+ // Skip soft-deleted transactions - they stay in DB but not in indices
172
+ if (this.#deletedPool.isSoftDeleted(txHashStr)) {
173
+ continue;
174
+ }
175
+
176
+ let meta: TxMetaData;
177
+ let txEffect: Awaited<ReturnType<L2BlockSource['getTxEffect']>>;
178
+ try {
179
+ const tx = Tx.fromBuffer(buffer);
180
+ // Resolve allowed-setup-calls and the tx effect concurrently
181
+ // getTxEffect failures are non-fatal (we just treat the tx as not-yet-mined), so
182
+ // its rejection is swallowed before the Promise.all so it can't fail-fast the batch.
183
+ const txEffectPromise = this.#l2BlockSource.getTxEffect(tx.getTxHash()).catch(err => {
184
+ this.#log.warn(`Failed to check mined status for tx ${txHashStr}`, { err });
185
+ return undefined;
186
+ });
187
+ const [allowedSetupCalls, fetchedTxEffect] = await Promise.all([
188
+ this.#checkAllowedSetupCalls(tx),
189
+ txEffectPromise,
190
+ ]);
191
+ meta = await buildTxMetaData(tx, allowedSetupCalls);
192
+ txEffect = fetchedTxEffect;
193
+ } catch (err) {
194
+ this.#log.warn(`Failed to deserialize tx ${txHashStr}, deleting`, { err });
195
+ deserializationErrors.push(txHashStr);
196
+ continue;
197
+ }
198
+
199
+ if (txEffect) {
200
+ meta.minedL2BlockId = {
201
+ number: txEffect.l2BlockNumber,
202
+ hash: txEffect.l2BlockHash.toString(),
203
+ };
204
+ }
205
+
206
+ if (meta.minedL2BlockId !== undefined) {
207
+ minedMetas.push(meta);
208
+ } else {
209
+ pendingMetas.push(meta);
210
+ }
211
+ }
212
+
213
+ // Step 2: Validate non-mined transactions
214
+ const { valid, invalid } = await this.#revalidateMetadata(pendingMetas, 'on startup');
215
+
216
+ // Step 3: Populate mined indices (these don't need conflict resolution)
217
+ for (const meta of minedMetas) {
218
+ this.#indices.addMined(meta);
219
+ }
220
+
221
+ // Step 4: Rebuild pending pool by running pre-add rules for each tx
222
+ // This resolves nullifier conflicts, fee payer balance issues, and pool size limits
223
+ const { rejected } = await this.#rebuildPendingPool(valid);
224
+
225
+ // Step 5: Delete invalid and rejected txs from DB only (indices were never populated for these)
226
+ const toDelete = [...deserializationErrors, ...invalid, ...rejected];
227
+ if (toDelete.length === 0) {
228
+ return;
229
+ }
230
+ await this.#store.transactionAsync(async () => {
231
+ for (const txHashStr of toDelete) {
232
+ await this.#deleteTxData(txHashStr);
233
+ }
234
+ });
235
+ this.#log.info(`Deleted ${toDelete.length} invalid/rejected transactions on startup`, { txHashes: toDelete });
236
+ }
237
+
238
+ async addPendingTxs(txs: Tx[], opts: { source?: string; feeComparisonOnly?: boolean }): Promise<AddTxsResult> {
239
+ const accepted: TxHash[] = [];
240
+ const ignored: TxHash[] = [];
241
+ const rejected: TxHash[] = [];
242
+ const errors = new Map<string, TxPoolRejectionError>();
243
+ const acceptedPending = new Set<string>();
244
+
245
+ // Phase 1: Pre-compute all throwable I/O outside the transaction.
246
+ // If any pre-computation throws, the entire call fails before mutations happen.
247
+ const precomputed = new Map<string, { meta: TxMetaData; minedBlockId: L2BlockId | undefined; isValid: boolean }>();
248
+
249
+ const validator = await this.#createTxValidator();
250
+
251
+ for (const tx of txs) {
252
+ const txHash = tx.getTxHash();
253
+ const txHashStr = txHash.toString();
254
+
255
+ const meta = await buildTxMetaData(tx);
256
+ const minedBlockId = await this.#getMinedBlockId(txHash);
257
+
258
+ // Validate non-mined txs (mined and pre-protected txs bypass validation inside the transaction)
259
+ let isValid = true;
260
+ if (!minedBlockId) {
261
+ isValid = await this.#validateMeta(meta, validator);
262
+ }
263
+
264
+ precomputed.set(txHashStr, { meta, minedBlockId, isValid });
265
+ }
266
+
267
+ // Phase 2: Apply mutations inside the transaction using only pre-computed results,
268
+ // in-memory reads, and buffered DB writes. Nothing here can throw an unhandled exception.
269
+ const poolAccess = this.#createPreAddPoolAccess();
270
+ const preAddContext: PreAddContext | undefined =
271
+ opts.feeComparisonOnly !== undefined
272
+ ? { feeComparisonOnly: opts.feeComparisonOnly, priceBumpPercentage: this.#config.priceBumpPercentage }
273
+ : undefined;
274
+
275
+ await this.#store.transactionAsync(async () => {
276
+ for (const tx of txs) {
277
+ const txHash = tx.getTxHash();
278
+ const txHashStr = txHash.toString();
279
+
280
+ // Skip duplicates
281
+ if (this.#indices.has(txHashStr)) {
282
+ ignored.push(txHash);
283
+ continue;
284
+ }
285
+
286
+ const { meta, minedBlockId, isValid } = precomputed.get(txHashStr)!;
287
+ const preProtectedSlot = this.#indices.getProtectionSlot(txHashStr);
288
+
289
+ if (minedBlockId) {
290
+ // Already mined - add directly (protection already set if pre-protected)
291
+ await this.#addTx(tx, { mined: minedBlockId }, opts, meta);
292
+ accepted.push(txHash);
293
+ } else if (preProtectedSlot !== undefined) {
294
+ // Pre-protected and not mined - add as protected (bypass validation)
295
+ await this.#addTx(tx, { protected: preProtectedSlot }, opts, meta);
296
+ accepted.push(txHash);
297
+ } else if (!isValid) {
298
+ // Failed pre-computed validation
299
+ rejected.push(txHash);
300
+ } else {
301
+ // Regular pending tx - run pre-add rules using pre-computed metadata
302
+ const result = await this.#tryAddRegularPendingTx(
303
+ tx,
304
+ meta,
305
+ opts,
306
+ poolAccess,
307
+ acceptedPending,
308
+ ignored,
309
+ errors,
310
+ preAddContext,
311
+ );
312
+ if (result.status === 'accepted') {
313
+ acceptedPending.add(txHashStr);
314
+ } else {
315
+ ignored.push(txHash);
316
+ }
317
+ }
318
+ }
319
+
320
+ // Run post-add eviction rules for pending txs (inside transaction for atomicity)
321
+ if (acceptedPending.size > 0) {
322
+ const feePayers = Array.from(acceptedPending).map(txHash => this.#indices.getMetadata(txHash)!.feePayer);
323
+ const uniqueFeePayers = new Set<string>(feePayers);
324
+ await this.#evictionManager.evictAfterNewTxs(Array.from(acceptedPending), [...uniqueFeePayers]);
325
+ }
326
+ });
327
+
328
+ // Build final accepted list for pending txs (excludes intra-batch evictions)
329
+ for (const txHashStr of acceptedPending) {
330
+ accepted.push(TxHash.fromString(txHashStr));
331
+ }
332
+
333
+ // Record metrics
334
+ if (ignored.length > 0) {
335
+ this.#instrumentation.recordIgnored(ignored.length);
336
+ }
337
+ if (rejected.length > 0) {
338
+ this.#instrumentation.recordRejected(rejected.length);
339
+ }
340
+
341
+ return { accepted, ignored, rejected, ...(errors.size > 0 ? { errors } : {}) };
342
+ }
343
+
344
+ /** Adds a validated pending tx, running pre-add rules and evicting conflicts. */
345
+ async #tryAddRegularPendingTx(
346
+ tx: Tx,
347
+ precomputedMeta: TxMetaData,
348
+ opts: { source?: string },
349
+ poolAccess: PreAddPoolAccess,
350
+ acceptedPending: Set<string>,
351
+ ignored: TxHash[],
352
+ errors: Map<string, TxPoolRejectionError>,
353
+ preAddContext?: PreAddContext,
354
+ ): Promise<{ status: 'accepted' | 'ignored' }> {
355
+ const txHashStr = tx.getTxHash().toString();
356
+
357
+ // Run pre-add rules
358
+ const preAddResult = await this.#evictionManager.runPreAddRules(precomputedMeta, poolAccess, preAddContext);
359
+
360
+ if (preAddResult.shouldIgnore) {
361
+ this.#log.debug(`Ignoring tx ${txHashStr}: ${preAddResult.reason?.message ?? 'unknown reason'}`);
362
+ if (preAddResult.reason && preAddResult.reason.code !== TxPoolRejectionCode.INTERNAL_ERROR) {
363
+ errors.set(txHashStr, preAddResult.reason);
364
+ }
365
+ return { status: 'ignored' };
366
+ }
367
+
368
+ // Evict conflicts, grouped by rule name for metrics
369
+ if (preAddResult.evictions && preAddResult.evictions.length > 0) {
370
+ const byReason = new Map<string, string[]>();
371
+ for (const { txHash: evictHash, reason } of preAddResult.evictions) {
372
+ const group = byReason.get(reason);
373
+ if (group) {
374
+ group.push(evictHash);
375
+ } else {
376
+ byReason.set(reason, [evictHash]);
377
+ }
378
+ }
379
+ for (const [reason, hashes] of byReason) {
380
+ await this.#evictTxs(hashes, reason);
381
+ }
382
+ for (const evictHashStr of preAddResult.txHashesToEvict) {
383
+ this.#log.debug(`Evicted tx ${evictHashStr} due to higher-fee tx ${txHashStr}`, {
384
+ evictedTxHash: evictHashStr,
385
+ replacementTxHash: txHashStr,
386
+ });
387
+ if (acceptedPending.has(evictHashStr)) {
388
+ // Evicted tx was from this batch - mark as ignored in result
389
+ acceptedPending.delete(evictHashStr);
390
+ ignored.push(TxHash.fromString(evictHashStr));
391
+ }
392
+ }
393
+ }
394
+
395
+ // Randomly drop the transaction for testing purposes (report as accepted so it propagates)
396
+ if (this.#config.dropTransactionsProbability > 0 && Math.random() < this.#config.dropTransactionsProbability) {
397
+ this.#log.debug(`Dropping tx ${txHashStr} (simulated drop for testing)`);
398
+ return { status: 'accepted' };
399
+ }
400
+
401
+ // Add the transaction
402
+ await this.#addTx(tx, 'pending', opts, precomputedMeta);
403
+ return { status: 'accepted' };
404
+ }
405
+
406
+ async canAddPendingTx(tx: Tx): Promise<'accepted' | 'ignored'> {
407
+ const txHashStr = tx.getTxHash().toString();
408
+
409
+ // Check if already in pool
410
+ if (this.#indices.has(txHashStr)) {
411
+ this.#log.verbose(`canAddPendingTx: tx ${txHashStr} already in pool`);
412
+ return 'ignored';
413
+ }
414
+
415
+ // Build metadata and check pre-add rules
416
+ const meta = await buildTxMetaData(tx);
417
+ const poolAccess = this.#createPreAddPoolAccess();
418
+ const preAddResult = await this.#evictionManager.runPreAddRules(meta, poolAccess);
419
+
420
+ if (preAddResult.shouldIgnore) {
421
+ this.#log.verbose(`canAddPendingTx: tx ${txHashStr} ignored by pre-add rule`, {
422
+ reason: preAddResult.reason?.message ?? 'no reason provided',
423
+ });
424
+ return 'ignored';
425
+ }
426
+ return 'accepted';
427
+ }
428
+
429
+ async addProtectedTxs(txs: Tx[], block: BlockHeader, opts: { source?: string }): Promise<void> {
430
+ const slotNumber = block.globalVariables.slotNumber;
431
+
432
+ // Precompute setup-call allow-list flags outside the store transaction
433
+ const allowedFlags = await Promise.all(txs.map(tx => this.#checkAllowedSetupCalls(tx)));
434
+
435
+ await this.#store.transactionAsync(async () => {
436
+ for (let i = 0; i < txs.length; i++) {
437
+ const tx = txs[i];
438
+ const txHash = tx.getTxHash();
439
+ const txHashStr = txHash.toString();
440
+ const isNew = !this.#indices.has(txHashStr);
441
+ const minedBlockId = await this.#getMinedBlockId(txHash);
442
+
443
+ if (isNew) {
444
+ const meta = await buildTxMetaData(tx, allowedFlags[i]);
445
+ // New tx - add as mined or protected (callback emitted by #addTx)
446
+ if (minedBlockId) {
447
+ await this.#addTx(tx, { mined: minedBlockId }, opts, meta);
448
+ this.#indices.setProtection(txHashStr, slotNumber);
449
+ } else {
450
+ await this.#addTx(tx, { protected: slotNumber }, opts, meta);
451
+ }
452
+ } else {
453
+ // Existing tx - update protection and mined status
454
+ this.#indices.updateProtection(txHashStr, slotNumber);
455
+ if (minedBlockId) {
456
+ const meta = this.#indices.getMetadata(txHashStr)!;
457
+ this.#indices.markAsMined(meta, minedBlockId);
458
+ }
459
+ }
460
+ }
461
+ });
462
+ }
463
+
464
+ async protectTxs(txHashes: TxHash[], block: BlockHeader): Promise<TxHash[]> {
465
+ const slotNumber = block.globalVariables.slotNumber;
466
+ const missing: TxHash[] = [];
467
+ let softDeletedHits = 0;
468
+ let missingPreviouslyEvicted = 0;
469
+
470
+ await this.#store.transactionAsync(async () => {
471
+ for (const txHash of txHashes) {
472
+ const txHashStr = txHash.toString();
473
+
474
+ if (this.#indices.has(txHashStr)) {
475
+ // Update protection for existing tx
476
+ this.#indices.updateProtection(txHashStr, slotNumber);
477
+ } else if (this.#deletedPool.isSoftDeleted(txHashStr)) {
478
+ // Resurrect soft-deleted tx as protected. Load the proof too: #addTx rewrites both entries, so re-adding
479
+ // a proofless tx would wipe the stored proof.
480
+ const buffer = await this.#txsDB.getAsync(txHashStr);
481
+ if (buffer) {
482
+ const tx = await this.#loadTxWithProof(txHashStr, buffer);
483
+ await this.#addTx(tx, { protected: slotNumber });
484
+ softDeletedHits++;
485
+ } else {
486
+ // Data missing despite soft-delete flag — treat as truly missing
487
+ this.#indices.setProtection(txHashStr, slotNumber);
488
+ missing.push(txHash);
489
+ }
490
+ } else {
491
+ // Truly missing — pre-record protection for tx we don't have yet
492
+ this.#indices.setProtection(txHashStr, slotNumber);
493
+ missing.push(txHash);
494
+ if (this.#evictedTxHashes.has(txHashStr)) {
495
+ missingPreviouslyEvicted++;
496
+ }
497
+ }
498
+ }
499
+ });
500
+
501
+ // Record metrics
502
+ if (softDeletedHits > 0) {
503
+ this.#instrumentation.recordSoftDeletedHits(softDeletedHits);
504
+ }
505
+ if (missing.length > 0) {
506
+ this.#log.debug(`protectTxs missing tx hashes: ${missing.map(h => h.toString()).join(', ')}`);
507
+ this.#instrumentation.recordMissingOnProtect(missing.length);
508
+ }
509
+ if (missingPreviouslyEvicted > 0) {
510
+ this.#instrumentation.recordMissingPreviouslyEvicted(missingPreviouslyEvicted);
511
+ }
512
+
513
+ this.#log.info(
514
+ `Protected ${txHashes.length} txs, missing: ${missing.length}, soft-deleted hits: ${softDeletedHits}`,
515
+ );
516
+
517
+ return missing;
518
+ }
519
+
520
+ async addMinedTxs(txs: Tx[], block: BlockHeader, opts: { source?: string }): Promise<void> {
521
+ // Step 1: Build block ID
522
+ const blockId = await this.#buildBlockId(block);
523
+
524
+ await this.#store.transactionAsync(async () => {
525
+ for (const tx of txs) {
526
+ const txHashStr = tx.getTxHash().toString();
527
+ const existingMeta = this.#indices.getMetadata(txHashStr);
528
+
529
+ if (existingMeta) {
530
+ // Mark existing tx as mined
531
+ this.#indices.markAsMined(existingMeta, blockId);
532
+ } else {
533
+ // Add new mined tx (callback emitted by #addTx)
534
+ await this.#addTx(tx, { mined: blockId }, opts);
535
+ }
536
+ await this.#deletedPool.clearIfMinedHigher(txHashStr, blockId.number);
537
+ }
538
+ });
539
+ }
540
+
541
+ async handleMinedBlock(block: L2Block): Promise<void> {
542
+ // Step 1: Build block ID
543
+ const blockId = await this.#buildBlockId(block.header);
544
+
545
+ // Step 2: Extract tx hashes and nullifiers directly from the block
546
+ const txHashes = block.body.txEffects.map(tx => tx.txHash);
547
+ const nullifiers = block.body.txEffects.flatMap(tx => tx.nullifiers.map(n => n.toString()));
548
+
549
+ // Step 3: Collect fee payers from txs we have in the pool (for balance-based eviction)
550
+ const feePayers: string[] = [];
551
+ const found: TxMetaData[] = [];
552
+ for (const txHash of txHashes) {
553
+ const meta = this.#indices.getMetadata(txHash.toString());
554
+ if (meta) {
555
+ feePayers.push(meta.feePayer);
556
+ found.push(meta);
557
+ }
558
+ }
559
+
560
+ await this.#store.transactionAsync(async () => {
561
+ // Step 4: Mark txs as mined (only those we have in the pool)
562
+ for (const meta of found) {
563
+ this.#indices.markAsMined(meta, blockId);
564
+ await this.#deletedPool.clearIfMinedHigher(meta.txHash, blockId.number);
565
+ }
566
+
567
+ // Step 5: Run post-event eviction rules (inside transaction for atomicity)
568
+ await this.#evictionManager.evictAfterNewBlock(block.header, nullifiers, feePayers);
569
+ });
570
+
571
+ if (found.length > 0) {
572
+ // receivedAt is 0 for txs hydrated from the DB on restart (true receive time lost) — leave
573
+ // their delay undefined so the metric isn't polluted by epoch-sized values.
574
+ const now = this.#dateProvider.now();
575
+ this.#callbacks.onTxsMined(
576
+ found.map(m => ({
577
+ txHash: m.txHash,
578
+ minedDelayMs: m.receivedAt > 0 ? now - m.receivedAt : undefined,
579
+ })),
580
+ );
581
+ }
582
+
583
+ this.#log.info(`Marked ${found.length} txs as mined in block ${blockId.number}`);
584
+ }
585
+
586
+ async prepareForSlot(slotNumber: SlotNumber): Promise<void> {
587
+ await this.#store.transactionAsync(async () => {
588
+ // Step 0: Clean up slot-deleted txs from previous slots
589
+ await this.#deletedPool.cleanupSlotDeleted(slotNumber);
590
+
591
+ // Step 1: Find expired protected txs
592
+ const expiredProtected = this.#indices.findExpiredProtectedTxs(slotNumber);
593
+
594
+ // Step 2: Clear protection for all expired entries (including those without metadata)
595
+ this.#indices.clearProtection(expiredProtected);
596
+
597
+ // Step 3: Filter to only txs that have metadata and are not mined
598
+ const txsToRestore = this.#indices.filterRestorable(expiredProtected);
599
+ if (txsToRestore.length === 0) {
600
+ this.#log.debug(`Preparing for slot ${slotNumber}, no txs to unprotect`);
601
+ return;
602
+ }
603
+
604
+ this.#log.info(`Preparing for slot ${slotNumber}: unprotecting ${txsToRestore.length} txs`);
605
+ await this.#restoreUnprotectedToPending(txsToRestore, 'during prepareForSlot');
606
+ });
607
+ }
608
+
609
+ async unprotectTxs(txHashes: TxHash[], slotNumber: SlotNumber): Promise<void> {
610
+ const hashStrs = txHashes.map(h => h.toString());
611
+
612
+ await this.#store.transactionAsync(async () => {
613
+ // Only release entries still recorded at this exact slot. A tx that another, still-live proposal
614
+ // raised to a higher slot via updateProtection must keep that protection. Mined txs have no
615
+ // protection entry and so are never matched here.
616
+ const matching = this.#indices.findProtectedTxsAtSlot(hashStrs, slotNumber);
617
+ if (matching.length === 0) {
618
+ this.#log.debug(`Unprotecting txs for slot ${slotNumber}: no matching protections to release`);
619
+ return;
620
+ }
621
+
622
+ this.#indices.clearProtection(matching);
623
+
624
+ const txsToRestore = this.#indices.filterRestorable(matching);
625
+ if (txsToRestore.length === 0) {
626
+ return;
627
+ }
628
+
629
+ this.#log.info(`Unprotecting ${txsToRestore.length} txs from failed proposal at slot ${slotNumber}`);
630
+ await this.#restoreUnprotectedToPending(txsToRestore, 'during unprotectTxs');
631
+ });
632
+ }
633
+
634
+ /**
635
+ * Returns just-unprotected txs to the pending pool: revalidates them, resolves nullifier
636
+ * conflicts, deletes losers, then enforces the pool size limit. Must run inside a store
637
+ * transaction; callers clear the protection entries before invoking.
638
+ */
639
+ async #restoreUnprotectedToPending(txsToRestore: TxMetaData[], context: string): Promise<void> {
640
+ // Step 1: Validate for pending pool
641
+ const { valid, invalid } = await this.#revalidateMetadata(txsToRestore, context);
642
+
643
+ // Step 2: Resolve nullifier conflicts and add winners to pending indices
644
+ const { added, toEvict } = this.#applyNullifierConflictResolution(valid);
645
+
646
+ // Step 3: Delete invalid txs and evict conflict losers
647
+ await this.#deleteTxsBatch(invalid);
648
+ await this.#evictTxs(toEvict, 'NullifierConflict');
649
+
650
+ // Step 4: Run eviction rules (enforce pool size limit)
651
+ if (added.length > 0) {
652
+ const feePayers = added.map(meta => meta.feePayer);
653
+ const uniqueFeePayers = new Set<string>(feePayers);
654
+ await this.#evictionManager.evictAfterNewTxs(
655
+ added.map(m => m.txHash),
656
+ [...uniqueFeePayers],
657
+ );
658
+ }
659
+ }
660
+
661
+ async handlePrunedBlocks(latestBlock: L2BlockId, options?: { deleteAllTxs?: boolean }): Promise<void> {
662
+ // Step 1: Find transactions mined after the prune point
663
+ const txsToUnmine = this.#indices.findTxsMinedAfter(latestBlock.number);
664
+ if (txsToUnmine.length === 0) {
665
+ this.#log.debug(`No transactions to un-mine for prune to block ${latestBlock.number}`);
666
+ return;
667
+ }
668
+
669
+ this.#log.info(`Handling prune to block ${latestBlock.number}: un-mining ${txsToUnmine.length} txs`);
670
+
671
+ await this.#store.transactionAsync(async () => {
672
+ // Step 2: Mark ALL un-mined txs with their original mined block number
673
+ // This ensures they get soft-deleted if removed later, and only hard-deleted
674
+ // when their original mined block is finalized
675
+ await this.#deletedPool.markFromPrunedBlock(
676
+ txsToUnmine.map(m => ({
677
+ txHash: m.txHash,
678
+ minedAtBlock: BlockNumber(m.minedL2BlockId!.number),
679
+ })),
680
+ );
681
+
682
+ // Step 3: Unmine - clear mined status from metadata
683
+ for (const meta of txsToUnmine) {
684
+ this.#indices.markAsUnmined(meta);
685
+ }
686
+
687
+ // If deleteAllTxs is set (epoch prune), delete all un-mined txs and return early
688
+ if (options?.deleteAllTxs) {
689
+ const allTxHashes = txsToUnmine.map(m => m.txHash);
690
+ await this.#deleteTxsBatch(allTxHashes);
691
+ this.#log.info(
692
+ `Handled prune to block ${latestBlock.number} with deleteAllTxs: deleted ${allTxHashes.length} txs`,
693
+ );
694
+ return;
695
+ }
696
+
697
+ // Step 4: Filter out protected txs (they'll be handled by prepareForSlot)
698
+ const unprotectedTxs = this.#indices.filterUnprotected(txsToUnmine);
699
+
700
+ // Step 5: Validate for pending pool
701
+ const { valid, invalid } = await this.#revalidateMetadata(unprotectedTxs, 'during handlePrunedBlocks');
702
+
703
+ // Step 6: Resolve nullifier conflicts and add winners to pending indices
704
+ const { toEvict } = this.#applyNullifierConflictResolution(valid);
705
+
706
+ // Step 7: Delete invalid txs and evict conflict losers
707
+ await this.#deleteTxsBatch(invalid);
708
+ await this.#evictTxs(toEvict, 'NullifierConflict');
709
+
710
+ this.#log.info(
711
+ `Handled prune to block ${latestBlock.number}: ${valid.length} txs restored to pending, ${invalid.length} invalid, ${toEvict.length} evicted due to nullifier conflicts`,
712
+ { txHashesRestored: valid.map(m => m.txHash), txHashesInvalid: invalid, txHashesEvicted: toEvict },
713
+ );
714
+
715
+ // Step 8: Run eviction rules for ALL pending txs (not just restored ones)
716
+ // This handles cases like existing pending txs with invalid fee payer balances
717
+ await this.#evictionManager.evictAfterChainPrune(latestBlock.number);
718
+ });
719
+ }
720
+
721
+ async handleFailedExecution(txHashes: TxHash[]): Promise<void> {
722
+ await this.#store.transactionAsync(async () => {
723
+ await this.#deleteTxsBatch(txHashes.map(h => h.toString()));
724
+ });
725
+
726
+ this.#log.info(`Deleted ${txHashes.length} failed txs`, { txHashes: txHashes.map(h => h.toString()) });
727
+ }
728
+
729
+ /**
730
+ * Resolves what a finalized block event should process: the cutoff block and the mined txs at or
731
+ * before it. The wrapper feeds the result to archiveFinalizedTxs / finalizeTxs in chunks, each as
732
+ * its own serial-queue item, so gossip-driven pool operations can interleave with finalization
733
+ * instead of stalling behind an entire epoch's worth of tx processing.
734
+ */
735
+ async prepareFinalization(block: BlockHeader): Promise<{ cutoffBlock: BlockNumber; txHashes: string[] }> {
736
+ // Hold finalized txs for a configurable margin behind the finalized tip so a prover still
737
+ // proving an epoch with already-finalized blocks isn't starved of its txs. 0 deletes at the finalized tip.
738
+ const cutoffBlock = await this.#finalizationCutoffBlock(block);
739
+ return { cutoffBlock, txHashes: this.#indices.findTxsMinedAtOrBefore(cutoffBlock) };
740
+ }
741
+
742
+ /**
743
+ * Copies the given finalized txs into the archive. The pool stores txs proof-stripped, which is
744
+ * exactly the archive format, so buffers are copied as-is without deserialization.
745
+ */
746
+ async archiveFinalizedTxs(txHashes: string[]): Promise<void> {
747
+ if (!this.#archive.isEnabled()) {
748
+ return;
749
+ }
750
+ const entries: { txHash: string; buffer: Buffer }[] = [];
751
+ for (const txHash of txHashes) {
752
+ const buffer = await this.#txsDB.getAsync(txHash);
753
+ if (buffer) {
754
+ entries.push({ txHash, buffer });
755
+ }
756
+ }
757
+ await this.#archive.archiveTxBuffers(entries);
758
+ }
759
+
760
+ /**
761
+ * Deletes a batch of finalized mined txs from the active pool. Callers may invoke this in
762
+ * chunks: a crash between chunks leaves some finalized txs mined, and the next finalized-block
763
+ * event lists and deletes them again (the operation is idempotent), so per-chunk atomicity is
764
+ * sufficient. Since other pool operations may interleave between the finalization plan being
765
+ * computed and this call, each tx is re-checked to still be mined at or before the cutoff.
766
+ */
767
+ async deleteFinalizedTxs(txHashes: string[], cutoffBlock: BlockNumber): Promise<void> {
768
+ const stillFinalized = txHashes.filter(txHash => {
769
+ const minedBlock = this.#indices.getMetadata(txHash)?.minedL2BlockId?.number;
770
+ return minedBlock !== undefined && minedBlock <= cutoffBlock;
771
+ });
772
+ if (stillFinalized.length === 0) {
773
+ return;
774
+ }
775
+ await this.#store.transactionAsync(async () => {
776
+ await this.#deleteTxsBatch(stillFinalized);
777
+ });
778
+ }
779
+
780
+ /** Finalizes soft-deleted txs up to the cutoff and logs the completed finalization. */
781
+ async completeFinalization(
782
+ txHashes: string[],
783
+ cutoffBlock: BlockNumber,
784
+ finalizedBlockNumber: BlockNumber,
785
+ ): Promise<void> {
786
+ await this.#store.transactionAsync(async () => {
787
+ await this.#deletedPool.finalizeBlock(cutoffBlock);
788
+ });
789
+
790
+ if (txHashes.length > 0) {
791
+ this.#log.info(`Finalized ${txHashes.length} mined txs from blocks up to ${cutoffBlock}`, {
792
+ txHashes,
793
+ finalizedBlockNumber,
794
+ cutoffBlock,
795
+ });
796
+ }
797
+ }
798
+
799
+ /**
800
+ * Resolves the block up to which finalized txs may be deleted, given `keepFinalizedTxsForSlots`.
801
+ * With a margin of 0 this is just the finalized block. Otherwise we keep txs whose block is within
802
+ * the margin (in slots) of the finalized tip: take the target slot `finalizedSlot - margin`, find the
803
+ * latest checkpoint at or before it with a single reverse range query (`limit: 1`), and use that
804
+ * checkpoint's last block as the cutoff. This rounds to a checkpoint boundary, so it can retain slightly
805
+ * more than the configured margin but never less, and never deletes past the finalized block.
806
+ */
807
+ async #finalizationCutoffBlock(block: BlockHeader): Promise<BlockNumber> {
808
+ const keepSlots = this.#config.keepFinalizedTxsForSlots;
809
+ if (keepSlots <= 0) {
810
+ return block.globalVariables.blockNumber;
811
+ }
812
+
813
+ // The goal here really is to ensure we keep transactions long enough for them to be proven.
814
+ // So we could be smart and calculate the number of slots until the end of the proof submission window.
815
+ // Our approach here is a lot simpler however and we just keep transactions for the configured number
816
+ // of slots past L1 finalisation. This means we may keep transactions in the mined pool for longer
817
+ // than strictly necessary.
818
+ const targetSlot = block.getSlot() - keepSlots;
819
+ if (targetSlot < 0) {
820
+ // The margin reaches past genesis: keep everything.
821
+ return BlockNumber(0);
822
+ }
823
+
824
+ const [checkpoint] = await this.#l2BlockSource.getCheckpointsData({
825
+ fromSlot: SlotNumber(targetSlot),
826
+ limit: 1,
827
+ reverse: true,
828
+ });
829
+ // No checkpoint at or before the target slot (e.g. early chain): keep everything.
830
+ return checkpoint ? BlockNumber(checkpoint.startBlock + checkpoint.blockCount - 1) : BlockNumber(0);
831
+ }
832
+
833
+ // === Query Methods ===
834
+
835
+ async getTxByHash(txHash: TxHash, opts: { includeProof?: boolean } = {}): Promise<Tx | undefined> {
836
+ const txHashStr = txHash.toString();
837
+ const buffer = await this.#txsDB.getAsync(txHashStr);
838
+ if (!buffer) {
839
+ return undefined;
840
+ }
841
+ return opts.includeProof === false ? Tx.fromBuffer(buffer) : this.#loadTxWithProof(txHashStr, buffer);
842
+ }
843
+
844
+ async getTxsByHash(txHashes: TxHash[], opts: { includeProof?: boolean } = {}): Promise<(Tx | undefined)[]> {
845
+ const results: (Tx | undefined)[] = [];
846
+ for (const h of txHashes) {
847
+ results.push(await this.getTxByHash(h, opts));
848
+ }
849
+ return results;
850
+ }
851
+
852
+ /** Deserializes a tx blob loaded from #txsDB together with its separately-stored proof. */
853
+ async #loadTxWithProof(txHashStr: string, buffer: Buffer): Promise<Tx> {
854
+ const proofBuffer = await this.#proofsDB.getAsync(txHashStr);
855
+ if (!proofBuffer) {
856
+ // #addTx always writes a proof entry (an empty proof serializes to a 4-byte sentinel), so a missing entry
857
+ // means the blob/proof invariant is broken. Return the proofless tx but flag it, since a consumer that needs
858
+ // the proof (eg serving peers) would otherwise fail far away from the root cause.
859
+ this.#log.warn(`Missing stored proof for tx ${txHashStr}`, { txHash: txHashStr });
860
+ return Tx.fromBuffer(buffer);
861
+ }
862
+ return Tx.fromBuffers(buffer, proofBuffer);
863
+ }
864
+
865
+ hasTxs(txHashes: TxHash[]): boolean[] {
866
+ return txHashes.map(h => {
867
+ const hashStr = h.toString();
868
+ return this.#indices.has(hashStr) || this.#deletedPool.isSoftDeleted(hashStr);
869
+ });
870
+ }
871
+
872
+ getTxStatus(txHash: TxHash): TxState | undefined {
873
+ const txHashStr = txHash.toString();
874
+ const meta = this.#indices.getMetadata(txHashStr);
875
+ if (meta) {
876
+ return this.#indices.getTxState(meta);
877
+ }
878
+ // Check if soft-deleted
879
+ if (this.#deletedPool.isSoftDeleted(txHashStr)) {
880
+ return 'deleted';
881
+ }
882
+ return undefined;
883
+ }
884
+
885
+ getPendingTxHashes(): TxHash[] {
886
+ return [...this.#indices.iteratePendingByPriority('desc')].map(hash => TxHash.fromString(hash));
887
+ }
888
+
889
+ getEligiblePendingTxHashes(): TxHash[] {
890
+ const maxReceivedAt = this.#dateProvider.now() - this.#config.minTxPoolAgeMs;
891
+ return [...this.#indices.iterateEligiblePendingByPriority('desc', maxReceivedAt)].map(hash =>
892
+ TxHash.fromString(hash),
893
+ );
894
+ }
895
+
896
+ getPendingTxCount(): number {
897
+ return this.#indices.getPendingTxCount();
898
+ }
899
+
900
+ hasEligiblePendingTxs(minCount: number): boolean {
901
+ const maxReceivedAt = this.#dateProvider.now() - this.#config.minTxPoolAgeMs;
902
+ return this.#indices.hasEligiblePendingTxs(maxReceivedAt, minCount);
903
+ }
904
+
905
+ getMinedTxHashes(): [TxHash, L2BlockId][] {
906
+ return this.#indices.getMinedTxs().map(([hash, blockId]) => [TxHash.fromString(hash), blockId]);
907
+ }
908
+
909
+ getMinedTxCount(): number {
910
+ let count = 0;
911
+ for (const [, meta] of this.#indices.iterateMetadata()) {
912
+ if (meta.minedL2BlockId !== undefined) {
913
+ count++;
914
+ }
915
+ }
916
+ return count;
917
+ }
918
+
919
+ isEmpty(): boolean {
920
+ return this.#indices.isEmpty();
921
+ }
922
+
923
+ getTxCount(): number {
924
+ return this.#indices.getTxCount();
925
+ }
926
+
927
+ getArchivedTxByHash(txHash: TxHash): Promise<Tx | undefined> {
928
+ return this.#archive.getTxByHash(txHash);
929
+ }
930
+
931
+ getLowestPriorityPending(limit: number): TxHash[] {
932
+ return this.#indices.getLowestPriorityPending(limit).map(h => TxHash.fromString(h));
933
+ }
934
+
935
+ // === Configuration ===
936
+
937
+ updateConfig(config: Partial<TxPoolV2Config>): void {
938
+ if (config.maxPendingTxCount !== undefined) {
939
+ this.#config.maxPendingTxCount = config.maxPendingTxCount;
940
+ }
941
+ if (config.archivedTxLimit !== undefined) {
942
+ this.#config.archivedTxLimit = config.archivedTxLimit;
943
+ this.#archive.updateLimit(config.archivedTxLimit);
944
+ }
945
+ if (config.minTxPoolAgeMs !== undefined) {
946
+ this.#config.minTxPoolAgeMs = config.minTxPoolAgeMs;
947
+ }
948
+ if (config.keepFinalizedTxsForSlots !== undefined) {
949
+ this.#config.keepFinalizedTxsForSlots = config.keepFinalizedTxsForSlots;
950
+ }
951
+ // Update eviction rules with new config
952
+ this.#evictionManager.updateConfig(config);
953
+ }
954
+
955
+ // === Pool Read Access ===
956
+
957
+ getPoolReadAccess(): PoolReadAccess {
958
+ return {
959
+ getMetadata: (txHash: string) => this.#indices.getMetadata(txHash),
960
+ getTxHashByNullifier: (nullifier: string) => this.#indices.getTxHashByNullifier(nullifier),
961
+ getTxHashesByFeePayer: (feePayer: string) => this.#indices.getTxHashesByFeePayer(feePayer),
962
+ getPendingTxCount: () => this.#indices.getPendingTxCount(),
963
+ };
964
+ }
965
+
966
+ // === Metrics ===
967
+
968
+ countTxs(): {
969
+ pending: number;
970
+ protected: number;
971
+ mined: number;
972
+ softDeleted: number;
973
+ totalMetadataBytes: number;
974
+ } {
975
+ return {
976
+ ...this.#indices.countTxs(),
977
+ softDeleted: this.#deletedPool.getSoftDeletedCount(),
978
+ };
979
+ }
980
+
981
+ // ============================================================================
982
+ // PRIVATE HELPERS - Transaction Management
983
+ // ============================================================================
984
+
985
+ /**
986
+ * Adds a new transaction to the pool with the specified state.
987
+ * Emits onTxsAdded callback immediately after DB write.
988
+ */
989
+ async #addTx(
990
+ tx: Tx,
991
+ state: 'pending' | { protected: SlotNumber } | { mined: L2BlockId },
992
+ opts: { source?: string } = {},
993
+ precomputedMeta?: TxMetaData,
994
+ ): Promise<TxMetaData> {
995
+ const txHashStr = tx.getTxHash().toString();
996
+ const meta = precomputedMeta ?? (await buildTxMetaData(tx));
997
+ meta.receivedAt = this.#dateProvider.now();
998
+
999
+ await this.#txsDB.set(txHashStr, tx.withoutProof().toBuffer());
1000
+ await this.#proofsDB.set(txHashStr, tx.chonkProof.toBuffer());
1001
+ await this.#deletedPool.clearSoftDeleted(txHashStr);
1002
+ this.#callbacks.onTxsAdded([tx], opts);
1003
+
1004
+ if (state === 'pending') {
1005
+ this.#indices.addPending(meta);
1006
+ } else if ('protected' in state) {
1007
+ this.#indices.addProtected(meta, state.protected);
1008
+ } else {
1009
+ meta.minedL2BlockId = state.mined;
1010
+ this.#indices.addMined(meta);
1011
+ }
1012
+
1013
+ const stateStr = typeof state === 'string' ? state : Object.keys(state)[0];
1014
+ this.#log.debug(`Added tx ${txHashStr} as ${stateStr}`, {
1015
+ eventName: 'tx-added-to-pool',
1016
+ txHash: txHashStr,
1017
+ state: stateStr,
1018
+ source: opts.source,
1019
+ });
1020
+
1021
+ return meta;
1022
+ }
1023
+
1024
+ /**
1025
+ * Deletes a transaction from both indices and DB.
1026
+ * Emits onTxsRemoved callback immediately after DB delete.
1027
+ */
1028
+ /**
1029
+ * Deletes a transaction from the pool.
1030
+ * Delegates to DeletedPool which decides soft vs hard delete based on whether
1031
+ * the tx is from a pruned block.
1032
+ */
1033
+ async #deleteTx(txHashStr: string): Promise<void> {
1034
+ this.#indices.remove(txHashStr);
1035
+ this.#callbacks.onTxsRemoved([txHashStr]);
1036
+ await this.#deletedPool.deleteTx(txHashStr);
1037
+ }
1038
+
1039
+ /** Hard-deletes a tx's stored data (tx blob and proof) from the DB. */
1040
+ async #deleteTxData(txHashStr: string): Promise<void> {
1041
+ await this.#txsDB.delete(txHashStr);
1042
+ await this.#proofsDB.delete(txHashStr);
1043
+ }
1044
+
1045
+ /** Deletes a batch of transactions, emitting callbacks individually for each. */
1046
+ async #deleteTxsBatch(txHashes: string[]): Promise<void> {
1047
+ for (const txHashStr of txHashes) {
1048
+ await this.#deleteTx(txHashStr);
1049
+ }
1050
+ }
1051
+
1052
+ /** Evicts transactions: records eviction metric with reason, caches hashes, then deletes. */
1053
+ async #evictTxs(txHashes: string[], reason: string): Promise<void> {
1054
+ if (txHashes.length === 0) {
1055
+ return;
1056
+ }
1057
+ this.#instrumentation.recordEvictions(txHashes.length, reason);
1058
+ for (const txHashStr of txHashes) {
1059
+ this.#log.debug(`Evicting tx ${txHashStr}`, { txHash: txHashStr, reason });
1060
+ this.#evictedTxHashes.add(txHashStr);
1061
+ }
1062
+ await this.#deleteTxsBatch(txHashes);
1063
+ }
1064
+
1065
+ // ============================================================================
1066
+ // PRIVATE HELPERS - Validation & Conflict Resolution
1067
+ // ============================================================================
1068
+
1069
+ /** Validates transaction metadata, returning true if valid */
1070
+ async #validateMeta(meta: TxMetaData, validator?: TxValidator<TxMetaData>, context?: string): Promise<boolean> {
1071
+ const txValidator = validator ?? (await this.#createTxValidator());
1072
+ const result = await txValidator.validateTx(meta);
1073
+ if (result.result !== 'valid') {
1074
+ const contextStr = context ? ` ${context}` : '';
1075
+ this.#log.info(`Tx ${meta.txHash}${contextStr} failed validation: ${result.reason?.join(', ')}`);
1076
+ return false;
1077
+ }
1078
+ return true;
1079
+ }
1080
+
1081
+ /** Validates metadata directly */
1082
+ async #revalidateMetadata(
1083
+ metas: TxMetaData[],
1084
+ context?: string,
1085
+ ): Promise<{ valid: TxMetaData[]; invalid: string[] }> {
1086
+ const valid: TxMetaData[] = [];
1087
+ const invalid: string[] = [];
1088
+ const validator = await this.#createTxValidator();
1089
+ for (const meta of metas) {
1090
+ if (await this.#validateMeta(meta, validator, context)) {
1091
+ valid.push(meta);
1092
+ } else {
1093
+ invalid.push(meta.txHash);
1094
+ }
1095
+ }
1096
+ return { valid, invalid };
1097
+ }
1098
+
1099
+ /**
1100
+ * Resolves nullifier conflicts between incoming txs and existing pending txs.
1101
+ * Modifies the pending indices during iteration to maintain consistent state
1102
+ * for subsequent conflict checks within the same batch.
1103
+ */
1104
+ #applyNullifierConflictResolution(txs: TxMetaData[]): { added: TxMetaData[]; toEvict: string[] } {
1105
+ const added: TxMetaData[] = [];
1106
+ const toEvict: string[] = [];
1107
+
1108
+ for (const meta of txs) {
1109
+ const conflict = checkNullifierConflict(
1110
+ meta,
1111
+ nullifier => this.#indices.getTxHashByNullifier(nullifier),
1112
+ txHash => this.#indices.getMetadata(txHash),
1113
+ );
1114
+ if (conflict.shouldIgnore) {
1115
+ // Lower priority than existing - don't add, mark for deletion
1116
+ toEvict.push(meta.txHash);
1117
+ } else {
1118
+ // Higher priority - evict existing conflicts
1119
+ toEvict.push(...conflict.txHashesToEvict);
1120
+ // Remove evicted from indices immediately for subsequent checks
1121
+ for (const evictHash of conflict.txHashesToEvict) {
1122
+ const evictMeta = this.#indices.getMetadata(evictHash);
1123
+ if (evictMeta) {
1124
+ this.#indices.removeFromPendingIndices(evictMeta);
1125
+ }
1126
+ }
1127
+ // Add to pending indices immediately so subsequent txs in the batch see this tx
1128
+ this.#indices.addToPendingIndices(meta);
1129
+ added.push(meta);
1130
+ }
1131
+ }
1132
+
1133
+ return { added, toEvict };
1134
+ }
1135
+
1136
+ // ============================================================================
1137
+ // PRIVATE HELPERS - Block & Hydration
1138
+ // ============================================================================
1139
+
1140
+ async #buildBlockId(block: BlockHeader): Promise<L2BlockId> {
1141
+ return {
1142
+ number: block.globalVariables.blockNumber,
1143
+ hash: (await block.hash()).toString(),
1144
+ };
1145
+ }
1146
+
1147
+ /** Checks if a tx is already mined and returns its block ID if so */
1148
+ async #getMinedBlockId(txHash: TxHash): Promise<L2BlockId | undefined> {
1149
+ const txEffect = await this.#l2BlockSource.getTxEffect(txHash);
1150
+ if (!txEffect) {
1151
+ return undefined;
1152
+ }
1153
+ return {
1154
+ number: txEffect.l2BlockNumber,
1155
+ hash: txEffect.l2BlockHash.toString(),
1156
+ };
1157
+ }
1158
+
1159
+ /**
1160
+ * Rebuilds the pending pool by processing each tx through pre-add rules.
1161
+ * Starts with an empty pending pool and adds txs one by one, resolving conflicts.
1162
+ * Returns the list of accepted and rejected tx hashes.
1163
+ */
1164
+ async #rebuildPendingPool(metas: TxMetaData[]): Promise<{ accepted: string[]; rejected: string[] }> {
1165
+ const accepted = new Set<string>();
1166
+ const rejected: string[] = [];
1167
+ const poolAccess = this.#createPreAddPoolAccess();
1168
+
1169
+ for (const meta of metas) {
1170
+ // Run pre-add rules against current pending pool state (metadata not yet in pool)
1171
+ const preAddResult = await this.#evictionManager.runPreAddRules(meta, poolAccess);
1172
+
1173
+ if (preAddResult.shouldIgnore) {
1174
+ // Transaction rejected - mark for deletion from DB
1175
+ rejected.push(meta.txHash);
1176
+ this.#log.debug(
1177
+ `Rejected tx ${meta.txHash} during rebuild: ${preAddResult.reason?.message ?? 'unknown reason'}`,
1178
+ );
1179
+ continue;
1180
+ }
1181
+
1182
+ // Evict any conflicting txs identified by pre-add rules
1183
+ for (const evictHashStr of preAddResult.txHashesToEvict) {
1184
+ const evictMeta = this.#indices.getMetadata(evictHashStr);
1185
+ if (evictMeta) {
1186
+ this.#indices.removeFromPendingIndices(evictMeta);
1187
+ this.#indices.remove(evictHashStr);
1188
+ rejected.push(evictHashStr);
1189
+ accepted.delete(evictHashStr);
1190
+ this.#log.debug(`Evicted tx ${evictHashStr} during rebuild due to conflict with ${meta.txHash}`);
1191
+ }
1192
+ }
1193
+
1194
+ // Add to indices
1195
+ this.#indices.addPending(meta);
1196
+ accepted.add(meta.txHash);
1197
+ }
1198
+
1199
+ this.#log.info(`Rebuilt pending pool: ${accepted.size} accepted, ${rejected.length} rejected`);
1200
+ return { accepted: [...accepted], rejected };
1201
+ }
1202
+
1203
+ // ============================================================================
1204
+ // PRIVATE HELPERS - Pool Access Adapters
1205
+ // ============================================================================
1206
+
1207
+ #createPoolOperations(): PoolOperations {
1208
+ return {
1209
+ getPendingTxs: () => this.#indices.getPendingTxs(),
1210
+ getPendingFeePayers: () => this.#indices.getPendingFeePayers(),
1211
+ getFeePayerPendingTxs: (feePayer: string) => this.#indices.getFeePayerPendingTxs(feePayer),
1212
+ getPendingTxCount: () => this.#indices.getPendingTxCount(),
1213
+ getLowestPriorityPending: (limit: number) => this.#indices.getLowestPriorityPending(limit),
1214
+ deleteTxs: (txHashes: string[], reason?: string) => this.#evictTxs(txHashes, reason ?? 'unknown'),
1215
+ };
1216
+ }
1217
+
1218
+ #createPreAddPoolAccess(): PreAddPoolAccess {
1219
+ return {
1220
+ getMetadata: (txHashStr: string) => {
1221
+ const meta = this.#indices.getMetadata(txHashStr);
1222
+ if (!meta || this.#indices.getTxState(meta) !== 'pending') {
1223
+ return undefined;
1224
+ }
1225
+ return meta;
1226
+ },
1227
+ getTxHashByNullifier: (nullifier: string) => this.#indices.getTxHashByNullifier(nullifier),
1228
+ getFeePayerBalance: async (feePayer: string) => {
1229
+ const db = this.#worldStateSynchronizer.getCommitted();
1230
+ const publicStateSource = new DatabasePublicStateSource(db);
1231
+ const balance = await publicStateSource.storageRead(
1232
+ ProtocolContractAddress.FeeJuice,
1233
+ await computeFeePayerBalanceStorageSlot(AztecAddress.fromStringUnsafe(feePayer)),
1234
+ );
1235
+ return balance.toBigInt();
1236
+ },
1237
+ getFeePayerPendingTxs: (feePayer: string) => this.#indices.getFeePayerPendingTxs(feePayer),
1238
+ getPendingTxCount: () => this.#indices.getPendingTxCount(),
1239
+ getLowestPriorityPendingTx: () => this.#indices.getLowestPriorityPendingTx(),
1240
+ };
1241
+ }
1242
+ }