@aztec/p2p 0.0.0-test.0 → 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
@@ -6,23 +6,24 @@ function _ts_decorate(decorators, target, key, desc) {
6
6
  }
7
7
  import { INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
8
8
  import { createLogger } from '@aztec/foundation/log';
9
+ import { DateProvider } from '@aztec/foundation/timer';
10
+ import { getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
11
+ import { tryStop } from '@aztec/stdlib/interfaces/server';
9
12
  import { Attributes, TraceableL2BlockStream, WithTracer, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
10
13
  import { getP2PDefaultConfig } from '../config.js';
11
14
  import { ReqRespSubProtocol } from '../services/reqresp/interface.js';
12
- /**
13
- * Enum defining the possible states of the p2p client.
14
- */ export var P2PClientState = /*#__PURE__*/ function(P2PClientState) {
15
- P2PClientState[P2PClientState["IDLE"] = 0] = "IDLE";
16
- P2PClientState[P2PClientState["SYNCHING"] = 1] = "SYNCHING";
17
- P2PClientState[P2PClientState["RUNNING"] = 2] = "RUNNING";
18
- P2PClientState[P2PClientState["STOPPED"] = 3] = "STOPPED";
19
- return P2PClientState;
20
- }({});
15
+ import { chunkTxHashesRequest } from '../services/reqresp/protocols/tx.js';
16
+ import { TxProvider } from '../services/tx_provider.js';
17
+ import { P2PClientState } from './interface.js';
21
18
  /**
22
19
  * The P2P client implementation.
23
20
  */ export class P2PClient extends WithTracer {
21
+ store;
24
22
  l2BlockSource;
25
23
  p2pService;
24
+ txCollection;
25
+ _dateProvider;
26
+ telemetry;
26
27
  log;
27
28
  /** The JS promise that will be running to keep the client's data in sync. Can be interrupted if the client is stopped. */ runningPromise;
28
29
  currentState;
@@ -30,71 +31,115 @@ import { ReqRespSubProtocol } from '../services/reqresp/interface.js';
30
31
  syncResolve;
31
32
  latestBlockNumberAtStart;
32
33
  provenBlockNumberAtStart;
34
+ finalizedBlockNumberAtStart;
33
35
  synchedBlockHashes;
34
36
  synchedLatestBlockNumber;
35
37
  synchedProvenBlockNumber;
38
+ synchedFinalizedBlockNumber;
39
+ synchedLatestSlot;
36
40
  txPool;
37
41
  attestationPool;
38
- /** How many slots to keep attestations for. */ keepAttestationsInPoolFor;
39
- /** How many slots to keep proven txs for. */ keepProvenTxsFor;
42
+ config;
40
43
  blockStream;
44
+ txProvider;
45
+ validatorAddresses;
41
46
  /**
42
47
  * In-memory P2P client constructor.
43
48
  * @param store - The client's instance of the KV store.
44
49
  * @param l2BlockSource - P2P client's source for fetching existing blocks.
45
50
  * @param txPool - The client's instance of a transaction pool. Defaults to in-memory implementation.
46
51
  * @param p2pService - The concrete instance of p2p networking to use.
47
- * @param keepProvenTxsFor - How many blocks have to pass after a block is proven before its txs are deleted (zero to delete immediately once proven).
48
52
  * @param log - A logger.
49
- */ constructor(_clientType, store, l2BlockSource, mempools, p2pService, config = {}, telemetry = getTelemetryClient(), log = createLogger('p2p')){
50
- super(telemetry, 'P2PClient'), this.l2BlockSource = l2BlockSource, this.p2pService = p2pService, this.log = log, this.currentState = 0, this.syncPromise = Promise.resolve(), this.syncResolve = undefined, this.latestBlockNumberAtStart = -1, this.provenBlockNumberAtStart = -1;
51
- const { keepProvenTxsInPoolFor, blockCheckIntervalMS, blockRequestBatchSize, keepAttestationsInPoolFor } = {
53
+ */ constructor(_clientType, store, l2BlockSource, mempools, p2pService, txCollection, config = {}, _dateProvider = new DateProvider(), telemetry = getTelemetryClient(), log = createLogger('p2p')){
54
+ super(telemetry, 'P2PClient'), this.store = store, this.l2BlockSource = l2BlockSource, this.p2pService = p2pService, this.txCollection = txCollection, this._dateProvider = _dateProvider, this.telemetry = telemetry, this.log = log, this.currentState = P2PClientState.IDLE, this.syncPromise = Promise.resolve(), this.syncResolve = undefined, this.latestBlockNumberAtStart = -1, this.provenBlockNumberAtStart = -1, this.finalizedBlockNumberAtStart = -1, this.validatorAddresses = [];
55
+ this.config = {
52
56
  ...getP2PDefaultConfig(),
53
57
  ...config
54
58
  };
55
- this.keepProvenTxsFor = keepProvenTxsInPoolFor;
56
- this.keepAttestationsInPoolFor = keepAttestationsInPoolFor;
57
- const tracer = telemetry.getTracer('P2PL2BlockStream');
58
- const logger = createLogger('p2p:l2-block-stream');
59
- this.blockStream = new TraceableL2BlockStream(l2BlockSource, this, this, tracer, 'P2PL2BlockStream', logger, {
60
- batchSize: blockRequestBatchSize,
61
- pollIntervalMS: blockCheckIntervalMS
59
+ this.txPool = mempools.txPool;
60
+ this.attestationPool = mempools.attestationPool;
61
+ this.txProvider = new TxProvider(this.txCollection, this.txPool, this, this.log.createChild('tx-provider'), this.telemetry);
62
+ // Default to collecting all txs when we see a valid proposal
63
+ // This can be overridden by the validator client to attest, and it will call getTxsForBlockProposal on its own
64
+ // TODO(palla/txs): We should not trigger a request for txs on a proposal before fully validating it. We need to bring
65
+ // validator-client code into here so we can validate a proposal is reasonable.
66
+ this.registerBlockProposalHandler(async (block, sender)=>{
67
+ this.log.debug(`Received block proposal from ${sender.toString()}`);
68
+ // TODO(palla/txs): Need to subtract validatorReexecuteDeadlineMs from this deadline (see ValidatorClient.getReexecutionDeadline)
69
+ const constants = this.txCollection.getConstants();
70
+ const nextSlotTimestampSeconds = Number(getTimestampForSlot(block.slotNumber.toBigInt() + 1n, constants));
71
+ const deadline = new Date(nextSlotTimestampSeconds * 1000);
72
+ const parentBlock = await this.l2BlockSource.getBlockHeaderByArchive(block.payload.header.lastArchiveRoot);
73
+ if (!parentBlock) {
74
+ this.log.debug(`Cannot collect txs for proposal as parent block not found`);
75
+ return;
76
+ }
77
+ const blockNumber = parentBlock.getBlockNumber() + 1;
78
+ await this.txProvider.getTxsForBlockProposal(block, blockNumber, {
79
+ pinnedPeer: sender,
80
+ deadline
81
+ });
82
+ return undefined;
62
83
  });
84
+ // REFACTOR: Try replacing these with an L2TipsStore
63
85
  this.synchedBlockHashes = store.openMap('p2p_pool_block_hashes');
64
86
  this.synchedLatestBlockNumber = store.openSingleton('p2p_pool_last_l2_block');
65
87
  this.synchedProvenBlockNumber = store.openSingleton('p2p_pool_last_proven_l2_block');
66
- this.txPool = mempools.txPool;
67
- this.attestationPool = mempools.attestationPool;
88
+ this.synchedFinalizedBlockNumber = store.openSingleton('p2p_pool_last_finalized_l2_block');
89
+ this.synchedLatestSlot = store.openSingleton('p2p_pool_last_l2_slot');
90
+ }
91
+ registerThisValidatorAddresses(addresses) {
92
+ this.validatorAddresses = [
93
+ ...addresses
94
+ ];
95
+ this.p2pService.registerThisValidatorAddresses(this.validatorAddresses);
96
+ }
97
+ clear() {
98
+ return this.store.clear();
68
99
  }
69
100
  isP2PClient() {
70
101
  return true;
71
102
  }
103
+ getTxProvider() {
104
+ return this.txProvider;
105
+ }
72
106
  getPeers(includePending) {
73
107
  return Promise.resolve(this.p2pService.getPeers(includePending));
74
108
  }
75
109
  getL2BlockHash(number) {
76
110
  return this.synchedBlockHashes.getAsync(number);
77
111
  }
112
+ updateP2PConfig(config) {
113
+ this.txPool.updateConfig(config);
114
+ this.p2pService.updateConfig(config);
115
+ return Promise.resolve();
116
+ }
78
117
  async getL2Tips() {
79
118
  const latestBlockNumber = await this.getSyncedLatestBlockNum();
80
119
  let latestBlockHash;
81
120
  const provenBlockNumber = await this.getSyncedProvenBlockNum();
82
121
  let provenBlockHash;
122
+ const finalizedBlockNumber = await this.getSyncedFinalizedBlockNum();
123
+ let finalizedBlockHash;
83
124
  if (latestBlockNumber > 0) {
84
125
  latestBlockHash = await this.synchedBlockHashes.getAsync(latestBlockNumber);
85
126
  if (typeof latestBlockHash === 'undefined') {
86
- this.log.warn(`Block hash for latest block ${latestBlockNumber} not found`);
87
- throw new Error();
127
+ throw new Error(`Block hash for latest block ${latestBlockNumber} not found in p2p client`);
88
128
  }
89
129
  }
90
130
  if (provenBlockNumber > 0) {
91
131
  provenBlockHash = await this.synchedBlockHashes.getAsync(provenBlockNumber);
92
132
  if (typeof provenBlockHash === 'undefined') {
93
- this.log.warn(`Block hash for proven block ${provenBlockNumber} not found`);
94
- throw new Error();
133
+ throw new Error(`Block hash for proven block ${provenBlockNumber} not found in p2p client`);
95
134
  }
96
135
  }
97
- return Promise.resolve({
136
+ if (finalizedBlockNumber > 0) {
137
+ finalizedBlockHash = await this.synchedBlockHashes.getAsync(finalizedBlockNumber);
138
+ if (typeof finalizedBlockHash === 'undefined') {
139
+ throw new Error(`Block hash for finalized block ${finalizedBlockNumber} not found in p2p client`);
140
+ }
141
+ }
142
+ return {
98
143
  latest: {
99
144
  hash: latestBlockHash,
100
145
  number: latestBlockNumber
@@ -104,10 +149,10 @@ import { ReqRespSubProtocol } from '../services/reqresp/interface.js';
104
149
  number: provenBlockNumber
105
150
  },
106
151
  finalized: {
107
- hash: provenBlockHash,
108
- number: provenBlockNumber
152
+ hash: finalizedBlockHash,
153
+ number: finalizedBlockNumber
109
154
  }
110
- });
155
+ };
111
156
  }
112
157
  async handleBlockStreamEvent(event) {
113
158
  this.log.debug(`Handling block stream event ${event.type}`);
@@ -116,16 +161,27 @@ import { ReqRespSubProtocol } from '../services/reqresp/interface.js';
116
161
  await this.handleLatestL2Blocks(event.blocks);
117
162
  break;
118
163
  case 'chain-finalized':
119
- break;
164
+ {
165
+ // TODO (alexg): I think we can prune the block hashes map here
166
+ await this.setBlockHash(event.block);
167
+ const from = await this.getSyncedFinalizedBlockNum() + 1;
168
+ const limit = event.block.number - from + 1;
169
+ if (limit > 0) {
170
+ await this.handleFinalizedL2Blocks(await this.l2BlockSource.getBlocks(from, limit));
171
+ }
172
+ break;
173
+ }
120
174
  case 'chain-proven':
121
175
  {
122
- const from = await this.getSyncedProvenBlockNum() + 1;
123
- const limit = event.blockNumber - from + 1;
124
- await this.handleProvenL2Blocks(await this.l2BlockSource.getBlocks(from, limit));
176
+ await this.setBlockHash(event.block);
177
+ this.txCollection.stopCollectingForBlocksUpTo(event.block.number);
178
+ await this.synchedProvenBlockNumber.set(event.block.number);
125
179
  break;
126
180
  }
127
181
  case 'chain-pruned':
128
- await this.handlePruneL2Blocks(event.blockNumber);
182
+ await this.setBlockHash(event.block);
183
+ this.txCollection.stopCollectingForBlocksAfter(event.block.number);
184
+ await this.handlePruneL2Blocks(event.block.number);
129
185
  break;
130
186
  default:
131
187
  {
@@ -134,6 +190,11 @@ import { ReqRespSubProtocol } from '../services/reqresp/interface.js';
134
190
  }
135
191
  }
136
192
  }
193
+ async setBlockHash(block) {
194
+ if (block.hash !== undefined) {
195
+ await this.synchedBlockHashes.set(block.number, block.hash.toString());
196
+ }
197
+ }
137
198
  #assertIsReady() {
138
199
  // this.log.info('Checking if p2p client is ready, current state: ', this.currentState);
139
200
  if (!this.isReady()) {
@@ -144,54 +205,102 @@ import { ReqRespSubProtocol } from '../services/reqresp/interface.js';
144
205
  * Starts the P2P client.
145
206
  * @returns An empty promise signalling the synching process.
146
207
  */ async start() {
147
- if (this.currentState === 3) {
208
+ if (this.currentState === P2PClientState.STOPPED) {
148
209
  throw new Error('P2P client already stopped');
149
210
  }
150
- if (this.currentState !== 0) {
211
+ if (this.currentState !== P2PClientState.IDLE) {
151
212
  return this.syncPromise;
152
213
  }
153
214
  // get the current latest block numbers
154
- this.latestBlockNumberAtStart = await this.l2BlockSource.getBlockNumber();
155
- this.provenBlockNumberAtStart = await this.l2BlockSource.getProvenBlockNumber();
215
+ const latestBlockNumbers = await this.l2BlockSource.getL2Tips();
216
+ this.latestBlockNumberAtStart = latestBlockNumbers.latest.number;
217
+ this.provenBlockNumberAtStart = latestBlockNumbers.proven.number;
218
+ this.finalizedBlockNumberAtStart = latestBlockNumbers.finalized.number;
156
219
  const syncedLatestBlock = await this.getSyncedLatestBlockNum() + 1;
157
220
  const syncedProvenBlock = await this.getSyncedProvenBlockNum() + 1;
158
- // if there are blocks to be retrieved, go to a synching state
159
- if (syncedLatestBlock <= this.latestBlockNumberAtStart || syncedProvenBlock <= this.provenBlockNumberAtStart) {
160
- this.setCurrentState(1);
221
+ const syncedFinalizedBlock = await this.getSyncedFinalizedBlockNum() + 1;
222
+ if (await this.txPool.isEmpty() && (this.attestationPool === undefined || await this.attestationPool?.isEmpty())) {
223
+ // if mempools are empty, we don't care about syncing prior blocks
224
+ this.initBlockStream(this.latestBlockNumberAtStart);
225
+ this.setCurrentState(P2PClientState.RUNNING);
226
+ this.syncPromise = Promise.resolve();
227
+ await this.p2pService.start();
228
+ this.log.info(`Starting p2p client from block ${this.latestBlockNumberAtStart} with empty mempools`);
229
+ } else if (syncedLatestBlock <= this.latestBlockNumberAtStart || syncedProvenBlock <= this.provenBlockNumberAtStart || syncedFinalizedBlock <= this.finalizedBlockNumberAtStart) {
230
+ // if there are blocks to be retrieved, go to a synching state
231
+ // this gets resolved on `startServiceIfSynched`
232
+ this.initBlockStream();
233
+ this.setCurrentState(P2PClientState.SYNCHING);
161
234
  this.syncPromise = new Promise((resolve)=>{
162
235
  this.syncResolve = resolve;
163
236
  });
164
- this.log.verbose(`Starting sync from ${syncedLatestBlock} (last proven ${syncedProvenBlock})`);
237
+ this.log.info(`Initiating p2p sync from ${syncedLatestBlock}`, {
238
+ syncedLatestBlock,
239
+ syncedProvenBlock,
240
+ syncedFinalizedBlock
241
+ });
165
242
  } else {
166
243
  // if no blocks to be retrieved, go straight to running
167
- this.setCurrentState(2);
244
+ this.initBlockStream();
245
+ this.setCurrentState(P2PClientState.RUNNING);
168
246
  this.syncPromise = Promise.resolve();
169
247
  await this.p2pService.start();
170
- this.log.debug(`Block ${syncedLatestBlock} (proven ${syncedProvenBlock}) already beyond current block`);
248
+ this.log.info(`Starting P2P client synced to ${syncedLatestBlock}`, {
249
+ syncedLatestBlock,
250
+ syncedProvenBlock,
251
+ syncedFinalizedBlock
252
+ });
171
253
  }
172
254
  this.blockStream.start();
173
- this.log.verbose(`Started block downloader from block ${syncedLatestBlock}`);
255
+ await this.txCollection.start();
174
256
  return this.syncPromise;
175
257
  }
258
+ addReqRespSubProtocol(subProtocol, handler, validator) {
259
+ return this.p2pService.addReqRespSubProtocol(subProtocol, handler, validator);
260
+ }
261
+ initBlockStream(startingBlock) {
262
+ if (!this.blockStream) {
263
+ const { blockRequestBatchSize: batchSize, blockCheckIntervalMS: pollIntervalMS } = this.config;
264
+ this.blockStream = new TraceableL2BlockStream(this.l2BlockSource, this, this, this.telemetry.getTracer('P2PL2BlockStream'), 'P2PL2BlockStream', createLogger(`${this.log.module}:l2-block-stream`), {
265
+ batchSize,
266
+ pollIntervalMS,
267
+ startingBlock
268
+ });
269
+ }
270
+ }
176
271
  /**
177
272
  * Allows consumers to stop the instance of the P2P client.
178
273
  * 'ready' will now return 'false' and the running promise that keeps the client synced is interrupted.
179
274
  */ async stop() {
180
275
  this.log.debug('Stopping p2p client...');
276
+ await tryStop(this.txCollection);
277
+ this.log.debug('Stopped tx collection service');
181
278
  await this.p2pService.stop();
182
279
  this.log.debug('Stopped p2p service');
183
- await this.blockStream.stop();
280
+ await this.blockStream?.stop();
184
281
  this.log.debug('Stopped block downloader');
185
282
  await this.runningPromise;
186
- this.setCurrentState(3);
187
- this.log.info('P2P client stopped.');
283
+ this.setCurrentState(P2PClientState.STOPPED);
284
+ this.log.info('P2P client stopped');
285
+ }
286
+ /** Triggers a sync to the archiver. Used for testing. */ async sync() {
287
+ this.initBlockStream();
288
+ await this.blockStream.sync();
188
289
  }
189
290
  broadcastProposal(proposal) {
190
291
  this.log.verbose(`Broadcasting proposal for slot ${proposal.slotNumber.toNumber()} to peers`);
191
292
  return this.p2pService.propagate(proposal);
192
293
  }
193
294
  async getAttestationsForSlot(slot, proposalId) {
194
- return await this.attestationPool?.getAttestationsForSlot(slot, proposalId) ?? [];
295
+ return await (proposalId ? this.attestationPool?.getAttestationsForSlotAndProposal(slot, proposalId) : this.attestationPool?.getAttestationsForSlot(slot)) ?? [];
296
+ }
297
+ addAttestations(attestations) {
298
+ return this.attestationPool?.addAttestations(attestations) ?? Promise.resolve();
299
+ }
300
+ deleteAttestation(attestation) {
301
+ return this.attestationPool?.deleteAttestations([
302
+ attestation
303
+ ]) ?? Promise.resolve();
195
304
  }
196
305
  // REVIEW: https://github.com/AztecProtocol/aztec-packages/issues/7963
197
306
  // ^ This pattern is not my favorite (md)
@@ -199,52 +308,27 @@ import { ReqRespSubProtocol } from '../services/reqresp/interface.js';
199
308
  this.p2pService.registerBlockReceivedCallback(handler);
200
309
  }
201
310
  /**
202
- * Requests the transactions with the given hashes from the network.
203
- *
204
- * If a transaction can be retrieved, it will be returned, if not an undefined
205
- * will be returned. In place.
206
- *
207
- * @param txHashes - The hashes of the transactions to request.
208
- * @returns A promise that resolves to an array of transactions or undefined.
209
- */ async requestTxs(txHashes) {
210
- const res = await this.p2pService.sendBatchRequest(ReqRespSubProtocol.TX, txHashes);
211
- return Promise.resolve(res ?? []);
212
- }
213
- /**
214
- * Uses the Request Response protocol to request a transaction from the network.
215
- *
216
- * If the underlying request response protocol fails, then we return undefined.
217
- * If it succeeds then we add the transaction to our transaction pool and return.
218
- *
219
- * @param txHash - The hash of the transaction to request.
220
- * @returns A promise that resolves to a transaction or undefined.
221
- */ async requestTxByHash(txHash) {
222
- const tx = await this.p2pService.sendRequest(ReqRespSubProtocol.TX, txHash);
223
- if (tx) {
224
- this.log.debug(`Received tx ${txHash.toString()} from peer`);
225
- await this.txPool.addTxs([
226
- tx
227
- ]);
228
- } else {
229
- this.log.debug(`Failed to receive tx ${txHash.toString()} from peer`);
230
- }
231
- return tx;
232
- }
233
- /**
234
311
  * Uses the batched Request Response protocol to request a set of transactions from the network.
235
- */ async requestTxsByHash(txHashes) {
236
- const txs = await this.p2pService.sendBatchRequest(ReqRespSubProtocol.TX, txHashes) ?? [];
237
- await this.txPool.addTxs(txs);
312
+ */ async requestTxsByHash(txHashes, pinnedPeerId) {
313
+ const timeoutMs = 8000; // Longer timeout for now
314
+ const maxRetryAttempts = 10; // Keep retrying within the timeout
315
+ const requests = chunkTxHashesRequest(txHashes);
316
+ const maxPeers = Math.min(Math.ceil(requests.length / 3), 10);
317
+ const txBatches = await this.p2pService.sendBatchRequest(ReqRespSubProtocol.TX, requests, pinnedPeerId, timeoutMs, maxPeers, maxRetryAttempts);
318
+ const txs = txBatches.flat();
319
+ if (txs.length > 0) {
320
+ await this.txPool.addTxs(txs);
321
+ }
238
322
  const txHashesStr = txHashes.map((tx)=>tx.toString()).join(', ');
239
- this.log.debug(`Received batched txs ${txHashesStr} (${txs.length} / ${txHashes.length}}) from peers`);
323
+ this.log.debug(`Requested txs ${txHashesStr} (${txs.length} / ${txHashes.length}) from peers`);
324
+ // We return all transactions, even the not found ones to the caller, such they can handle missing items themselves.
240
325
  return txs;
241
326
  }
242
- getPendingTxs() {
243
- return Promise.resolve(this.getTxs('pending'));
327
+ getPendingTxs(limit, after) {
328
+ return this.getTxs('pending', limit, after);
244
329
  }
245
- async getPendingTxCount() {
246
- const pendingTxs = await this.txPool.getPendingTxHashes();
247
- return pendingTxs.length;
330
+ getPendingTxCount() {
331
+ return this.txPool.getPendingTxCount();
248
332
  }
249
333
  async *iteratePendingTxs() {
250
334
  for (const txHash of (await this.txPool.getPendingTxHashes())){
@@ -256,22 +340,50 @@ import { ReqRespSubProtocol } from '../services/reqresp/interface.js';
256
340
  }
257
341
  /**
258
342
  * Returns all transactions in the transaction pool.
343
+ * @param filter - The type of txs to return
344
+ * @param limit - How many txs to return
345
+ * @param after - If paginating, the last known tx hash. Will return txs after this hash
259
346
  * @returns An array of Txs.
260
- */ async getTxs(filter) {
347
+ */ async getTxs(filter, limit, after) {
348
+ if (limit !== undefined && limit <= 0) {
349
+ throw new TypeError('limit must be greater than 0');
350
+ }
351
+ let txs = undefined;
352
+ let txHashes;
261
353
  if (filter === 'all') {
262
- return this.txPool.getAllTxs();
354
+ txs = await this.txPool.getAllTxs();
355
+ txHashes = await Promise.all(txs.map((tx)=>tx.getTxHash()));
263
356
  } else if (filter === 'mined') {
264
- const minedHashes = await this.txPool.getMinedTxHashes();
265
- const minedTx = await Promise.all(minedHashes.map(([txHash])=>this.txPool.getTxByHash(txHash)));
266
- return minedTx.filter((tx)=>!!tx);
357
+ const minedTxHashes = await this.txPool.getMinedTxHashes();
358
+ txHashes = minedTxHashes.map(([txHash])=>txHash);
267
359
  } else if (filter === 'pending') {
268
- const pendingHashses = await this.txPool.getPendingTxHashes();
269
- const pendingTxs = await Promise.all(pendingHashses.map((txHash)=>this.txPool.getTxByHash(txHash)));
270
- return pendingTxs.filter((tx)=>!!tx);
360
+ txHashes = await this.txPool.getPendingTxHashes();
271
361
  } else {
272
362
  const _ = filter;
273
363
  throw new Error(`Unknown filter ${filter}`);
274
364
  }
365
+ let startIndex = 0;
366
+ let endIndex = undefined;
367
+ if (after) {
368
+ startIndex = txHashes.findIndex((txHash)=>after.equals(txHash));
369
+ // if we can't find the last tx in our set then return an empty array as pagination is no longer valid.
370
+ if (startIndex === -1) {
371
+ return [];
372
+ }
373
+ // increment by one because we don't want to return the same tx again
374
+ startIndex++;
375
+ }
376
+ if (limit !== undefined) {
377
+ endIndex = startIndex + limit;
378
+ }
379
+ txHashes = txHashes.slice(startIndex, endIndex);
380
+ if (txs) {
381
+ txs = txs.slice(startIndex, endIndex);
382
+ } else {
383
+ const maybeTxs = await Promise.all(txHashes.map((txHash)=>this.txPool.getTxByHash(txHash)));
384
+ txs = maybeTxs.filter((tx)=>!!tx);
385
+ }
386
+ return txs;
275
387
  }
276
388
  /**
277
389
  * Returns a transaction in the transaction pool by its hash.
@@ -281,23 +393,21 @@ import { ReqRespSubProtocol } from '../services/reqresp/interface.js';
281
393
  return this.txPool.getTxByHash(txHash);
282
394
  }
283
395
  /**
284
- * Returns a transaction in the transaction pool by its hash.
285
- * If the transaction is not in the pool, it will be requested from the network.
286
- * @param txHash - Hash of the transaction to look for in the pool.
287
- * @returns A single tx or undefined.
288
- */ async getTxByHash(txHash) {
289
- const tx = await this.txPool.getTxByHash(txHash);
290
- if (tx) {
291
- return tx;
292
- }
293
- return this.requestTxByHash(txHash);
396
+ * Returns transactions in the transaction pool by hash.
397
+ * @param txHashes - Hashes of the transactions to look for.
398
+ * @returns The txs found, in the same order as the requested hashes. If a tx is not found, it will be undefined.
399
+ */ getTxsByHashFromPool(txHashes) {
400
+ return this.txPool.getTxsByHash(txHashes);
401
+ }
402
+ hasTxsInPool(txHashes) {
403
+ return this.txPool.hasTxs(txHashes);
294
404
  }
295
405
  /**
296
406
  * Returns transactions in the transaction pool by hash.
297
407
  * If a transaction is not in the pool, it will be requested from the network.
298
408
  * @param txHashes - Hashes of the transactions to look for.
299
- * @returns The txs found, not necessarily on the same order as the hashes.
300
- */ async getTxsByHash(txHashes) {
409
+ * @returns The txs found, or undefined if not found in the order requested.
410
+ */ async getTxsByHash(txHashes, pinnedPeerId) {
301
411
  const txs = await Promise.all(txHashes.map((txHash)=>this.txPool.getTxByHash(txHash)));
302
412
  const missingTxHashes = txs.map((tx, index)=>[
303
413
  tx,
@@ -306,8 +416,27 @@ import { ReqRespSubProtocol } from '../services/reqresp/interface.js';
306
416
  if (missingTxHashes.length === 0) {
307
417
  return txs;
308
418
  }
309
- const missingTxs = await this.requestTxsByHash(missingTxHashes);
310
- return txs.filter((tx)=>!!tx).concat(missingTxs);
419
+ const missingTxs = await this.requestTxsByHash(missingTxHashes, pinnedPeerId);
420
+ // TODO: optimize
421
+ // Merge the found txs in order
422
+ const mergingTxs = txHashes.map((txHash)=>{
423
+ // Is it in the txs list from the mempool?
424
+ for (const tx of txs){
425
+ if (tx !== undefined && tx.getTxHash().equals(txHash)) {
426
+ return tx;
427
+ }
428
+ }
429
+ // Is it in the fetched missing txs?
430
+ // Note: this is an O(n^2) operation, but we expect the number of missing txs to be small.
431
+ for (const tx of missingTxs){
432
+ if (tx.getTxHash().equals(txHash)) {
433
+ return tx;
434
+ }
435
+ }
436
+ // Otherwise return undefined
437
+ return undefined;
438
+ });
439
+ return mergingTxs;
311
440
  }
312
441
  /**
313
442
  * Returns an archived transaction in the transaction pool by its hash.
@@ -321,11 +450,20 @@ import { ReqRespSubProtocol } from '../services/reqresp/interface.js';
321
450
  * @param tx - The tx to verify.
322
451
  * @returns Empty promise.
323
452
  **/ async sendTx(tx) {
324
- this.#assertIsReady();
325
- await this.txPool.addTxs([
453
+ const addedCount = await this.addTxsToPool([
326
454
  tx
327
455
  ]);
328
- this.p2pService.propagate(tx);
456
+ const txAddedSuccessfully = addedCount === 1;
457
+ if (txAddedSuccessfully) {
458
+ await this.p2pService.propagate(tx);
459
+ }
460
+ }
461
+ /**
462
+ * Adds transactions to the pool. Does not send to peers or validate the txs.
463
+ * @param txs - The transactions.
464
+ **/ async addTxsToPool(txs) {
465
+ this.#assertIsReady();
466
+ return await this.txPool.addTxs(txs);
329
467
  }
330
468
  /**
331
469
  * Returns whether the given tx hash is flagged as pending or mined.
@@ -353,7 +491,7 @@ import { ReqRespSubProtocol } from '../services/reqresp/interface.js';
353
491
  * Public function to check if the p2p client is fully synced and ready to receive txs.
354
492
  * @returns True if the P2P client is ready to receive txs.
355
493
  */ isReady() {
356
- return this.currentState === 2;
494
+ return this.currentState === P2PClientState.RUNNING;
357
495
  }
358
496
  /**
359
497
  * Public function to check the latest block number that the P2P client is synced to.
@@ -367,6 +505,12 @@ import { ReqRespSubProtocol } from '../services/reqresp/interface.js';
367
505
  */ async getSyncedProvenBlockNum() {
368
506
  return await this.synchedProvenBlockNumber.getAsync() ?? INITIAL_L2_BLOCK_NUM - 1;
369
507
  }
508
+ async getSyncedFinalizedBlockNum() {
509
+ return await this.synchedFinalizedBlockNumber.getAsync() ?? INITIAL_L2_BLOCK_NUM - 1;
510
+ }
511
+ /** Returns latest L2 slot for which we have seen an L2 block. */ async getSyncedLatestSlot() {
512
+ return await this.synchedLatestSlot.getAsync() ?? BigInt(0);
513
+ }
370
514
  /**
371
515
  * Method to check the status the p2p client.
372
516
  * @returns Information about p2p client status: state & syncedToBlockNum.
@@ -388,18 +532,7 @@ import { ReqRespSubProtocol } from '../services/reqresp/interface.js';
388
532
  */ async markTxsAsMinedFromBlocks(blocks) {
389
533
  for (const block of blocks){
390
534
  const txHashes = block.body.txEffects.map((txEffect)=>txEffect.txHash);
391
- await this.txPool.markAsMined(txHashes, block.number);
392
- }
393
- }
394
- /**
395
- * Deletes txs from these blocks.
396
- * @param blocks - A list of existing blocks with txs that the P2P client needs to ensure the tx pool is reconciled with.
397
- * @returns Empty promise.
398
- */ async deleteTxsFromBlocks(blocks) {
399
- this.log.debug(`Deleting txs from blocks ${blocks[0].number} to ${blocks[blocks.length - 1].number}`);
400
- for (const block of blocks){
401
- const txHashes = block.body.txEffects.map((txEffect)=>txEffect.txHash);
402
- await this.txPool.deleteTxs(txHashes);
535
+ await this.txPool.markAsMined(txHashes, block.getBlockHeader());
403
536
  }
404
537
  }
405
538
  /**
@@ -410,76 +543,123 @@ import { ReqRespSubProtocol } from '../services/reqresp/interface.js';
410
543
  if (!blocks.length) {
411
544
  return Promise.resolve();
412
545
  }
413
- await this.markTxsAsMinedFromBlocks(blocks);
414
- const lastBlockNum = blocks[blocks.length - 1].number;
415
- await Promise.all(blocks.map(async (block)=>this.synchedBlockHashes.set(block.number, (await block.hash()).toString())));
416
- await this.synchedLatestBlockNumber.set(lastBlockNum);
417
- this.log.verbose(`Synched to latest block ${lastBlockNum}`);
546
+ await this.markTxsAsMinedFromBlocks(blocks.map((b)=>b.block));
547
+ await this.startCollectingMissingTxs(blocks.map((b)=>b.block));
548
+ const lastBlock = blocks.at(-1).block;
549
+ await Promise.all(blocks.map(async (block)=>this.setBlockHash({
550
+ number: block.block.number,
551
+ hash: await block.block.hash().then((h)=>h.toString())
552
+ })));
553
+ await this.synchedLatestBlockNumber.set(lastBlock.number);
554
+ await this.synchedLatestSlot.set(lastBlock.header.getSlot());
555
+ this.log.verbose(`Synched to latest block ${lastBlock.number}`);
418
556
  await this.startServiceIfSynched();
419
557
  }
558
+ /** Request txs for unproven blocks so the prover node has more chances to get them. */ async startCollectingMissingTxs(blocks) {
559
+ try {
560
+ // TODO(#15435): If the archiver has lagged behind L1, the reported proven block number may
561
+ // be much lower than the actual one, and it does not update until the pending chain is
562
+ // fully synced. This could lead to a ton of tx collection requests for blocks that
563
+ // are already proven, but the archiver has not yet updated its state. Until this is properly
564
+ // fixed, it is mitigated by the expiration date of collection requests, which depends on
565
+ // the slot number of the block.
566
+ const provenBlockNumber = await this.l2BlockSource.getProvenBlockNumber();
567
+ const unprovenBlocks = blocks.filter((block)=>block.number > provenBlockNumber);
568
+ for (const block of unprovenBlocks){
569
+ const txHashes = block.body.txEffects.map((txEffect)=>txEffect.txHash);
570
+ const missingTxHashes = await this.txPool.hasTxs(txHashes).then((availability)=>txHashes.filter((_, index)=>!availability[index]));
571
+ if (missingTxHashes.length > 0) {
572
+ this.log.verbose(`Starting collection of ${missingTxHashes.length} missing txs for unproven mined block ${block.number}`, {
573
+ missingTxHashes,
574
+ blockNumber: block.number,
575
+ blockHash: await block.hash().then((h)=>h.toString())
576
+ });
577
+ this.txCollection.startCollecting(block, missingTxHashes);
578
+ }
579
+ }
580
+ } catch (err) {
581
+ this.log.error(`Error while starting collection of missing txs for unproven blocks`, err);
582
+ }
583
+ }
420
584
  /**
421
- * Handles new proven blocks by deleting the txs in them, or by deleting the txs in blocks `keepProvenTxsFor` ago.
422
- * @param blocks - A list of proven L2 blocks.
585
+ * Handles new finalized blocks by deleting the txs and attestations in them.
586
+ * @param blocks - A list of finalized L2 blocks.
423
587
  * @returns Empty promise.
424
- */ async handleProvenL2Blocks(blocks) {
588
+ */ async handleFinalizedL2Blocks(blocks) {
425
589
  if (!blocks.length) {
426
590
  return Promise.resolve();
427
591
  }
428
- const firstBlockNum = blocks[0].number;
592
+ this.log.debug(`Handling finalized blocks ${blocks.length} up to ${blocks.at(-1)?.number}`);
429
593
  const lastBlockNum = blocks[blocks.length - 1].number;
430
- const lastBlockSlot = blocks[blocks.length - 1].header.globalVariables.slotNumber.toBigInt();
431
- // If keepProvenTxsFor is 0, we delete all txs from all proven blocks.
432
- if (this.keepProvenTxsFor === 0) {
433
- await this.deleteTxsFromBlocks(blocks);
434
- } else if (lastBlockNum - this.keepProvenTxsFor >= INITIAL_L2_BLOCK_NUM) {
435
- const fromBlock = Math.max(INITIAL_L2_BLOCK_NUM, firstBlockNum - this.keepProvenTxsFor);
436
- const toBlock = lastBlockNum - this.keepProvenTxsFor;
437
- const limit = toBlock - fromBlock + 1;
438
- const blocksToDeleteTxsFrom = await this.l2BlockSource.getBlocks(fromBlock, limit, true);
439
- await this.deleteTxsFromBlocks(blocksToDeleteTxsFrom);
440
- }
441
- // We delete attestations older than the last block slot minus the number of slots we want to keep in the pool.
442
- const lastBlockSlotMinusKeepAttestationsInPoolFor = lastBlockSlot - BigInt(this.keepAttestationsInPoolFor);
443
- if (lastBlockSlotMinusKeepAttestationsInPoolFor >= BigInt(INITIAL_L2_BLOCK_NUM)) {
444
- await this.attestationPool?.deleteAttestationsOlderThan(lastBlockSlotMinusKeepAttestationsInPoolFor);
445
- }
446
- await this.synchedProvenBlockNumber.set(lastBlockNum);
447
- this.log.debug(`Synched to proven block ${lastBlockNum}`);
594
+ const lastBlockSlot = blocks[blocks.length - 1].header.getSlot();
595
+ const txHashes = blocks.flatMap((block)=>block.body.txEffects.map((txEffect)=>txEffect.txHash));
596
+ this.log.debug(`Deleting ${txHashes.length} txs from pool from finalized blocks up to ${lastBlockNum}`);
597
+ await this.txPool.deleteTxs(txHashes, {
598
+ permanently: true
599
+ });
600
+ await this.txPool.cleanupDeletedMinedTxs(lastBlockNum);
601
+ await this.attestationPool?.deleteAttestationsOlderThan(lastBlockSlot);
602
+ await this.synchedFinalizedBlockNumber.set(lastBlockNum);
603
+ this.log.debug(`Synched to finalized block ${lastBlockNum} at slot ${lastBlockSlot}`);
448
604
  await this.startServiceIfSynched();
449
605
  }
450
606
  /**
451
607
  * Updates the tx pool after a chain prune.
452
608
  * @param latestBlock - The block number the chain was pruned to.
453
609
  */ async handlePruneL2Blocks(latestBlock) {
454
- const txsToDelete = [];
610
+ const txsToDelete = new Map();
611
+ const minedTxs = await this.txPool.getMinedTxHashes();
612
+ // Find transactions that reference pruned blocks in their historical header
455
613
  for (const tx of (await this.txPool.getAllTxs())){
456
614
  // every tx that's been generated against a block that has now been pruned is no longer valid
457
- if (tx.data.constants.historicalHeader.globalVariables.blockNumber.toNumber() > latestBlock) {
458
- txsToDelete.push(await tx.getTxHash());
615
+ if (tx.data.constants.anchorBlockHeader.globalVariables.blockNumber > latestBlock) {
616
+ const txHash = tx.getTxHash();
617
+ txsToDelete.set(txHash.toString(), txHash);
459
618
  }
460
619
  }
461
- this.log.info(`Detected chain prune. Removing invalid txs count=${txsToDelete.length} newLatestBlock=${latestBlock} previousLatestBlock=${this.getSyncedLatestBlockNum()}`);
620
+ this.log.info(`Detected chain prune. Removing ${txsToDelete.size} txs built against pruned blocks.`, {
621
+ newLatestBlock: latestBlock,
622
+ previousLatestBlock: await this.getSyncedLatestBlockNum(),
623
+ txsToDelete: Array.from(txsToDelete.keys())
624
+ });
462
625
  // delete invalid txs (both pending and mined)
463
- await this.txPool.deleteTxs(txsToDelete);
626
+ await this.txPool.deleteTxs(Array.from(txsToDelete.values()));
464
627
  // everything left in the mined set was built against a block on the proven chain so its still valid
465
- // move back to pending the txs that were reorged out of the chain
628
+ // move back to pending the txs that were reorged out of the chain, unless txPoolDeleteTxsAfterReorg is set,
629
+ // in which case we clean them up to avoid potential reorg loops
466
630
  // NOTE: we can't move _all_ txs back to pending because the tx pool could keep hold of mined txs for longer
467
631
  // (see this.keepProvenTxsFor)
468
- const txsToMoveToPending = [];
469
- for (const [txHash, blockNumber] of (await this.txPool.getMinedTxHashes())){
470
- if (blockNumber > latestBlock) {
471
- txsToMoveToPending.push(txHash);
632
+ const minedTxsFromReorg = [];
633
+ for (const [txHash, blockNumber] of minedTxs){
634
+ // We keep the txsToDelete out of this list as they have already been deleted above
635
+ if (blockNumber > latestBlock && !txsToDelete.has(txHash.toString())) {
636
+ minedTxsFromReorg.push(txHash);
472
637
  }
473
638
  }
474
- this.log.info(`Moving ${txsToMoveToPending.length} mined txs back to pending`);
475
- await this.txPool.markMinedAsPending(txsToMoveToPending);
639
+ if (this.config.txPoolDeleteTxsAfterReorg) {
640
+ this.log.info(`Deleting ${minedTxsFromReorg.length} mined txs from reorg`);
641
+ await this.txPool.deleteTxs(minedTxsFromReorg);
642
+ } else {
643
+ this.log.info(`Moving ${minedTxsFromReorg.length} mined txs from reorg back to pending`);
644
+ await this.txPool.markMinedAsPending(minedTxsFromReorg);
645
+ }
476
646
  await this.synchedLatestBlockNumber.set(latestBlock);
477
647
  // no need to update block hashes, as they will be updated as new blocks are added
478
648
  }
479
649
  async startServiceIfSynched() {
480
- if (this.currentState === 1 && await this.getSyncedLatestBlockNum() >= this.latestBlockNumberAtStart && await this.getSyncedProvenBlockNum() >= this.provenBlockNumberAtStart) {
481
- this.log.debug(`Synched to blocks at start`);
482
- this.setCurrentState(2);
650
+ if (this.currentState !== P2PClientState.SYNCHING) {
651
+ return;
652
+ }
653
+ const syncedFinalizedBlock = await this.getSyncedFinalizedBlockNum();
654
+ const syncedProvenBlock = await this.getSyncedProvenBlockNum();
655
+ const syncedLatestBlock = await this.getSyncedLatestBlockNum();
656
+ if (syncedLatestBlock >= this.latestBlockNumberAtStart && syncedProvenBlock >= this.provenBlockNumberAtStart && syncedFinalizedBlock >= this.finalizedBlockNumberAtStart) {
657
+ this.log.info(`Completed P2P client sync to block ${syncedLatestBlock}. Starting service.`, {
658
+ syncedLatestBlock,
659
+ syncedProvenBlock,
660
+ syncedFinalizedBlock
661
+ });
662
+ this.setCurrentState(P2PClientState.RUNNING);
483
663
  if (this.syncResolve !== undefined) {
484
664
  this.syncResolve();
485
665
  await this.p2pService.start();
@@ -494,10 +674,21 @@ import { ReqRespSubProtocol } from '../services/reqresp/interface.js';
494
674
  this.currentState = newState;
495
675
  this.log.debug(`Moved from state ${P2PClientState[oldState]} to ${P2PClientState[this.currentState]}`);
496
676
  }
677
+ validate(txs) {
678
+ return this.p2pService.validate(txs);
679
+ }
680
+ /**
681
+ * Marks transactions as non-evictable in the pool.
682
+ * @param txHashes - Hashes of the transactions to mark as non-evictable.
683
+ */ markTxsAsNonEvictable(txHashes) {
684
+ return this.txPool.markTxsAsNonEvictable(txHashes);
685
+ }
686
+ handleAuthRequestFromPeer(authRequest, peerId) {
687
+ return this.p2pService.handleAuthRequestFromPeer(authRequest, peerId);
688
+ }
497
689
  }
498
690
  _ts_decorate([
499
691
  trackSpan('p2pClient.broadcastProposal', async (proposal)=>({
500
- [Attributes.BLOCK_NUMBER]: proposal.blockNumber.toNumber(),
501
692
  [Attributes.SLOT_NUMBER]: proposal.slotNumber.toNumber(),
502
693
  [Attributes.BLOCK_ARCHIVE]: proposal.archive.toString(),
503
694
  [Attributes.P2P_ID]: (await proposal.p2pMessageIdentifier()).toString()