@aztec/p2p 0.0.0-test.1 → 0.0.1-commit.24de95ac

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 (339) hide show
  1. package/dest/bootstrap/bootstrap.d.ts.map +1 -1
  2. package/dest/bootstrap/bootstrap.js +22 -9
  3. package/dest/client/factory.d.ts +13 -3
  4. package/dest/client/factory.d.ts.map +1 -1
  5. package/dest/client/factory.js +60 -24
  6. package/dest/client/index.d.ts +1 -0
  7. package/dest/client/index.d.ts.map +1 -1
  8. package/dest/client/index.js +1 -0
  9. package/dest/client/interface.d.ts +155 -0
  10. package/dest/client/interface.d.ts.map +1 -0
  11. package/dest/client/interface.js +9 -0
  12. package/dest/client/p2p_client.d.ts +72 -169
  13. package/dest/client/p2p_client.d.ts.map +1 -1
  14. package/dest/client/p2p_client.js +365 -174
  15. package/dest/config.d.ts +123 -103
  16. package/dest/config.d.ts.map +1 -1
  17. package/dest/config.js +173 -34
  18. package/dest/enr/generate-enr.d.ts +10 -2
  19. package/dest/enr/generate-enr.d.ts.map +1 -1
  20. package/dest/enr/generate-enr.js +27 -5
  21. package/dest/index.d.ts +3 -0
  22. package/dest/index.d.ts.map +1 -1
  23. package/dest/index.js +2 -0
  24. package/dest/mem_pools/attestation_pool/attestation_pool.d.ts +42 -4
  25. package/dest/mem_pools/attestation_pool/attestation_pool.d.ts.map +1 -1
  26. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.d.ts.map +1 -1
  27. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.js +204 -54
  28. package/dest/mem_pools/attestation_pool/kv_attestation_pool.d.ts +10 -2
  29. package/dest/mem_pools/attestation_pool/kv_attestation_pool.d.ts.map +1 -1
  30. package/dest/mem_pools/attestation_pool/kv_attestation_pool.js +93 -15
  31. package/dest/mem_pools/attestation_pool/memory_attestation_pool.d.ts +10 -2
  32. package/dest/mem_pools/attestation_pool/memory_attestation_pool.d.ts.map +1 -1
  33. package/dest/mem_pools/attestation_pool/memory_attestation_pool.js +86 -18
  34. package/dest/mem_pools/attestation_pool/mocks.d.ts +1 -2
  35. package/dest/mem_pools/attestation_pool/mocks.d.ts.map +1 -1
  36. package/dest/mem_pools/attestation_pool/mocks.js +9 -15
  37. package/dest/mem_pools/instrumentation.d.ts +7 -11
  38. package/dest/mem_pools/instrumentation.d.ts.map +1 -1
  39. package/dest/mem_pools/instrumentation.js +25 -37
  40. package/dest/mem_pools/tx_pool/aztec_kv_tx_pool.d.ts +93 -9
  41. package/dest/mem_pools/tx_pool/aztec_kv_tx_pool.d.ts.map +1 -1
  42. package/dest/mem_pools/tx_pool/aztec_kv_tx_pool.js +469 -97
  43. package/dest/mem_pools/tx_pool/memory_tx_pool.d.ts +33 -9
  44. package/dest/mem_pools/tx_pool/memory_tx_pool.d.ts.map +1 -1
  45. package/dest/mem_pools/tx_pool/memory_tx_pool.js +133 -36
  46. package/dest/mem_pools/tx_pool/priority.js +1 -1
  47. package/dest/mem_pools/tx_pool/tx_pool.d.ts +64 -8
  48. package/dest/mem_pools/tx_pool/tx_pool.d.ts.map +1 -1
  49. package/dest/mem_pools/tx_pool/tx_pool_test_suite.d.ts.map +1 -1
  50. package/dest/mem_pools/tx_pool/tx_pool_test_suite.js +264 -39
  51. package/dest/msg_validators/attestation_validator/attestation_validator.d.ts +1 -0
  52. package/dest/msg_validators/attestation_validator/attestation_validator.d.ts.map +1 -1
  53. package/dest/msg_validators/attestation_validator/attestation_validator.js +45 -9
  54. package/dest/msg_validators/block_proposal_validator/block_proposal_validator.d.ts +5 -1
  55. package/dest/msg_validators/block_proposal_validator/block_proposal_validator.d.ts.map +1 -1
  56. package/dest/msg_validators/block_proposal_validator/block_proposal_validator.js +61 -12
  57. package/dest/msg_validators/msg_seen_validator/msg_seen_validator.d.ts +10 -0
  58. package/dest/msg_validators/msg_seen_validator/msg_seen_validator.d.ts.map +1 -0
  59. package/dest/msg_validators/msg_seen_validator/msg_seen_validator.js +36 -0
  60. package/dest/msg_validators/tx_validator/allowed_public_setup.d.ts +3 -0
  61. package/dest/msg_validators/tx_validator/allowed_public_setup.d.ts.map +1 -0
  62. package/dest/msg_validators/tx_validator/allowed_public_setup.js +27 -0
  63. package/dest/msg_validators/tx_validator/archive_cache.d.ts +14 -0
  64. package/dest/msg_validators/tx_validator/archive_cache.d.ts.map +1 -0
  65. package/dest/msg_validators/tx_validator/archive_cache.js +22 -0
  66. package/dest/msg_validators/tx_validator/block_header_validator.d.ts.map +1 -1
  67. package/dest/msg_validators/tx_validator/block_header_validator.js +4 -4
  68. package/dest/msg_validators/tx_validator/data_validator.d.ts.map +1 -1
  69. package/dest/msg_validators/tx_validator/data_validator.js +56 -86
  70. package/dest/msg_validators/tx_validator/double_spend_validator.d.ts +0 -2
  71. package/dest/msg_validators/tx_validator/double_spend_validator.d.ts.map +1 -1
  72. package/dest/msg_validators/tx_validator/double_spend_validator.js +21 -27
  73. package/dest/msg_validators/tx_validator/factory.d.ts +15 -0
  74. package/dest/msg_validators/tx_validator/factory.d.ts.map +1 -0
  75. package/dest/msg_validators/tx_validator/factory.js +74 -0
  76. package/dest/msg_validators/tx_validator/gas_validator.d.ts +11 -0
  77. package/dest/msg_validators/tx_validator/gas_validator.d.ts.map +1 -0
  78. package/dest/msg_validators/tx_validator/gas_validator.js +115 -0
  79. package/dest/msg_validators/tx_validator/index.d.ts +7 -0
  80. package/dest/msg_validators/tx_validator/index.d.ts.map +1 -1
  81. package/dest/msg_validators/tx_validator/index.js +7 -0
  82. package/dest/msg_validators/tx_validator/metadata_validator.d.ts +7 -3
  83. package/dest/msg_validators/tx_validator/metadata_validator.d.ts.map +1 -1
  84. package/dest/msg_validators/tx_validator/metadata_validator.js +39 -20
  85. package/dest/msg_validators/tx_validator/phases_validator.d.ts +14 -0
  86. package/dest/msg_validators/tx_validator/phases_validator.d.ts.map +1 -0
  87. package/dest/msg_validators/tx_validator/phases_validator.js +91 -0
  88. package/dest/msg_validators/tx_validator/test_utils.d.ts +17 -0
  89. package/dest/msg_validators/tx_validator/test_utils.d.ts.map +1 -0
  90. package/dest/msg_validators/tx_validator/test_utils.js +22 -0
  91. package/dest/msg_validators/tx_validator/timestamp_validator.d.ts +12 -0
  92. package/dest/msg_validators/tx_validator/timestamp_validator.d.ts.map +1 -0
  93. package/dest/msg_validators/tx_validator/timestamp_validator.js +32 -0
  94. package/dest/msg_validators/tx_validator/tx_permitted_validator.d.ts +8 -0
  95. package/dest/msg_validators/tx_validator/tx_permitted_validator.d.ts.map +1 -0
  96. package/dest/msg_validators/tx_validator/tx_permitted_validator.js +24 -0
  97. package/dest/msg_validators/tx_validator/tx_proof_validator.d.ts.map +1 -1
  98. package/dest/msg_validators/tx_validator/tx_proof_validator.js +6 -5
  99. package/dest/services/discv5/discV5_service.d.ts +9 -8
  100. package/dest/services/discv5/discV5_service.d.ts.map +1 -1
  101. package/dest/services/discv5/discV5_service.js +63 -36
  102. package/dest/services/dummy_service.d.ts +49 -10
  103. package/dest/services/dummy_service.d.ts.map +1 -1
  104. package/dest/services/dummy_service.js +88 -5
  105. package/dest/services/encoding.d.ts +25 -6
  106. package/dest/services/encoding.d.ts.map +1 -1
  107. package/dest/services/encoding.js +73 -5
  108. package/dest/services/index.d.ts +4 -0
  109. package/dest/services/index.d.ts.map +1 -1
  110. package/dest/services/index.js +4 -0
  111. package/dest/services/libp2p/instrumentation.d.ts +18 -0
  112. package/dest/services/libp2p/instrumentation.d.ts.map +1 -0
  113. package/dest/services/libp2p/instrumentation.js +157 -0
  114. package/dest/services/libp2p/libp2p_service.d.ts +87 -42
  115. package/dest/services/libp2p/libp2p_service.d.ts.map +1 -1
  116. package/dest/services/libp2p/libp2p_service.js +500 -218
  117. package/dest/services/peer-manager/interface.d.ts +23 -0
  118. package/dest/services/peer-manager/interface.d.ts.map +1 -0
  119. package/dest/services/peer-manager/interface.js +1 -0
  120. package/dest/services/peer-manager/metrics.d.ts +3 -1
  121. package/dest/services/peer-manager/metrics.d.ts.map +1 -1
  122. package/dest/services/peer-manager/metrics.js +11 -2
  123. package/dest/services/peer-manager/peer_manager.d.ts +126 -15
  124. package/dest/services/peer-manager/peer_manager.d.ts.map +1 -1
  125. package/dest/services/peer-manager/peer_manager.js +547 -72
  126. package/dest/services/reqresp/config.d.ts +10 -8
  127. package/dest/services/reqresp/config.d.ts.map +1 -1
  128. package/dest/services/reqresp/config.js +18 -4
  129. package/dest/services/reqresp/connection-sampler/batch_connection_sampler.d.ts +1 -1
  130. package/dest/services/reqresp/connection-sampler/batch_connection_sampler.d.ts.map +1 -1
  131. package/dest/services/reqresp/connection-sampler/batch_connection_sampler.js +10 -6
  132. package/dest/services/reqresp/connection-sampler/connection_sampler.d.ts +30 -13
  133. package/dest/services/reqresp/connection-sampler/connection_sampler.d.ts.map +1 -1
  134. package/dest/services/reqresp/connection-sampler/connection_sampler.js +142 -84
  135. package/dest/services/reqresp/index.d.ts +2 -1
  136. package/dest/services/reqresp/index.d.ts.map +1 -1
  137. package/dest/services/reqresp/index.js +2 -1
  138. package/dest/services/reqresp/interface.d.ts +72 -23
  139. package/dest/services/reqresp/interface.d.ts.map +1 -1
  140. package/dest/services/reqresp/interface.js +45 -26
  141. package/dest/services/reqresp/metrics.d.ts.map +1 -1
  142. package/dest/services/reqresp/protocols/auth.d.ts +43 -0
  143. package/dest/services/reqresp/protocols/auth.d.ts.map +1 -0
  144. package/dest/services/reqresp/protocols/auth.js +71 -0
  145. package/dest/services/reqresp/protocols/block.d.ts +5 -0
  146. package/dest/services/reqresp/protocols/block.d.ts.map +1 -1
  147. package/dest/services/reqresp/protocols/block.js +28 -5
  148. package/dest/services/reqresp/protocols/block_txs/bitvector.d.ts +30 -0
  149. package/dest/services/reqresp/protocols/block_txs/bitvector.d.ts.map +1 -0
  150. package/dest/services/reqresp/protocols/block_txs/bitvector.js +75 -0
  151. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.d.ts +11 -0
  152. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.d.ts.map +1 -0
  153. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.js +39 -0
  154. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.d.ts +49 -0
  155. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.d.ts.map +1 -0
  156. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.js +75 -0
  157. package/dest/services/reqresp/protocols/block_txs/index.d.ts +4 -0
  158. package/dest/services/reqresp/protocols/block_txs/index.d.ts.map +1 -0
  159. package/dest/services/reqresp/protocols/block_txs/index.js +3 -0
  160. package/dest/services/reqresp/protocols/goodbye.d.ts +2 -4
  161. package/dest/services/reqresp/protocols/goodbye.d.ts.map +1 -1
  162. package/dest/services/reqresp/protocols/goodbye.js +7 -7
  163. package/dest/services/reqresp/protocols/index.d.ts +2 -0
  164. package/dest/services/reqresp/protocols/index.d.ts.map +1 -1
  165. package/dest/services/reqresp/protocols/index.js +2 -0
  166. package/dest/services/reqresp/protocols/ping.d.ts +0 -2
  167. package/dest/services/reqresp/protocols/ping.d.ts.map +1 -1
  168. package/dest/services/reqresp/protocols/status.d.ts +38 -6
  169. package/dest/services/reqresp/protocols/status.d.ts.map +1 -1
  170. package/dest/services/reqresp/protocols/status.js +72 -5
  171. package/dest/services/reqresp/protocols/tx.d.ts +12 -1
  172. package/dest/services/reqresp/protocols/tx.d.ts.map +1 -1
  173. package/dest/services/reqresp/protocols/tx.js +34 -6
  174. package/dest/services/reqresp/rate-limiter/rate_limiter.d.ts +4 -2
  175. package/dest/services/reqresp/rate-limiter/rate_limiter.d.ts.map +1 -1
  176. package/dest/services/reqresp/rate-limiter/rate_limiter.js +10 -2
  177. package/dest/services/reqresp/rate-limiter/rate_limits.d.ts.map +1 -1
  178. package/dest/services/reqresp/rate-limiter/rate_limits.js +21 -1
  179. package/dest/services/reqresp/reqresp.d.ts +45 -47
  180. package/dest/services/reqresp/reqresp.d.ts.map +1 -1
  181. package/dest/services/reqresp/reqresp.js +298 -207
  182. package/dest/services/reqresp/status.d.ts +9 -3
  183. package/dest/services/reqresp/status.d.ts.map +1 -1
  184. package/dest/services/reqresp/status.js +9 -2
  185. package/dest/services/service.d.ts +22 -18
  186. package/dest/services/service.d.ts.map +1 -1
  187. package/dest/services/tx_collection/config.d.ts +25 -0
  188. package/dest/services/tx_collection/config.d.ts.map +1 -0
  189. package/dest/services/tx_collection/config.js +58 -0
  190. package/dest/services/tx_collection/fast_tx_collection.d.ts +56 -0
  191. package/dest/services/tx_collection/fast_tx_collection.d.ts.map +1 -0
  192. package/dest/services/tx_collection/fast_tx_collection.js +300 -0
  193. package/dest/services/tx_collection/index.d.ts +3 -0
  194. package/dest/services/tx_collection/index.d.ts.map +1 -0
  195. package/dest/services/tx_collection/index.js +2 -0
  196. package/dest/services/tx_collection/instrumentation.d.ts +10 -0
  197. package/dest/services/tx_collection/instrumentation.d.ts.map +1 -0
  198. package/dest/services/tx_collection/instrumentation.js +34 -0
  199. package/dest/services/tx_collection/slow_tx_collection.d.ts +54 -0
  200. package/dest/services/tx_collection/slow_tx_collection.d.ts.map +1 -0
  201. package/dest/services/tx_collection/slow_tx_collection.js +176 -0
  202. package/dest/services/tx_collection/tx_collection.d.ts +110 -0
  203. package/dest/services/tx_collection/tx_collection.d.ts.map +1 -0
  204. package/dest/services/tx_collection/tx_collection.js +128 -0
  205. package/dest/services/tx_collection/tx_collection_sink.d.ts +30 -0
  206. package/dest/services/tx_collection/tx_collection_sink.d.ts.map +1 -0
  207. package/dest/services/tx_collection/tx_collection_sink.js +111 -0
  208. package/dest/services/tx_collection/tx_source.d.ts +18 -0
  209. package/dest/services/tx_collection/tx_source.d.ts.map +1 -0
  210. package/dest/services/tx_collection/tx_source.js +31 -0
  211. package/dest/services/tx_provider.d.ts +49 -0
  212. package/dest/services/tx_provider.d.ts.map +1 -0
  213. package/dest/services/tx_provider.js +210 -0
  214. package/dest/services/tx_provider_instrumentation.d.ts +13 -0
  215. package/dest/services/tx_provider_instrumentation.d.ts.map +1 -0
  216. package/dest/services/tx_provider_instrumentation.js +34 -0
  217. package/dest/test-helpers/get-ports.d.ts.map +1 -1
  218. package/dest/test-helpers/index.d.ts +1 -0
  219. package/dest/test-helpers/index.d.ts.map +1 -1
  220. package/dest/test-helpers/index.js +1 -0
  221. package/dest/test-helpers/make-enrs.d.ts.map +1 -1
  222. package/dest/test-helpers/make-enrs.js +4 -5
  223. package/dest/test-helpers/make-test-p2p-clients.d.ts +32 -4
  224. package/dest/test-helpers/make-test-p2p-clients.d.ts.map +1 -1
  225. package/dest/test-helpers/make-test-p2p-clients.js +86 -16
  226. package/dest/test-helpers/mock-pubsub.d.ts +59 -0
  227. package/dest/test-helpers/mock-pubsub.d.ts.map +1 -0
  228. package/dest/test-helpers/mock-pubsub.js +130 -0
  229. package/dest/test-helpers/mock-tx-helpers.d.ts +12 -0
  230. package/dest/test-helpers/mock-tx-helpers.d.ts.map +1 -0
  231. package/dest/test-helpers/mock-tx-helpers.js +19 -0
  232. package/dest/test-helpers/reqresp-nodes.d.ts +14 -10
  233. package/dest/test-helpers/reqresp-nodes.d.ts.map +1 -1
  234. package/dest/test-helpers/reqresp-nodes.js +62 -28
  235. package/dest/testbench/p2p_client_testbench_worker.js +96 -25
  236. package/dest/testbench/parse_log_file.js +4 -4
  237. package/dest/testbench/testbench.js +4 -4
  238. package/dest/testbench/worker_client_manager.d.ts +0 -5
  239. package/dest/testbench/worker_client_manager.d.ts.map +1 -1
  240. package/dest/testbench/worker_client_manager.js +11 -19
  241. package/dest/types/index.d.ts +3 -1
  242. package/dest/types/index.d.ts.map +1 -1
  243. package/dest/types/index.js +2 -0
  244. package/dest/util.d.ts +22 -15
  245. package/dest/util.d.ts.map +1 -1
  246. package/dest/util.js +64 -67
  247. package/dest/versioning.d.ts +3 -3
  248. package/dest/versioning.d.ts.map +1 -1
  249. package/dest/versioning.js +8 -3
  250. package/package.json +28 -24
  251. package/src/bootstrap/bootstrap.ts +27 -11
  252. package/src/client/factory.ts +136 -45
  253. package/src/client/index.ts +1 -0
  254. package/src/client/interface.ts +195 -0
  255. package/src/client/p2p_client.ts +460 -327
  256. package/src/config.ts +288 -134
  257. package/src/enr/generate-enr.ts +39 -6
  258. package/src/index.ts +4 -0
  259. package/src/mem_pools/attestation_pool/attestation_pool.ts +48 -4
  260. package/src/mem_pools/attestation_pool/attestation_pool_test_suite.ts +241 -55
  261. package/src/mem_pools/attestation_pool/kv_attestation_pool.ts +117 -20
  262. package/src/mem_pools/attestation_pool/memory_attestation_pool.ts +114 -22
  263. package/src/mem_pools/attestation_pool/mocks.ts +11 -10
  264. package/src/mem_pools/instrumentation.ts +32 -46
  265. package/src/mem_pools/tx_pool/aztec_kv_tx_pool.ts +549 -108
  266. package/src/mem_pools/tx_pool/memory_tx_pool.ts +153 -44
  267. package/src/mem_pools/tx_pool/priority.ts +1 -1
  268. package/src/mem_pools/tx_pool/tx_pool.ts +67 -8
  269. package/src/mem_pools/tx_pool/tx_pool_test_suite.ts +217 -34
  270. package/src/msg_validators/attestation_validator/attestation_validator.ts +55 -10
  271. package/src/msg_validators/block_proposal_validator/block_proposal_validator.ts +66 -14
  272. package/src/msg_validators/msg_seen_validator/msg_seen_validator.ts +36 -0
  273. package/src/msg_validators/tx_validator/allowed_public_setup.ts +35 -0
  274. package/src/msg_validators/tx_validator/archive_cache.ts +28 -0
  275. package/src/msg_validators/tx_validator/block_header_validator.ts +4 -4
  276. package/src/msg_validators/tx_validator/data_validator.ts +81 -69
  277. package/src/msg_validators/tx_validator/double_spend_validator.ts +19 -17
  278. package/src/msg_validators/tx_validator/factory.ts +109 -0
  279. package/src/msg_validators/tx_validator/gas_validator.ts +134 -0
  280. package/src/msg_validators/tx_validator/index.ts +7 -0
  281. package/src/msg_validators/tx_validator/metadata_validator.ts +58 -21
  282. package/src/msg_validators/tx_validator/phases_validator.ts +114 -0
  283. package/src/msg_validators/tx_validator/test_utils.ts +43 -0
  284. package/src/msg_validators/tx_validator/timestamp_validator.ts +46 -0
  285. package/src/msg_validators/tx_validator/tx_permitted_validator.ts +17 -0
  286. package/src/msg_validators/tx_validator/tx_proof_validator.ts +6 -5
  287. package/src/services/discv5/discV5_service.ts +84 -38
  288. package/src/services/dummy_service.ts +147 -9
  289. package/src/services/encoding.ts +80 -5
  290. package/src/services/index.ts +4 -0
  291. package/src/services/libp2p/instrumentation.ts +158 -0
  292. package/src/services/libp2p/libp2p_service.ts +646 -263
  293. package/src/services/peer-manager/interface.ts +29 -0
  294. package/src/services/peer-manager/metrics.ts +16 -1
  295. package/src/services/peer-manager/peer_manager.ts +652 -78
  296. package/src/services/reqresp/config.ts +26 -9
  297. package/src/services/reqresp/connection-sampler/batch_connection_sampler.ts +12 -6
  298. package/src/services/reqresp/connection-sampler/connection_sampler.ts +148 -95
  299. package/src/services/reqresp/index.ts +2 -0
  300. package/src/services/reqresp/interface.ts +91 -36
  301. package/src/services/reqresp/metrics.ts +4 -1
  302. package/src/services/reqresp/protocols/auth.ts +83 -0
  303. package/src/services/reqresp/protocols/block.ts +24 -3
  304. package/src/services/reqresp/protocols/block_txs/bitvector.ts +90 -0
  305. package/src/services/reqresp/protocols/block_txs/block_txs_handler.ts +53 -0
  306. package/src/services/reqresp/protocols/block_txs/block_txs_reqresp.ts +79 -0
  307. package/src/services/reqresp/protocols/block_txs/index.ts +3 -0
  308. package/src/services/reqresp/protocols/goodbye.ts +9 -7
  309. package/src/services/reqresp/protocols/index.ts +2 -0
  310. package/src/services/reqresp/protocols/status.ts +117 -5
  311. package/src/services/reqresp/protocols/tx.ts +35 -6
  312. package/src/services/reqresp/rate-limiter/rate_limiter.ts +12 -3
  313. package/src/services/reqresp/rate-limiter/rate_limits.ts +21 -1
  314. package/src/services/reqresp/reqresp.ts +387 -256
  315. package/src/services/reqresp/status.ts +12 -3
  316. package/src/services/service.ts +45 -21
  317. package/src/services/tx_collection/config.ts +84 -0
  318. package/src/services/tx_collection/fast_tx_collection.ts +340 -0
  319. package/src/services/tx_collection/index.ts +2 -0
  320. package/src/services/tx_collection/instrumentation.ts +43 -0
  321. package/src/services/tx_collection/slow_tx_collection.ts +232 -0
  322. package/src/services/tx_collection/tx_collection.ts +215 -0
  323. package/src/services/tx_collection/tx_collection_sink.ts +129 -0
  324. package/src/services/tx_collection/tx_source.ts +37 -0
  325. package/src/services/tx_provider.ts +216 -0
  326. package/src/services/tx_provider_instrumentation.ts +44 -0
  327. package/src/test-helpers/index.ts +1 -0
  328. package/src/test-helpers/make-enrs.ts +4 -5
  329. package/src/test-helpers/make-test-p2p-clients.ts +111 -21
  330. package/src/test-helpers/mock-pubsub.ts +188 -0
  331. package/src/test-helpers/mock-tx-helpers.ts +24 -0
  332. package/src/test-helpers/reqresp-nodes.ts +86 -35
  333. package/src/testbench/p2p_client_testbench_worker.ts +145 -22
  334. package/src/testbench/parse_log_file.ts +4 -4
  335. package/src/testbench/testbench.ts +4 -4
  336. package/src/testbench/worker_client_manager.ts +17 -23
  337. package/src/types/index.ts +2 -0
  338. package/src/util.ts +93 -89
  339. package/src/versioning.ts +11 -4
@@ -1,9 +1,21 @@
1
1
  import { INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
2
2
  import { createLogger } from '@aztec/foundation/log';
3
+ import { DateProvider } from '@aztec/foundation/timer';
3
4
  import type { AztecAsyncKVStore, AztecAsyncMap, AztecAsyncSingleton } from '@aztec/kv-store';
4
- import type { L2Block, L2BlockId, L2BlockSource, L2BlockStreamEvent, L2Tips } from '@aztec/stdlib/block';
5
- import type { P2PApi, PeerInfo, ProverCoordination } from '@aztec/stdlib/interfaces/server';
6
- import type { BlockAttestation, BlockProposal, P2PClientType } from '@aztec/stdlib/p2p';
5
+ import type {
6
+ EthAddress,
7
+ L2Block,
8
+ L2BlockId,
9
+ L2BlockSource,
10
+ L2BlockStream,
11
+ L2BlockStreamEvent,
12
+ L2Tips,
13
+ PublishedL2Block,
14
+ } from '@aztec/stdlib/block';
15
+ import type { ContractDataSource } from '@aztec/stdlib/contract';
16
+ import { getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
17
+ import { type PeerInfo, tryStop } from '@aztec/stdlib/interfaces/server';
18
+ import { BlockAttestation, type BlockProposal, type P2PClientType } from '@aztec/stdlib/p2p';
7
19
  import type { Tx, TxHash } from '@aztec/stdlib/tx';
8
20
  import {
9
21
  Attributes,
@@ -14,152 +26,24 @@ import {
14
26
  trackSpan,
15
27
  } from '@aztec/telemetry-client';
16
28
 
17
- import type { ENR } from '@chainsafe/enr';
29
+ import type { PeerId } from '@libp2p/interface';
30
+ import type { ENR } from '@nethermindeth/enr';
18
31
 
19
32
  import { type P2PConfig, getP2PDefaultConfig } from '../config.js';
20
33
  import type { AttestationPool } from '../mem_pools/attestation_pool/attestation_pool.js';
21
34
  import type { MemPools } from '../mem_pools/interface.js';
22
35
  import type { TxPool } from '../mem_pools/tx_pool/index.js';
23
- import { ReqRespSubProtocol } from '../services/reqresp/interface.js';
24
- import type { P2PService } from '../services/service.js';
25
-
26
- /**
27
- * Enum defining the possible states of the p2p client.
28
- */
29
- export enum P2PClientState {
30
- IDLE,
31
- SYNCHING,
32
- RUNNING,
33
- STOPPED,
34
- }
35
-
36
- /**
37
- * The synchronization status of the P2P client.
38
- */
39
- export interface P2PSyncState {
40
- /**
41
- * The current state of the p2p client.
42
- */
43
- state: P2PClientState;
44
- /**
45
- * The block number that the p2p client is synced to.
46
- */
47
- syncedToL2Block: L2BlockId;
48
- }
49
-
50
- /**
51
- * Interface of a P2P client.
52
- **/
53
- export type P2P<T extends P2PClientType = P2PClientType.Full> = ProverCoordination &
54
- P2PApi<T> & {
55
- /**
56
- * Broadcasts a block proposal to other peers.
57
- *
58
- * @param proposal - the block proposal
59
- */
60
- broadcastProposal(proposal: BlockProposal): void;
61
-
62
- /**
63
- * Registers a callback from the validator client that determines how to behave when
64
- * foreign block proposals are received
65
- *
66
- * @param handler - A function taking a received block proposal and producing an attestation
67
- */
68
- // REVIEW: https://github.com/AztecProtocol/aztec-packages/issues/7963
69
- // ^ This pattern is not my favorite (md)
70
- registerBlockProposalHandler(handler: (block: BlockProposal) => Promise<BlockAttestation | undefined>): void;
71
-
72
- /**
73
- * Request a list of transactions from another peer by their tx hashes.
74
- * @param txHashes - Hashes of the txs to query.
75
- * @returns A list of transactions or undefined if the transactions are not found.
76
- */
77
- requestTxs(txHashes: TxHash[]): Promise<(Tx | undefined)[]>;
78
-
79
- /**
80
- * Request a transaction from another peer by its tx hash.
81
- * @param txHash - Hash of the tx to query.
82
- */
83
- requestTxByHash(txHash: TxHash): Promise<Tx | undefined>;
84
-
85
- /**
86
- * Verifies the 'tx' and, if valid, adds it to local tx pool and forwards it to other peers.
87
- * @param tx - The transaction.
88
- **/
89
- sendTx(tx: Tx): Promise<void>;
90
-
91
- /**
92
- * Deletes 'txs' from the pool, given hashes.
93
- * NOT used if we use sendTx as reconcileTxPool will handle this.
94
- * @param txHashes - Hashes to check.
95
- **/
96
- deleteTxs(txHashes: TxHash[]): Promise<void>;
97
-
98
- /**
99
- * Returns a transaction in the transaction pool by its hash.
100
- * @param txHash - Hash of tx to return.
101
- * @returns A single tx or undefined.
102
- */
103
- getTxByHashFromPool(txHash: TxHash): Promise<Tx | undefined>;
104
-
105
- /**
106
- * Returns a transaction in the transaction pool by its hash, requesting it from the network if it is not found.
107
- * @param txHash - Hash of tx to return.
108
- * @returns A single tx or undefined.
109
- */
110
- getTxByHash(txHash: TxHash): Promise<Tx | undefined>;
111
-
112
- /**
113
- * Returns an archived transaction from the transaction pool by its hash.
114
- * @param txHash - Hash of tx to return.
115
- * @returns A single tx or undefined.
116
- */
117
- getArchivedTxByHash(txHash: TxHash): Promise<Tx | undefined>;
118
-
119
- /**
120
- * Returns whether the given tx hash is flagged as pending or mined.
121
- * @param txHash - Hash of the tx to query.
122
- * @returns Pending or mined depending on its status, or undefined if not found.
123
- */
124
- getTxStatus(txHash: TxHash): Promise<'pending' | 'mined' | undefined>;
125
-
126
- /** Returns an iterator over pending txs on the mempool. */
127
- iteratePendingTxs(): AsyncIterableIterator<Tx>;
128
-
129
- /** Returns the number of pending txs in the mempool. */
130
- getPendingTxCount(): Promise<number>;
131
-
132
- /**
133
- * Starts the p2p client.
134
- * @returns A promise signalling the completion of the block sync.
135
- */
136
- start(): Promise<void>;
137
-
138
- /**
139
- * Stops the p2p client.
140
- * @returns A promise signalling the completion of the stop process.
141
- */
142
- stop(): Promise<void>;
143
-
144
- /**
145
- * Indicates if the p2p client is ready for transaction submission.
146
- * @returns A boolean flag indicating readiness.
147
- */
148
- isReady(): boolean;
149
-
150
- /**
151
- * Returns the current status of the p2p client.
152
- */
153
- getStatus(): Promise<P2PSyncState>;
154
-
155
- /**
156
- * Returns the ENR of this node, if any.
157
- */
158
- getEnr(): ENR | undefined;
159
-
160
- /** Identifies a p2p client. */
161
- isP2PClient(): true;
162
- };
36
+ import type { AuthRequest, StatusMessage } from '../services/index.js';
37
+ import {
38
+ ReqRespSubProtocol,
39
+ type ReqRespSubProtocolHandler,
40
+ type ReqRespSubProtocolValidators,
41
+ } from '../services/reqresp/interface.js';
42
+ import { chunkTxHashesRequest } from '../services/reqresp/protocols/tx.js';
43
+ import type { P2PBlockReceivedCallback, P2PService } from '../services/service.js';
44
+ import { TxCollection } from '../services/tx_collection/tx_collection.js';
45
+ import { TxProvider } from '../services/tx_provider.js';
46
+ import { type P2P, P2PClientState, type P2PSyncState } from './interface.js';
163
47
 
164
48
  /**
165
49
  * The P2P client implementation.
@@ -176,20 +60,24 @@ export class P2PClient<T extends P2PClientType = P2PClientType.Full>
176
60
  private syncResolve?: () => void = undefined;
177
61
  private latestBlockNumberAtStart = -1;
178
62
  private provenBlockNumberAtStart = -1;
63
+ private finalizedBlockNumberAtStart = -1;
179
64
 
180
65
  private synchedBlockHashes: AztecAsyncMap<number, string>;
181
66
  private synchedLatestBlockNumber: AztecAsyncSingleton<number>;
182
67
  private synchedProvenBlockNumber: AztecAsyncSingleton<number>;
68
+ private synchedFinalizedBlockNumber: AztecAsyncSingleton<number>;
69
+ private synchedLatestSlot: AztecAsyncSingleton<bigint>;
183
70
 
184
71
  private txPool: TxPool;
185
72
  private attestationPool: T extends P2PClientType.Full ? AttestationPool : undefined;
186
73
 
187
- /** How many slots to keep attestations for. */
188
- private keepAttestationsInPoolFor: number;
189
- /** How many slots to keep proven txs for. */
190
- private keepProvenTxsFor: number;
74
+ private config: P2PConfig;
191
75
 
192
- private blockStream;
76
+ private blockStream: L2BlockStream | undefined;
77
+
78
+ private txProvider: TxProvider;
79
+
80
+ private validatorAddresses: EthAddress[] = [];
193
81
 
194
82
  /**
195
83
  * In-memory P2P client constructor.
@@ -197,47 +85,79 @@ export class P2PClient<T extends P2PClientType = P2PClientType.Full>
197
85
  * @param l2BlockSource - P2P client's source for fetching existing blocks.
198
86
  * @param txPool - The client's instance of a transaction pool. Defaults to in-memory implementation.
199
87
  * @param p2pService - The concrete instance of p2p networking to use.
200
- * @param keepProvenTxsFor - How many blocks have to pass after a block is proven before its txs are deleted (zero to delete immediately once proven).
201
88
  * @param log - A logger.
202
89
  */
203
90
  constructor(
204
91
  _clientType: T,
205
- store: AztecAsyncKVStore,
206
- private l2BlockSource: L2BlockSource,
92
+ private store: AztecAsyncKVStore,
93
+ private l2BlockSource: L2BlockSource & ContractDataSource,
207
94
  mempools: MemPools<T>,
208
95
  private p2pService: P2PService,
96
+ private txCollection: TxCollection,
209
97
  config: Partial<P2PConfig> = {},
210
- telemetry: TelemetryClient = getTelemetryClient(),
98
+ private _dateProvider: DateProvider = new DateProvider(),
99
+ private telemetry: TelemetryClient = getTelemetryClient(),
211
100
  private log = createLogger('p2p'),
212
101
  ) {
213
102
  super(telemetry, 'P2PClient');
214
103
 
215
- const { keepProvenTxsInPoolFor, blockCheckIntervalMS, blockRequestBatchSize, keepAttestationsInPoolFor } = {
216
- ...getP2PDefaultConfig(),
217
- ...config,
218
- };
219
- this.keepProvenTxsFor = keepProvenTxsInPoolFor;
220
- this.keepAttestationsInPoolFor = keepAttestationsInPoolFor;
221
-
222
- const tracer = telemetry.getTracer('P2PL2BlockStream');
223
- const logger = createLogger('p2p:l2-block-stream');
224
- this.blockStream = new TraceableL2BlockStream(l2BlockSource, this, this, tracer, 'P2PL2BlockStream', logger, {
225
- batchSize: blockRequestBatchSize,
226
- pollIntervalMS: blockCheckIntervalMS,
104
+ this.config = { ...getP2PDefaultConfig(), ...config };
105
+ this.txPool = mempools.txPool;
106
+ this.attestationPool = mempools.attestationPool!;
107
+
108
+ this.txProvider = new TxProvider(
109
+ this.txCollection,
110
+ this.txPool,
111
+ this,
112
+ this.log.createChild('tx-provider'),
113
+ this.telemetry,
114
+ );
115
+
116
+ // Default to collecting all txs when we see a valid proposal
117
+ // This can be overridden by the validator client to attest, and it will call getTxsForBlockProposal on its own
118
+ // TODO(palla/txs): We should not trigger a request for txs on a proposal before fully validating it. We need to bring
119
+ // validator-client code into here so we can validate a proposal is reasonable.
120
+ this.registerBlockProposalHandler(async (block, sender) => {
121
+ this.log.debug(`Received block proposal from ${sender.toString()}`);
122
+ // TODO(palla/txs): Need to subtract validatorReexecuteDeadlineMs from this deadline (see ValidatorClient.getReexecutionDeadline)
123
+ const constants = this.txCollection.getConstants();
124
+ const nextSlotTimestampSeconds = Number(getTimestampForSlot(block.slotNumber.toBigInt() + 1n, constants));
125
+ const deadline = new Date(nextSlotTimestampSeconds * 1000);
126
+ const parentBlock = await this.l2BlockSource.getBlockHeaderByArchive(block.payload.header.lastArchiveRoot);
127
+ if (!parentBlock) {
128
+ this.log.debug(`Cannot collect txs for proposal as parent block not found`);
129
+ return;
130
+ }
131
+ const blockNumber = parentBlock.getBlockNumber() + 1;
132
+ await this.txProvider.getTxsForBlockProposal(block, blockNumber, { pinnedPeer: sender, deadline });
133
+ return undefined;
227
134
  });
228
135
 
136
+ // REFACTOR: Try replacing these with an L2TipsStore
229
137
  this.synchedBlockHashes = store.openMap('p2p_pool_block_hashes');
230
138
  this.synchedLatestBlockNumber = store.openSingleton('p2p_pool_last_l2_block');
231
139
  this.synchedProvenBlockNumber = store.openSingleton('p2p_pool_last_proven_l2_block');
140
+ this.synchedFinalizedBlockNumber = store.openSingleton('p2p_pool_last_finalized_l2_block');
141
+ this.synchedLatestSlot = store.openSingleton('p2p_pool_last_l2_slot');
142
+ }
232
143
 
233
- this.txPool = mempools.txPool;
234
- this.attestationPool = mempools.attestationPool!;
144
+ public registerThisValidatorAddresses(addresses: EthAddress[]): void {
145
+ this.validatorAddresses = [...addresses];
146
+ this.p2pService.registerThisValidatorAddresses(this.validatorAddresses);
147
+ }
148
+
149
+ public clear(): Promise<void> {
150
+ return this.store.clear();
235
151
  }
236
152
 
237
153
  public isP2PClient(): true {
238
154
  return true;
239
155
  }
240
156
 
157
+ public getTxProvider(): TxProvider {
158
+ return this.txProvider;
159
+ }
160
+
241
161
  public getPeers(includePending?: boolean): Promise<PeerInfo[]> {
242
162
  return Promise.resolve(this.p2pService.getPeers(includePending));
243
163
  }
@@ -246,33 +166,48 @@ export class P2PClient<T extends P2PClientType = P2PClientType.Full>
246
166
  return this.synchedBlockHashes.getAsync(number);
247
167
  }
248
168
 
169
+ public updateP2PConfig(config: Partial<P2PConfig>): Promise<void> {
170
+ this.txPool.updateConfig(config);
171
+ this.p2pService.updateConfig(config);
172
+ return Promise.resolve();
173
+ }
174
+
249
175
  public async getL2Tips(): Promise<L2Tips> {
250
176
  const latestBlockNumber = await this.getSyncedLatestBlockNum();
251
177
  let latestBlockHash: string | undefined;
178
+
252
179
  const provenBlockNumber = await this.getSyncedProvenBlockNum();
253
180
  let provenBlockHash: string | undefined;
254
181
 
182
+ const finalizedBlockNumber = await this.getSyncedFinalizedBlockNum();
183
+ let finalizedBlockHash: string | undefined;
184
+
255
185
  if (latestBlockNumber > 0) {
256
186
  latestBlockHash = await this.synchedBlockHashes.getAsync(latestBlockNumber);
257
187
  if (typeof latestBlockHash === 'undefined') {
258
- this.log.warn(`Block hash for latest block ${latestBlockNumber} not found`);
259
- throw new Error();
188
+ throw new Error(`Block hash for latest block ${latestBlockNumber} not found in p2p client`);
260
189
  }
261
190
  }
262
191
 
263
192
  if (provenBlockNumber > 0) {
264
193
  provenBlockHash = await this.synchedBlockHashes.getAsync(provenBlockNumber);
265
194
  if (typeof provenBlockHash === 'undefined') {
266
- this.log.warn(`Block hash for proven block ${provenBlockNumber} not found`);
267
- throw new Error();
195
+ throw new Error(`Block hash for proven block ${provenBlockNumber} not found in p2p client`);
196
+ }
197
+ }
198
+
199
+ if (finalizedBlockNumber > 0) {
200
+ finalizedBlockHash = await this.synchedBlockHashes.getAsync(finalizedBlockNumber);
201
+ if (typeof finalizedBlockHash === 'undefined') {
202
+ throw new Error(`Block hash for finalized block ${finalizedBlockNumber} not found in p2p client`);
268
203
  }
269
204
  }
270
205
 
271
- return Promise.resolve({
206
+ return {
272
207
  latest: { hash: latestBlockHash!, number: latestBlockNumber },
273
208
  proven: { hash: provenBlockHash!, number: provenBlockNumber },
274
- finalized: { hash: provenBlockHash!, number: provenBlockNumber },
275
- });
209
+ finalized: { hash: finalizedBlockHash!, number: finalizedBlockNumber },
210
+ };
276
211
  }
277
212
 
278
213
  public async handleBlockStreamEvent(event: L2BlockStreamEvent): Promise<void> {
@@ -281,17 +216,26 @@ export class P2PClient<T extends P2PClientType = P2PClientType.Full>
281
216
  case 'blocks-added':
282
217
  await this.handleLatestL2Blocks(event.blocks);
283
218
  break;
284
- case 'chain-finalized':
219
+ case 'chain-finalized': {
285
220
  // TODO (alexg): I think we can prune the block hashes map here
221
+ await this.setBlockHash(event.block);
222
+ const from = (await this.getSyncedFinalizedBlockNum()) + 1;
223
+ const limit = event.block.number - from + 1;
224
+ if (limit > 0) {
225
+ await this.handleFinalizedL2Blocks(await this.l2BlockSource.getBlocks(from, limit));
226
+ }
286
227
  break;
228
+ }
287
229
  case 'chain-proven': {
288
- const from = (await this.getSyncedProvenBlockNum()) + 1;
289
- const limit = event.blockNumber - from + 1;
290
- await this.handleProvenL2Blocks(await this.l2BlockSource.getBlocks(from, limit));
230
+ await this.setBlockHash(event.block);
231
+ this.txCollection.stopCollectingForBlocksUpTo(event.block.number);
232
+ await this.synchedProvenBlockNumber.set(event.block.number);
291
233
  break;
292
234
  }
293
235
  case 'chain-pruned':
294
- await this.handlePruneL2Blocks(event.blockNumber);
236
+ await this.setBlockHash(event.block);
237
+ this.txCollection.stopCollectingForBlocksAfter(event.block.number);
238
+ await this.handlePruneL2Blocks(event.block.number);
295
239
  break;
296
240
  default: {
297
241
  const _: never = event;
@@ -300,6 +244,12 @@ export class P2PClient<T extends P2PClientType = P2PClientType.Full>
300
244
  }
301
245
  }
302
246
 
247
+ private async setBlockHash(block: L2BlockId): Promise<void> {
248
+ if (block.hash !== undefined) {
249
+ await this.synchedBlockHashes.set(block.number, block.hash.toString());
250
+ }
251
+ }
252
+
303
253
  #assertIsReady() {
304
254
  // this.log.info('Checking if p2p client is ready, current state: ', this.currentState);
305
255
  if (!this.isReady()) {
@@ -320,123 +270,174 @@ export class P2PClient<T extends P2PClientType = P2PClientType.Full>
320
270
  }
321
271
 
322
272
  // get the current latest block numbers
323
- this.latestBlockNumberAtStart = await this.l2BlockSource.getBlockNumber();
324
- this.provenBlockNumberAtStart = await this.l2BlockSource.getProvenBlockNumber();
273
+ const latestBlockNumbers = await this.l2BlockSource.getL2Tips();
274
+ this.latestBlockNumberAtStart = latestBlockNumbers.latest.number;
275
+ this.provenBlockNumberAtStart = latestBlockNumbers.proven.number;
276
+ this.finalizedBlockNumberAtStart = latestBlockNumbers.finalized.number;
325
277
 
326
278
  const syncedLatestBlock = (await this.getSyncedLatestBlockNum()) + 1;
327
279
  const syncedProvenBlock = (await this.getSyncedProvenBlockNum()) + 1;
280
+ const syncedFinalizedBlock = (await this.getSyncedFinalizedBlockNum()) + 1;
328
281
 
329
- // if there are blocks to be retrieved, go to a synching state
330
- if (syncedLatestBlock <= this.latestBlockNumberAtStart || syncedProvenBlock <= this.provenBlockNumberAtStart) {
282
+ if (
283
+ (await this.txPool.isEmpty()) &&
284
+ (this.attestationPool === undefined || (await this.attestationPool?.isEmpty()))
285
+ ) {
286
+ // if mempools are empty, we don't care about syncing prior blocks
287
+ this.initBlockStream(this.latestBlockNumberAtStart);
288
+ this.setCurrentState(P2PClientState.RUNNING);
289
+ this.syncPromise = Promise.resolve();
290
+ await this.p2pService.start();
291
+ this.log.info(`Starting p2p client from block ${this.latestBlockNumberAtStart} with empty mempools`);
292
+ } else if (
293
+ syncedLatestBlock <= this.latestBlockNumberAtStart ||
294
+ syncedProvenBlock <= this.provenBlockNumberAtStart ||
295
+ syncedFinalizedBlock <= this.finalizedBlockNumberAtStart
296
+ ) {
297
+ // if there are blocks to be retrieved, go to a synching state
298
+ // this gets resolved on `startServiceIfSynched`
299
+ this.initBlockStream();
331
300
  this.setCurrentState(P2PClientState.SYNCHING);
332
301
  this.syncPromise = new Promise(resolve => {
333
302
  this.syncResolve = resolve;
334
303
  });
335
- this.log.verbose(`Starting sync from ${syncedLatestBlock} (last proven ${syncedProvenBlock})`);
304
+ this.log.info(`Initiating p2p sync from ${syncedLatestBlock}`, {
305
+ syncedLatestBlock,
306
+ syncedProvenBlock,
307
+ syncedFinalizedBlock,
308
+ });
336
309
  } else {
337
310
  // if no blocks to be retrieved, go straight to running
311
+ this.initBlockStream();
338
312
  this.setCurrentState(P2PClientState.RUNNING);
339
313
  this.syncPromise = Promise.resolve();
340
314
  await this.p2pService.start();
341
- this.log.debug(`Block ${syncedLatestBlock} (proven ${syncedProvenBlock}) already beyond current block`);
315
+ this.log.info(`Starting P2P client synced to ${syncedLatestBlock}`, {
316
+ syncedLatestBlock,
317
+ syncedProvenBlock,
318
+ syncedFinalizedBlock,
319
+ });
342
320
  }
343
321
 
344
- this.blockStream.start();
345
- this.log.verbose(`Started block downloader from block ${syncedLatestBlock}`);
346
-
322
+ this.blockStream!.start();
323
+ await this.txCollection.start();
347
324
  return this.syncPromise;
348
325
  }
349
326
 
327
+ addReqRespSubProtocol(
328
+ subProtocol: ReqRespSubProtocol,
329
+ handler: ReqRespSubProtocolHandler,
330
+ validator: ReqRespSubProtocolValidators[ReqRespSubProtocol],
331
+ ): Promise<void> {
332
+ return this.p2pService.addReqRespSubProtocol(subProtocol, handler, validator);
333
+ }
334
+
335
+ private initBlockStream(startingBlock?: number) {
336
+ if (!this.blockStream) {
337
+ const { blockRequestBatchSize: batchSize, blockCheckIntervalMS: pollIntervalMS } = this.config;
338
+ this.blockStream = new TraceableL2BlockStream(
339
+ this.l2BlockSource,
340
+ this,
341
+ this,
342
+ this.telemetry.getTracer('P2PL2BlockStream'),
343
+ 'P2PL2BlockStream',
344
+ createLogger(`${this.log.module}:l2-block-stream`),
345
+ { batchSize, pollIntervalMS, startingBlock },
346
+ );
347
+ }
348
+ }
349
+
350
350
  /**
351
351
  * Allows consumers to stop the instance of the P2P client.
352
352
  * 'ready' will now return 'false' and the running promise that keeps the client synced is interrupted.
353
353
  */
354
354
  public async stop() {
355
355
  this.log.debug('Stopping p2p client...');
356
+ await tryStop(this.txCollection);
357
+ this.log.debug('Stopped tx collection service');
356
358
  await this.p2pService.stop();
357
359
  this.log.debug('Stopped p2p service');
358
- await this.blockStream.stop();
360
+ await this.blockStream?.stop();
359
361
  this.log.debug('Stopped block downloader');
360
362
  await this.runningPromise;
361
363
  this.setCurrentState(P2PClientState.STOPPED);
362
- this.log.info('P2P client stopped.');
364
+ this.log.info('P2P client stopped');
365
+ }
366
+
367
+ /** Triggers a sync to the archiver. Used for testing. */
368
+ public async sync() {
369
+ this.initBlockStream();
370
+ await this.blockStream!.sync();
363
371
  }
364
372
 
365
373
  @trackSpan('p2pClient.broadcastProposal', async proposal => ({
366
- [Attributes.BLOCK_NUMBER]: proposal.blockNumber.toNumber(),
367
374
  [Attributes.SLOT_NUMBER]: proposal.slotNumber.toNumber(),
368
375
  [Attributes.BLOCK_ARCHIVE]: proposal.archive.toString(),
369
376
  [Attributes.P2P_ID]: (await proposal.p2pMessageIdentifier()).toString(),
370
377
  }))
371
- public broadcastProposal(proposal: BlockProposal): void {
378
+ public broadcastProposal(proposal: BlockProposal): Promise<void> {
372
379
  this.log.verbose(`Broadcasting proposal for slot ${proposal.slotNumber.toNumber()} to peers`);
373
380
  return this.p2pService.propagate(proposal);
374
381
  }
375
382
 
376
- public async getAttestationsForSlot(slot: bigint, proposalId: string): Promise<BlockAttestation[]> {
377
- return (await this.attestationPool?.getAttestationsForSlot(slot, proposalId)) ?? [];
383
+ public async getAttestationsForSlot(slot: bigint, proposalId?: string): Promise<BlockAttestation[]> {
384
+ return (
385
+ (await (proposalId
386
+ ? this.attestationPool?.getAttestationsForSlotAndProposal(slot, proposalId)
387
+ : this.attestationPool?.getAttestationsForSlot(slot))) ?? []
388
+ );
389
+ }
390
+
391
+ public addAttestations(attestations: BlockAttestation[]): Promise<void> {
392
+ return this.attestationPool?.addAttestations(attestations) ?? Promise.resolve();
393
+ }
394
+
395
+ public deleteAttestation(attestation: BlockAttestation): Promise<void> {
396
+ return this.attestationPool?.deleteAttestations([attestation]) ?? Promise.resolve();
378
397
  }
379
398
 
380
399
  // REVIEW: https://github.com/AztecProtocol/aztec-packages/issues/7963
381
400
  // ^ This pattern is not my favorite (md)
382
- public registerBlockProposalHandler(handler: (block: BlockProposal) => Promise<BlockAttestation | undefined>): void {
401
+ public registerBlockProposalHandler(handler: P2PBlockReceivedCallback): void {
383
402
  this.p2pService.registerBlockReceivedCallback(handler);
384
403
  }
385
404
 
386
405
  /**
387
- * Requests the transactions with the given hashes from the network.
388
- *
389
- * If a transaction can be retrieved, it will be returned, if not an undefined
390
- * will be returned. In place.
391
- *
392
- * @param txHashes - The hashes of the transactions to request.
393
- * @returns A promise that resolves to an array of transactions or undefined.
394
- */
395
- public async requestTxs(txHashes: TxHash[]): Promise<(Tx | undefined)[]> {
396
- const res = await this.p2pService.sendBatchRequest(ReqRespSubProtocol.TX, txHashes);
397
- return Promise.resolve(res ?? []);
398
- }
399
-
400
- /**
401
- * Uses the Request Response protocol to request a transaction from the network.
402
- *
403
- * If the underlying request response protocol fails, then we return undefined.
404
- * If it succeeds then we add the transaction to our transaction pool and return.
405
- *
406
- * @param txHash - The hash of the transaction to request.
407
- * @returns A promise that resolves to a transaction or undefined.
406
+ * Uses the batched Request Response protocol to request a set of transactions from the network.
408
407
  */
409
- public async requestTxByHash(txHash: TxHash): Promise<Tx | undefined> {
410
- const tx = await this.p2pService.sendRequest(ReqRespSubProtocol.TX, txHash);
408
+ public async requestTxsByHash(txHashes: TxHash[], pinnedPeerId: PeerId | undefined): Promise<Tx[]> {
409
+ const timeoutMs = 8000; // Longer timeout for now
410
+ const maxRetryAttempts = 10; // Keep retrying within the timeout
411
+ const requests = chunkTxHashesRequest(txHashes);
412
+ const maxPeers = Math.min(Math.ceil(requests.length / 3), 10);
413
+
414
+ const txBatches = await this.p2pService.sendBatchRequest(
415
+ ReqRespSubProtocol.TX,
416
+ requests,
417
+ pinnedPeerId,
418
+ timeoutMs,
419
+ maxPeers,
420
+ maxRetryAttempts,
421
+ );
411
422
 
412
- if (tx) {
413
- this.log.debug(`Received tx ${txHash.toString()} from peer`);
414
- await this.txPool.addTxs([tx]);
415
- } else {
416
- this.log.debug(`Failed to receive tx ${txHash.toString()} from peer`);
423
+ const txs = txBatches.flat();
424
+ if (txs.length > 0) {
425
+ await this.txPool.addTxs(txs);
417
426
  }
418
427
 
419
- return tx;
420
- }
421
-
422
- /**
423
- * Uses the batched Request Response protocol to request a set of transactions from the network.
424
- */
425
- public async requestTxsByHash(txHashes: TxHash[]): Promise<Tx[]> {
426
- const txs = (await this.p2pService.sendBatchRequest(ReqRespSubProtocol.TX, txHashes)) ?? [];
427
- await this.txPool.addTxs(txs);
428
428
  const txHashesStr = txHashes.map(tx => tx.toString()).join(', ');
429
- this.log.debug(`Received batched txs ${txHashesStr} (${txs.length} / ${txHashes.length}}) from peers`);
430
- return txs as Tx[];
429
+ this.log.debug(`Requested txs ${txHashesStr} (${txs.length} / ${txHashes.length}) from peers`);
430
+
431
+ // We return all transactions, even the not found ones to the caller, such they can handle missing items themselves.
432
+ return txs;
431
433
  }
432
434
 
433
- public getPendingTxs(): Promise<Tx[]> {
434
- return Promise.resolve(this.getTxs('pending'));
435
+ public getPendingTxs(limit?: number, after?: TxHash): Promise<Tx[]> {
436
+ return this.getTxs('pending', limit, after);
435
437
  }
436
438
 
437
- public async getPendingTxCount(): Promise<number> {
438
- const pendingTxs = await this.txPool.getPendingTxHashes();
439
- return pendingTxs.length;
439
+ public getPendingTxCount(): Promise<number> {
440
+ return this.txPool.getPendingTxCount();
440
441
  }
441
442
 
442
443
  public async *iteratePendingTxs(): AsyncIterableIterator<Tx> {
@@ -450,23 +451,60 @@ export class P2PClient<T extends P2PClientType = P2PClientType.Full>
450
451
 
451
452
  /**
452
453
  * Returns all transactions in the transaction pool.
454
+ * @param filter - The type of txs to return
455
+ * @param limit - How many txs to return
456
+ * @param after - If paginating, the last known tx hash. Will return txs after this hash
453
457
  * @returns An array of Txs.
454
458
  */
455
- public async getTxs(filter: 'all' | 'pending' | 'mined'): Promise<Tx[]> {
459
+ public async getTxs(filter: 'all' | 'pending' | 'mined', limit?: number, after?: TxHash): Promise<Tx[]> {
460
+ if (limit !== undefined && limit <= 0) {
461
+ throw new TypeError('limit must be greater than 0');
462
+ }
463
+
464
+ let txs: Tx[] | undefined = undefined;
465
+ let txHashes: TxHash[];
466
+
456
467
  if (filter === 'all') {
457
- return this.txPool.getAllTxs();
468
+ txs = await this.txPool.getAllTxs();
469
+ txHashes = await Promise.all(txs.map(tx => tx.getTxHash()));
458
470
  } else if (filter === 'mined') {
459
- const minedHashes = await this.txPool.getMinedTxHashes();
460
- const minedTx = await Promise.all(minedHashes.map(([txHash]) => this.txPool.getTxByHash(txHash)));
461
- return minedTx.filter((tx): tx is Tx => !!tx);
471
+ const minedTxHashes = await this.txPool.getMinedTxHashes();
472
+ txHashes = minedTxHashes.map(([txHash]) => txHash);
462
473
  } else if (filter === 'pending') {
463
- const pendingHashses = await this.txPool.getPendingTxHashes();
464
- const pendingTxs = await Promise.all(pendingHashses.map(txHash => this.txPool.getTxByHash(txHash)));
465
- return pendingTxs.filter((tx): tx is Tx => !!tx);
474
+ txHashes = await this.txPool.getPendingTxHashes();
466
475
  } else {
467
476
  const _: never = filter;
468
477
  throw new Error(`Unknown filter ${filter}`);
469
478
  }
479
+
480
+ let startIndex = 0;
481
+ let endIndex: number | undefined = undefined;
482
+
483
+ if (after) {
484
+ startIndex = txHashes.findIndex(txHash => after.equals(txHash));
485
+
486
+ // if we can't find the last tx in our set then return an empty array as pagination is no longer valid.
487
+ if (startIndex === -1) {
488
+ return [];
489
+ }
490
+
491
+ // increment by one because we don't want to return the same tx again
492
+ startIndex++;
493
+ }
494
+
495
+ if (limit !== undefined) {
496
+ endIndex = startIndex + limit;
497
+ }
498
+
499
+ txHashes = txHashes.slice(startIndex, endIndex);
500
+ if (txs) {
501
+ txs = txs.slice(startIndex, endIndex);
502
+ } else {
503
+ const maybeTxs = await Promise.all(txHashes.map(txHash => this.txPool.getTxByHash(txHash)));
504
+ txs = maybeTxs.filter((tx): tx is Tx => !!tx);
505
+ }
506
+
507
+ return txs;
470
508
  }
471
509
 
472
510
  /**
@@ -479,26 +517,25 @@ export class P2PClient<T extends P2PClientType = P2PClientType.Full>
479
517
  }
480
518
 
481
519
  /**
482
- * Returns a transaction in the transaction pool by its hash.
483
- * If the transaction is not in the pool, it will be requested from the network.
484
- * @param txHash - Hash of the transaction to look for in the pool.
485
- * @returns A single tx or undefined.
520
+ * Returns transactions in the transaction pool by hash.
521
+ * @param txHashes - Hashes of the transactions to look for.
522
+ * @returns The txs found, in the same order as the requested hashes. If a tx is not found, it will be undefined.
486
523
  */
487
- async getTxByHash(txHash: TxHash): Promise<Tx | undefined> {
488
- const tx = await this.txPool.getTxByHash(txHash);
489
- if (tx) {
490
- return tx;
491
- }
492
- return this.requestTxByHash(txHash);
524
+ getTxsByHashFromPool(txHashes: TxHash[]): Promise<(Tx | undefined)[]> {
525
+ return this.txPool.getTxsByHash(txHashes);
526
+ }
527
+
528
+ hasTxsInPool(txHashes: TxHash[]): Promise<boolean[]> {
529
+ return this.txPool.hasTxs(txHashes);
493
530
  }
494
531
 
495
532
  /**
496
533
  * Returns transactions in the transaction pool by hash.
497
534
  * If a transaction is not in the pool, it will be requested from the network.
498
535
  * @param txHashes - Hashes of the transactions to look for.
499
- * @returns The txs found, not necessarily on the same order as the hashes.
536
+ * @returns The txs found, or undefined if not found in the order requested.
500
537
  */
501
- async getTxsByHash(txHashes: TxHash[]): Promise<Tx[]> {
538
+ async getTxsByHash(txHashes: TxHash[], pinnedPeerId: PeerId | undefined): Promise<(Tx | undefined)[]> {
502
539
  const txs = await Promise.all(txHashes.map(txHash => this.txPool.getTxByHash(txHash)));
503
540
  const missingTxHashes = txs
504
541
  .map((tx, index) => [tx, index] as const)
@@ -509,8 +546,30 @@ export class P2PClient<T extends P2PClientType = P2PClientType.Full>
509
546
  return txs as Tx[];
510
547
  }
511
548
 
512
- const missingTxs = await this.requestTxsByHash(missingTxHashes);
513
- return txs.filter((tx): tx is Tx => !!tx).concat(missingTxs);
549
+ const missingTxs = await this.requestTxsByHash(missingTxHashes, pinnedPeerId);
550
+ // TODO: optimize
551
+ // Merge the found txs in order
552
+ const mergingTxs = txHashes.map(txHash => {
553
+ // Is it in the txs list from the mempool?
554
+ for (const tx of txs) {
555
+ if (tx !== undefined && tx.getTxHash().equals(txHash)) {
556
+ return tx;
557
+ }
558
+ }
559
+
560
+ // Is it in the fetched missing txs?
561
+ // Note: this is an O(n^2) operation, but we expect the number of missing txs to be small.
562
+ for (const tx of missingTxs) {
563
+ if (tx.getTxHash().equals(txHash)) {
564
+ return tx;
565
+ }
566
+ }
567
+
568
+ // Otherwise return undefined
569
+ return undefined;
570
+ });
571
+
572
+ return mergingTxs;
514
573
  }
515
574
 
516
575
  /**
@@ -528,9 +587,20 @@ export class P2PClient<T extends P2PClientType = P2PClientType.Full>
528
587
  * @returns Empty promise.
529
588
  **/
530
589
  public async sendTx(tx: Tx): Promise<void> {
590
+ const addedCount = await this.addTxsToPool([tx]);
591
+ const txAddedSuccessfully = addedCount === 1;
592
+ if (txAddedSuccessfully) {
593
+ await this.p2pService.propagate(tx);
594
+ }
595
+ }
596
+
597
+ /**
598
+ * Adds transactions to the pool. Does not send to peers or validate the txs.
599
+ * @param txs - The transactions.
600
+ **/
601
+ public async addTxsToPool(txs: Tx[]): Promise<number> {
531
602
  this.#assertIsReady();
532
- await this.txPool.addTxs([tx]);
533
- this.p2pService.propagate(tx);
603
+ return await this.txPool.addTxs(txs);
534
604
  }
535
605
 
536
606
  /**
@@ -538,7 +608,7 @@ export class P2PClient<T extends P2PClientType = P2PClientType.Full>
538
608
  * @param txHash - Hash of the tx to query.
539
609
  * @returns Pending or mined depending on its status, or undefined if not found.
540
610
  */
541
- public getTxStatus(txHash: TxHash): Promise<'pending' | 'mined' | undefined> {
611
+ public getTxStatus(txHash: TxHash): Promise<'pending' | 'mined' | 'deleted' | undefined> {
542
612
  return this.txPool.getTxStatus(txHash);
543
613
  }
544
614
 
@@ -585,6 +655,15 @@ export class P2PClient<T extends P2PClientType = P2PClientType.Full>
585
655
  return (await this.synchedProvenBlockNumber.getAsync()) ?? INITIAL_L2_BLOCK_NUM - 1;
586
656
  }
587
657
 
658
+ public async getSyncedFinalizedBlockNum(): Promise<number> {
659
+ return (await this.synchedFinalizedBlockNumber.getAsync()) ?? INITIAL_L2_BLOCK_NUM - 1;
660
+ }
661
+
662
+ /** Returns latest L2 slot for which we have seen an L2 block. */
663
+ public async getSyncedLatestSlot(): Promise<bigint> {
664
+ return (await this.synchedLatestSlot.getAsync()) ?? BigInt(0);
665
+ }
666
+
588
667
  /**
589
668
  * Method to check the status the p2p client.
590
669
  * @returns Information about p2p client status: state & syncedToBlockNum.
@@ -613,20 +692,7 @@ export class P2PClient<T extends P2PClientType = P2PClientType.Full>
613
692
  private async markTxsAsMinedFromBlocks(blocks: L2Block[]): Promise<void> {
614
693
  for (const block of blocks) {
615
694
  const txHashes = block.body.txEffects.map(txEffect => txEffect.txHash);
616
- await this.txPool.markAsMined(txHashes, block.number);
617
- }
618
- }
619
-
620
- /**
621
- * Deletes txs from these blocks.
622
- * @param blocks - A list of existing blocks with txs that the P2P client needs to ensure the tx pool is reconciled with.
623
- * @returns Empty promise.
624
- */
625
- private async deleteTxsFromBlocks(blocks: L2Block[]): Promise<void> {
626
- this.log.debug(`Deleting txs from blocks ${blocks[0].number} to ${blocks[blocks.length - 1].number}`);
627
- for (const block of blocks) {
628
- const txHashes = block.body.txEffects.map(txEffect => txEffect.txHash);
629
- await this.txPool.deleteTxs(txHashes);
695
+ await this.txPool.markAsMined(txHashes, block.getBlockHeader());
630
696
  }
631
697
  }
632
698
 
@@ -635,54 +701,83 @@ export class P2PClient<T extends P2PClientType = P2PClientType.Full>
635
701
  * @param blocks - A list of existing blocks with txs that the P2P client needs to ensure the tx pool is reconciled with.
636
702
  * @returns Empty promise.
637
703
  */
638
- private async handleLatestL2Blocks(blocks: L2Block[]): Promise<void> {
704
+ private async handleLatestL2Blocks(blocks: PublishedL2Block[]): Promise<void> {
639
705
  if (!blocks.length) {
640
706
  return Promise.resolve();
641
707
  }
642
708
 
643
- await this.markTxsAsMinedFromBlocks(blocks);
644
- const lastBlockNum = blocks[blocks.length - 1].number;
709
+ await this.markTxsAsMinedFromBlocks(blocks.map(b => b.block));
710
+ await this.startCollectingMissingTxs(blocks.map(b => b.block));
711
+
712
+ const lastBlock = blocks.at(-1)!.block;
713
+
645
714
  await Promise.all(
646
- blocks.map(async block => this.synchedBlockHashes.set(block.number, (await block.hash()).toString())),
715
+ blocks.map(async block =>
716
+ this.setBlockHash({
717
+ number: block.block.number,
718
+ hash: await block.block.hash().then(h => h.toString()),
719
+ }),
720
+ ),
647
721
  );
648
- await this.synchedLatestBlockNumber.set(lastBlockNum);
649
- this.log.verbose(`Synched to latest block ${lastBlockNum}`);
722
+
723
+ await this.synchedLatestBlockNumber.set(lastBlock.number);
724
+ await this.synchedLatestSlot.set(lastBlock.header.getSlot());
725
+ this.log.verbose(`Synched to latest block ${lastBlock.number}`);
650
726
  await this.startServiceIfSynched();
651
727
  }
652
728
 
729
+ /** Request txs for unproven blocks so the prover node has more chances to get them. */
730
+ private async startCollectingMissingTxs(blocks: L2Block[]): Promise<void> {
731
+ try {
732
+ // TODO(#15435): If the archiver has lagged behind L1, the reported proven block number may
733
+ // be much lower than the actual one, and it does not update until the pending chain is
734
+ // fully synced. This could lead to a ton of tx collection requests for blocks that
735
+ // are already proven, but the archiver has not yet updated its state. Until this is properly
736
+ // fixed, it is mitigated by the expiration date of collection requests, which depends on
737
+ // the slot number of the block.
738
+ const provenBlockNumber = await this.l2BlockSource.getProvenBlockNumber();
739
+ const unprovenBlocks = blocks.filter(block => block.number > provenBlockNumber);
740
+ for (const block of unprovenBlocks) {
741
+ const txHashes = block.body.txEffects.map(txEffect => txEffect.txHash);
742
+ const missingTxHashes = await this.txPool
743
+ .hasTxs(txHashes)
744
+ .then(availability => txHashes.filter((_, index) => !availability[index]));
745
+ if (missingTxHashes.length > 0) {
746
+ this.log.verbose(
747
+ `Starting collection of ${missingTxHashes.length} missing txs for unproven mined block ${block.number}`,
748
+ { missingTxHashes, blockNumber: block.number, blockHash: await block.hash().then(h => h.toString()) },
749
+ );
750
+ this.txCollection.startCollecting(block, missingTxHashes);
751
+ }
752
+ }
753
+ } catch (err) {
754
+ this.log.error(`Error while starting collection of missing txs for unproven blocks`, err);
755
+ }
756
+ }
757
+
653
758
  /**
654
- * Handles new proven blocks by deleting the txs in them, or by deleting the txs in blocks `keepProvenTxsFor` ago.
655
- * @param blocks - A list of proven L2 blocks.
759
+ * Handles new finalized blocks by deleting the txs and attestations in them.
760
+ * @param blocks - A list of finalized L2 blocks.
656
761
  * @returns Empty promise.
657
762
  */
658
- private async handleProvenL2Blocks(blocks: L2Block[]): Promise<void> {
763
+ private async handleFinalizedL2Blocks(blocks: L2Block[]): Promise<void> {
659
764
  if (!blocks.length) {
660
765
  return Promise.resolve();
661
766
  }
767
+ this.log.debug(`Handling finalized blocks ${blocks.length} up to ${blocks.at(-1)?.number}`);
662
768
 
663
- const firstBlockNum = blocks[0].number;
664
769
  const lastBlockNum = blocks[blocks.length - 1].number;
665
- const lastBlockSlot = blocks[blocks.length - 1].header.globalVariables.slotNumber.toBigInt();
666
-
667
- // If keepProvenTxsFor is 0, we delete all txs from all proven blocks.
668
- if (this.keepProvenTxsFor === 0) {
669
- await this.deleteTxsFromBlocks(blocks);
670
- } else if (lastBlockNum - this.keepProvenTxsFor >= INITIAL_L2_BLOCK_NUM) {
671
- const fromBlock = Math.max(INITIAL_L2_BLOCK_NUM, firstBlockNum - this.keepProvenTxsFor);
672
- const toBlock = lastBlockNum - this.keepProvenTxsFor;
673
- const limit = toBlock - fromBlock + 1;
674
- const blocksToDeleteTxsFrom = await this.l2BlockSource.getBlocks(fromBlock, limit, true);
675
- await this.deleteTxsFromBlocks(blocksToDeleteTxsFrom);
676
- }
770
+ const lastBlockSlot = blocks[blocks.length - 1].header.getSlot();
677
771
 
678
- // We delete attestations older than the last block slot minus the number of slots we want to keep in the pool.
679
- const lastBlockSlotMinusKeepAttestationsInPoolFor = lastBlockSlot - BigInt(this.keepAttestationsInPoolFor);
680
- if (lastBlockSlotMinusKeepAttestationsInPoolFor >= BigInt(INITIAL_L2_BLOCK_NUM)) {
681
- await this.attestationPool?.deleteAttestationsOlderThan(lastBlockSlotMinusKeepAttestationsInPoolFor);
682
- }
772
+ const txHashes = blocks.flatMap(block => block.body.txEffects.map(txEffect => txEffect.txHash));
773
+ this.log.debug(`Deleting ${txHashes.length} txs from pool from finalized blocks up to ${lastBlockNum}`);
774
+ await this.txPool.deleteTxs(txHashes, { permanently: true });
775
+ await this.txPool.cleanupDeletedMinedTxs(lastBlockNum);
776
+
777
+ await this.attestationPool?.deleteAttestationsOlderThan(lastBlockSlot);
683
778
 
684
- await this.synchedProvenBlockNumber.set(lastBlockNum);
685
- this.log.debug(`Synched to proven block ${lastBlockNum}`);
779
+ await this.synchedFinalizedBlockNumber.set(lastBlockNum);
780
+ this.log.debug(`Synched to finalized block ${lastBlockNum} at slot ${lastBlockSlot}`);
686
781
 
687
782
  await this.startServiceIfSynched();
688
783
  }
@@ -692,48 +787,70 @@ export class P2PClient<T extends P2PClientType = P2PClientType.Full>
692
787
  * @param latestBlock - The block number the chain was pruned to.
693
788
  */
694
789
  private async handlePruneL2Blocks(latestBlock: number): Promise<void> {
695
- const txsToDelete: TxHash[] = [];
790
+ const txsToDelete = new Map<string, TxHash>();
791
+ const minedTxs = await this.txPool.getMinedTxHashes();
792
+
793
+ // Find transactions that reference pruned blocks in their historical header
696
794
  for (const tx of await this.txPool.getAllTxs()) {
697
795
  // every tx that's been generated against a block that has now been pruned is no longer valid
698
- if (tx.data.constants.historicalHeader.globalVariables.blockNumber.toNumber() > latestBlock) {
699
- txsToDelete.push(await tx.getTxHash());
796
+ if (tx.data.constants.anchorBlockHeader.globalVariables.blockNumber > latestBlock) {
797
+ const txHash = tx.getTxHash();
798
+ txsToDelete.set(txHash.toString(), txHash);
700
799
  }
701
800
  }
702
801
 
703
- this.log.info(
704
- `Detected chain prune. Removing invalid txs count=${
705
- txsToDelete.length
706
- } newLatestBlock=${latestBlock} previousLatestBlock=${this.getSyncedLatestBlockNum()}`,
707
- );
802
+ this.log.info(`Detected chain prune. Removing ${txsToDelete.size} txs built against pruned blocks.`, {
803
+ newLatestBlock: latestBlock,
804
+ previousLatestBlock: await this.getSyncedLatestBlockNum(),
805
+ txsToDelete: Array.from(txsToDelete.keys()),
806
+ });
708
807
 
709
808
  // delete invalid txs (both pending and mined)
710
- await this.txPool.deleteTxs(txsToDelete);
809
+ await this.txPool.deleteTxs(Array.from(txsToDelete.values()));
711
810
 
712
811
  // everything left in the mined set was built against a block on the proven chain so its still valid
713
- // move back to pending the txs that were reorged out of the chain
812
+ // move back to pending the txs that were reorged out of the chain, unless txPoolDeleteTxsAfterReorg is set,
813
+ // in which case we clean them up to avoid potential reorg loops
714
814
  // NOTE: we can't move _all_ txs back to pending because the tx pool could keep hold of mined txs for longer
715
815
  // (see this.keepProvenTxsFor)
716
- const txsToMoveToPending: TxHash[] = [];
717
- for (const [txHash, blockNumber] of await this.txPool.getMinedTxHashes()) {
718
- if (blockNumber > latestBlock) {
719
- txsToMoveToPending.push(txHash);
816
+ const minedTxsFromReorg: TxHash[] = [];
817
+ for (const [txHash, blockNumber] of minedTxs) {
818
+ // We keep the txsToDelete out of this list as they have already been deleted above
819
+ if (blockNumber > latestBlock && !txsToDelete.has(txHash.toString())) {
820
+ minedTxsFromReorg.push(txHash);
720
821
  }
721
822
  }
722
823
 
723
- this.log.info(`Moving ${txsToMoveToPending.length} mined txs back to pending`);
724
- await this.txPool.markMinedAsPending(txsToMoveToPending);
824
+ if (this.config.txPoolDeleteTxsAfterReorg) {
825
+ this.log.info(`Deleting ${minedTxsFromReorg.length} mined txs from reorg`);
826
+ await this.txPool.deleteTxs(minedTxsFromReorg);
827
+ } else {
828
+ this.log.info(`Moving ${minedTxsFromReorg.length} mined txs from reorg back to pending`);
829
+ await this.txPool.markMinedAsPending(minedTxsFromReorg);
830
+ }
725
831
 
726
832
  await this.synchedLatestBlockNumber.set(latestBlock);
727
833
  // no need to update block hashes, as they will be updated as new blocks are added
728
834
  }
729
835
 
730
836
  private async startServiceIfSynched() {
837
+ if (this.currentState !== P2PClientState.SYNCHING) {
838
+ return;
839
+ }
840
+ const syncedFinalizedBlock = await this.getSyncedFinalizedBlockNum();
841
+ const syncedProvenBlock = await this.getSyncedProvenBlockNum();
842
+ const syncedLatestBlock = await this.getSyncedLatestBlockNum();
843
+
731
844
  if (
732
- this.currentState === P2PClientState.SYNCHING &&
733
- (await this.getSyncedLatestBlockNum()) >= this.latestBlockNumberAtStart &&
734
- (await this.getSyncedProvenBlockNum()) >= this.provenBlockNumberAtStart
845
+ syncedLatestBlock >= this.latestBlockNumberAtStart &&
846
+ syncedProvenBlock >= this.provenBlockNumberAtStart &&
847
+ syncedFinalizedBlock >= this.finalizedBlockNumberAtStart
735
848
  ) {
736
- this.log.debug(`Synched to blocks at start`);
849
+ this.log.info(`Completed P2P client sync to block ${syncedLatestBlock}. Starting service.`, {
850
+ syncedLatestBlock,
851
+ syncedProvenBlock,
852
+ syncedFinalizedBlock,
853
+ });
737
854
  this.setCurrentState(P2PClientState.RUNNING);
738
855
  if (this.syncResolve !== undefined) {
739
856
  this.syncResolve();
@@ -751,4 +868,20 @@ export class P2PClient<T extends P2PClientType = P2PClientType.Full>
751
868
  this.currentState = newState;
752
869
  this.log.debug(`Moved from state ${P2PClientState[oldState]} to ${P2PClientState[this.currentState]}`);
753
870
  }
871
+
872
+ public validate(txs: Tx[]): Promise<void> {
873
+ return this.p2pService.validate(txs);
874
+ }
875
+
876
+ /**
877
+ * Marks transactions as non-evictable in the pool.
878
+ * @param txHashes - Hashes of the transactions to mark as non-evictable.
879
+ */
880
+ public markTxsAsNonEvictable(txHashes: TxHash[]): Promise<void> {
881
+ return this.txPool.markTxsAsNonEvictable(txHashes);
882
+ }
883
+
884
+ public handleAuthRequestFromPeer(authRequest: AuthRequest, peerId: PeerId): Promise<StatusMessage> {
885
+ return this.p2pService.handleAuthRequestFromPeer(authRequest, peerId);
886
+ }
754
887
  }