@aztec/p2p 0.0.1-commit.f504929 → 0.0.1-commit.f5a9928

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 (483) hide show
  1. package/README.md +130 -3
  2. package/dest/bootstrap/bootstrap.d.ts +1 -1
  3. package/dest/bootstrap/bootstrap.d.ts.map +1 -1
  4. package/dest/bootstrap/bootstrap.js +22 -6
  5. package/dest/client/factory.d.ts +5 -4
  6. package/dest/client/factory.d.ts.map +1 -1
  7. package/dest/client/factory.js +39 -16
  8. package/dest/client/interface.d.ts +52 -12
  9. package/dest/client/interface.d.ts.map +1 -1
  10. package/dest/client/p2p_client.d.ts +36 -20
  11. package/dest/client/p2p_client.d.ts.map +1 -1
  12. package/dest/client/p2p_client.js +142 -81
  13. package/dest/config.d.ts +163 -98
  14. package/dest/config.d.ts.map +1 -1
  15. package/dest/config.js +130 -20
  16. package/dest/errors/p2p-service.error.d.ts +9 -0
  17. package/dest/errors/p2p-service.error.d.ts.map +1 -0
  18. package/dest/errors/p2p-service.error.js +10 -0
  19. package/dest/errors/reqresp.error.d.ts +9 -16
  20. package/dest/errors/reqresp.error.d.ts.map +1 -1
  21. package/dest/errors/reqresp.error.js +10 -17
  22. package/dest/index.d.ts +1 -2
  23. package/dest/index.d.ts.map +1 -1
  24. package/dest/index.js +0 -1
  25. package/dest/mem_pools/attestation_pool/attestation_pool.d.ts +101 -59
  26. package/dest/mem_pools/attestation_pool/attestation_pool.d.ts.map +1 -1
  27. package/dest/mem_pools/attestation_pool/attestation_pool.js +272 -199
  28. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.d.ts +1 -1
  29. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.d.ts.map +1 -1
  30. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.js +224 -65
  31. package/dest/mem_pools/attestation_pool/mocks.d.ts +1 -1
  32. package/dest/mem_pools/attestation_pool/mocks.d.ts.map +1 -1
  33. package/dest/mem_pools/attestation_pool/mocks.js +6 -4
  34. package/dest/mem_pools/index.d.ts +1 -2
  35. package/dest/mem_pools/index.d.ts.map +1 -1
  36. package/dest/mem_pools/instrumentation.d.ts +9 -4
  37. package/dest/mem_pools/instrumentation.d.ts.map +1 -1
  38. package/dest/mem_pools/instrumentation.js +28 -9
  39. package/dest/mem_pools/tx_pool_v2/archive/tx_archive.d.ts +10 -5
  40. package/dest/mem_pools/tx_pool_v2/archive/tx_archive.d.ts.map +1 -1
  41. package/dest/mem_pools/tx_pool_v2/archive/tx_archive.js +29 -20
  42. package/dest/mem_pools/tx_pool_v2/deleted_pool.d.ts +3 -3
  43. package/dest/mem_pools/tx_pool_v2/deleted_pool.d.ts.map +1 -1
  44. package/dest/mem_pools/tx_pool_v2/deleted_pool.js +6 -6
  45. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.d.ts +1 -1
  46. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.d.ts.map +1 -1
  47. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.js +5 -4
  48. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.d.ts +1 -1
  49. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.d.ts.map +1 -1
  50. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.js +3 -1
  51. package/dest/mem_pools/tx_pool_v2/eviction/index.d.ts +2 -1
  52. package/dest/mem_pools/tx_pool_v2/eviction/index.d.ts.map +1 -1
  53. package/dest/mem_pools/tx_pool_v2/eviction/index.js +1 -0
  54. package/dest/mem_pools/tx_pool_v2/eviction/insufficient_fee_per_gas_eviction_rule.d.ts +16 -0
  55. package/dest/mem_pools/tx_pool_v2/eviction/insufficient_fee_per_gas_eviction_rule.d.ts.map +1 -0
  56. package/dest/mem_pools/tx_pool_v2/eviction/insufficient_fee_per_gas_eviction_rule.js +64 -0
  57. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.d.ts +7 -1
  58. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.d.ts.map +1 -1
  59. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.d.ts +1 -1
  60. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.d.ts.map +1 -1
  61. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.js +3 -4
  62. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.d.ts +1 -1
  63. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.d.ts.map +1 -1
  64. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.js +6 -7
  65. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.d.ts +1 -1
  66. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.d.ts.map +1 -1
  67. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.js +6 -5
  68. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.d.ts +1 -1
  69. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.d.ts.map +1 -1
  70. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.js +8 -6
  71. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.d.ts +2 -2
  72. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.d.ts.map +1 -1
  73. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.js +2 -2
  74. package/dest/mem_pools/tx_pool_v2/instrumentation.d.ts +11 -1
  75. package/dest/mem_pools/tx_pool_v2/instrumentation.d.ts.map +1 -1
  76. package/dest/mem_pools/tx_pool_v2/instrumentation.js +24 -0
  77. package/dest/mem_pools/tx_pool_v2/interfaces.d.ts +41 -9
  78. package/dest/mem_pools/tx_pool_v2/interfaces.d.ts.map +1 -1
  79. package/dest/mem_pools/tx_pool_v2/interfaces.js +3 -1
  80. package/dest/mem_pools/tx_pool_v2/tx_metadata.d.ts +29 -11
  81. package/dest/mem_pools/tx_pool_v2/tx_metadata.d.ts.map +1 -1
  82. package/dest/mem_pools/tx_pool_v2/tx_metadata.js +46 -16
  83. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.d.ts +15 -1
  84. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.d.ts.map +1 -1
  85. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.js +55 -41
  86. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.d.ts +19 -4
  87. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.d.ts.map +1 -1
  88. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.js +86 -32
  89. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.d.ts +50 -6
  90. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.d.ts.map +1 -1
  91. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.js +262 -131
  92. package/dest/msg_validators/attestation_validator/attestation_validator.d.ts +10 -3
  93. package/dest/msg_validators/attestation_validator/attestation_validator.d.ts.map +1 -1
  94. package/dest/msg_validators/attestation_validator/attestation_validator.js +38 -15
  95. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.d.ts +7 -3
  96. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.d.ts.map +1 -1
  97. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.js +4 -5
  98. package/dest/msg_validators/proposal_validator/block_proposal_validator.d.ts +11 -5
  99. package/dest/msg_validators/proposal_validator/block_proposal_validator.d.ts.map +1 -1
  100. package/dest/msg_validators/proposal_validator/block_proposal_validator.js +11 -3
  101. package/dest/msg_validators/proposal_validator/checkpoint_proposal_validator.d.ts +11 -5
  102. package/dest/msg_validators/proposal_validator/checkpoint_proposal_validator.d.ts.map +1 -1
  103. package/dest/msg_validators/proposal_validator/checkpoint_proposal_validator.js +23 -3
  104. package/dest/msg_validators/proposal_validator/proposal_validator.d.ts +35 -10
  105. package/dest/msg_validators/proposal_validator/proposal_validator.d.ts.map +1 -1
  106. package/dest/msg_validators/proposal_validator/proposal_validator.js +128 -56
  107. package/dest/msg_validators/tx_validator/aggregate_tx_validator.d.ts +1 -1
  108. package/dest/msg_validators/tx_validator/aggregate_tx_validator.d.ts.map +1 -1
  109. package/dest/msg_validators/tx_validator/aggregate_tx_validator.js +8 -15
  110. package/dest/msg_validators/tx_validator/allowed_public_setup.d.ts +1 -1
  111. package/dest/msg_validators/tx_validator/allowed_public_setup.d.ts.map +1 -1
  112. package/dest/msg_validators/tx_validator/allowed_public_setup.js +21 -32
  113. package/dest/msg_validators/tx_validator/allowed_setup_helpers.d.ts +17 -0
  114. package/dest/msg_validators/tx_validator/allowed_setup_helpers.d.ts.map +1 -0
  115. package/dest/msg_validators/tx_validator/allowed_setup_helpers.js +24 -0
  116. package/dest/msg_validators/tx_validator/archive_cache.js +1 -1
  117. package/dest/msg_validators/tx_validator/cached_tx_validator.d.ts +15 -0
  118. package/dest/msg_validators/tx_validator/cached_tx_validator.d.ts.map +1 -0
  119. package/dest/msg_validators/tx_validator/cached_tx_validator.js +19 -0
  120. package/dest/msg_validators/tx_validator/contract_instance_validator.d.ts +9 -0
  121. package/dest/msg_validators/tx_validator/contract_instance_validator.d.ts.map +1 -0
  122. package/dest/msg_validators/tx_validator/contract_instance_validator.js +48 -0
  123. package/dest/msg_validators/tx_validator/data_validator.d.ts +2 -1
  124. package/dest/msg_validators/tx_validator/data_validator.d.ts.map +1 -1
  125. package/dest/msg_validators/tx_validator/data_validator.js +36 -2
  126. package/dest/msg_validators/tx_validator/factory.d.ts +25 -7
  127. package/dest/msg_validators/tx_validator/factory.d.ts.map +1 -1
  128. package/dest/msg_validators/tx_validator/factory.js +55 -16
  129. package/dest/msg_validators/tx_validator/fee_payer_balance.d.ts +1 -1
  130. package/dest/msg_validators/tx_validator/fee_payer_balance.d.ts.map +1 -1
  131. package/dest/msg_validators/tx_validator/fee_payer_balance.js +6 -2
  132. package/dest/msg_validators/tx_validator/gas_validator.d.ts +53 -7
  133. package/dest/msg_validators/tx_validator/gas_validator.d.ts.map +1 -1
  134. package/dest/msg_validators/tx_validator/gas_validator.js +88 -41
  135. package/dest/msg_validators/tx_validator/index.d.ts +4 -1
  136. package/dest/msg_validators/tx_validator/index.d.ts.map +1 -1
  137. package/dest/msg_validators/tx_validator/index.js +3 -0
  138. package/dest/msg_validators/tx_validator/metadata_validator.d.ts +1 -1
  139. package/dest/msg_validators/tx_validator/metadata_validator.d.ts.map +1 -1
  140. package/dest/msg_validators/tx_validator/metadata_validator.js +4 -4
  141. package/dest/msg_validators/tx_validator/phases_validator.d.ts +21 -1
  142. package/dest/msg_validators/tx_validator/phases_validator.d.ts.map +1 -1
  143. package/dest/msg_validators/tx_validator/phases_validator.js +49 -2
  144. package/dest/msg_validators/tx_validator/tx_proof_validator.d.ts +2 -1
  145. package/dest/msg_validators/tx_validator/tx_proof_validator.d.ts.map +1 -1
  146. package/dest/msg_validators/tx_validator/tx_proof_validator.js +2 -0
  147. package/dest/msg_validators/tx_validator/tx_validation_cache.d.ts +48 -0
  148. package/dest/msg_validators/tx_validator/tx_validation_cache.d.ts.map +1 -0
  149. package/dest/msg_validators/tx_validator/tx_validation_cache.js +68 -0
  150. package/dest/services/data_store.d.ts +1 -1
  151. package/dest/services/data_store.d.ts.map +1 -1
  152. package/dest/services/data_store.js +5 -5
  153. package/dest/services/discv5/discV5_service.d.ts +13 -2
  154. package/dest/services/discv5/discV5_service.d.ts.map +1 -1
  155. package/dest/services/discv5/discV5_service.js +119 -23
  156. package/dest/services/discv5/persisted_enr_store.d.ts +38 -0
  157. package/dest/services/discv5/persisted_enr_store.d.ts.map +1 -0
  158. package/dest/services/discv5/persisted_enr_store.js +145 -0
  159. package/dest/services/dummy_service.d.ts +18 -16
  160. package/dest/services/dummy_service.d.ts.map +1 -1
  161. package/dest/services/dummy_service.js +21 -16
  162. package/dest/services/encoding.d.ts +23 -6
  163. package/dest/services/encoding.d.ts.map +1 -1
  164. package/dest/services/encoding.js +32 -16
  165. package/dest/services/gossipsub/topic_score_params.d.ts +6 -12
  166. package/dest/services/gossipsub/topic_score_params.d.ts.map +1 -1
  167. package/dest/services/gossipsub/topic_score_params.js +4 -14
  168. package/dest/services/libp2p/instrumentation.d.ts +6 -1
  169. package/dest/services/libp2p/instrumentation.d.ts.map +1 -1
  170. package/dest/services/libp2p/instrumentation.js +21 -0
  171. package/dest/services/libp2p/libp2p_service.d.ts +51 -51
  172. package/dest/services/libp2p/libp2p_service.d.ts.map +1 -1
  173. package/dest/services/libp2p/libp2p_service.js +499 -333
  174. package/dest/services/peer-manager/peer_manager.d.ts +31 -3
  175. package/dest/services/peer-manager/peer_manager.d.ts.map +1 -1
  176. package/dest/services/peer-manager/peer_manager.js +125 -25
  177. package/dest/services/peer-manager/peer_scoring.d.ts +34 -2
  178. package/dest/services/peer-manager/peer_scoring.d.ts.map +1 -1
  179. package/dest/services/peer-manager/peer_scoring.js +102 -13
  180. package/dest/services/reqresp/batch-tx-requester/batch_tx_requester.d.ts +4 -8
  181. package/dest/services/reqresp/batch-tx-requester/batch_tx_requester.d.ts.map +1 -1
  182. package/dest/services/reqresp/batch-tx-requester/batch_tx_requester.js +81 -86
  183. package/dest/services/reqresp/batch-tx-requester/interface.d.ts +10 -6
  184. package/dest/services/reqresp/batch-tx-requester/interface.d.ts.map +1 -1
  185. package/dest/services/reqresp/batch-tx-requester/missing_txs.d.ts +5 -4
  186. package/dest/services/reqresp/batch-tx-requester/missing_txs.d.ts.map +1 -1
  187. package/dest/services/reqresp/batch-tx-requester/missing_txs.js +13 -7
  188. package/dest/services/reqresp/batch-tx-requester/peer_collection.d.ts +3 -1
  189. package/dest/services/reqresp/batch-tx-requester/peer_collection.d.ts.map +1 -1
  190. package/dest/services/reqresp/batch-tx-requester/peer_collection.js +3 -0
  191. package/dest/services/reqresp/batch-tx-requester/tx_validator.d.ts +5 -14
  192. package/dest/services/reqresp/batch-tx-requester/tx_validator.d.ts.map +1 -1
  193. package/dest/services/reqresp/batch-tx-requester/tx_validator.js +6 -20
  194. package/dest/services/reqresp/config.d.ts +15 -3
  195. package/dest/services/reqresp/config.d.ts.map +1 -1
  196. package/dest/services/reqresp/config.js +11 -0
  197. package/dest/services/reqresp/interface.d.ts +16 -18
  198. package/dest/services/reqresp/interface.d.ts.map +1 -1
  199. package/dest/services/reqresp/interface.js +10 -20
  200. package/dest/services/reqresp/metrics.d.ts +1 -1
  201. package/dest/services/reqresp/metrics.d.ts.map +1 -1
  202. package/dest/services/reqresp/metrics.js +0 -1
  203. package/dest/services/reqresp/protocols/block_txs/bitvector.d.ts +4 -3
  204. package/dest/services/reqresp/protocols/block_txs/bitvector.d.ts.map +1 -1
  205. package/dest/services/reqresp/protocols/block_txs/bitvector.js +3 -2
  206. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.d.ts +1 -1
  207. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.d.ts.map +1 -1
  208. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.js +31 -28
  209. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.d.ts +12 -7
  210. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.d.ts.map +1 -1
  211. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.js +42 -24
  212. package/dest/services/reqresp/protocols/index.d.ts +1 -2
  213. package/dest/services/reqresp/protocols/index.d.ts.map +1 -1
  214. package/dest/services/reqresp/protocols/index.js +0 -1
  215. package/dest/services/reqresp/protocols/tx.d.ts +1 -1
  216. package/dest/services/reqresp/protocols/tx.d.ts.map +1 -1
  217. package/dest/services/reqresp/protocols/tx.js +1 -3
  218. package/dest/services/reqresp/rate-limiter/rate_limiter.d.ts +5 -4
  219. package/dest/services/reqresp/rate-limiter/rate_limiter.d.ts.map +1 -1
  220. package/dest/services/reqresp/rate-limiter/rate_limiter.js +10 -8
  221. package/dest/services/reqresp/rate-limiter/rate_limits.d.ts +1 -1
  222. package/dest/services/reqresp/rate-limiter/rate_limits.d.ts.map +1 -1
  223. package/dest/services/reqresp/rate-limiter/rate_limits.js +3 -13
  224. package/dest/services/reqresp/reqresp.d.ts +7 -29
  225. package/dest/services/reqresp/reqresp.d.ts.map +1 -1
  226. package/dest/services/reqresp/reqresp.js +73 -215
  227. package/dest/services/service.d.ts +43 -18
  228. package/dest/services/service.d.ts.map +1 -1
  229. package/dest/services/tx_collection/config.d.ts +2 -23
  230. package/dest/services/tx_collection/config.d.ts.map +1 -1
  231. package/dest/services/tx_collection/config.js +2 -55
  232. package/dest/services/tx_collection/file_store_tx_collection.d.ts +12 -28
  233. package/dest/services/tx_collection/file_store_tx_collection.d.ts.map +1 -1
  234. package/dest/services/tx_collection/file_store_tx_collection.js +43 -83
  235. package/dest/services/tx_collection/file_store_tx_source.d.ts +5 -4
  236. package/dest/services/tx_collection/file_store_tx_source.d.ts.map +1 -1
  237. package/dest/services/tx_collection/file_store_tx_source.js +39 -29
  238. package/dest/services/tx_collection/index.d.ts +2 -3
  239. package/dest/services/tx_collection/index.d.ts.map +1 -1
  240. package/dest/services/tx_collection/index.js +0 -1
  241. package/dest/services/tx_collection/instrumentation.d.ts +1 -1
  242. package/dest/services/tx_collection/instrumentation.d.ts.map +1 -1
  243. package/dest/services/tx_collection/instrumentation.js +0 -2
  244. package/dest/services/tx_collection/request_tracker.d.ts +53 -0
  245. package/dest/services/tx_collection/request_tracker.d.ts.map +1 -0
  246. package/dest/services/tx_collection/request_tracker.js +84 -0
  247. package/dest/services/tx_collection/tx_collection.d.ts +36 -55
  248. package/dest/services/tx_collection/tx_collection.d.ts.map +1 -1
  249. package/dest/services/tx_collection/tx_collection.js +275 -119
  250. package/dest/services/tx_collection/tx_collection_sink.d.ts +1 -1
  251. package/dest/services/tx_collection/tx_collection_sink.js +2 -2
  252. package/dest/services/tx_collection/tx_source.d.ts +6 -5
  253. package/dest/services/tx_collection/tx_source.d.ts.map +1 -1
  254. package/dest/services/tx_collection/tx_source.js +13 -8
  255. package/dest/services/tx_file_store/tx_file_store.d.ts +1 -3
  256. package/dest/services/tx_file_store/tx_file_store.d.ts.map +1 -1
  257. package/dest/services/tx_file_store/tx_file_store.js +4 -14
  258. package/dest/services/tx_provider.d.ts +3 -1
  259. package/dest/services/tx_provider.d.ts.map +1 -1
  260. package/dest/services/tx_provider.js +3 -0
  261. package/dest/test-helpers/make-test-p2p-clients.d.ts +1 -1
  262. package/dest/test-helpers/make-test-p2p-clients.d.ts.map +1 -1
  263. package/dest/test-helpers/make-test-p2p-clients.js +5 -2
  264. package/dest/test-helpers/mock-pubsub.d.ts +33 -9
  265. package/dest/test-helpers/mock-pubsub.d.ts.map +1 -1
  266. package/dest/test-helpers/mock-pubsub.js +57 -44
  267. package/dest/test-helpers/reqresp-nodes.d.ts +4 -5
  268. package/dest/test-helpers/reqresp-nodes.d.ts.map +1 -1
  269. package/dest/test-helpers/reqresp-nodes.js +16 -18
  270. package/dest/test-helpers/test_tx_provider.d.ts +3 -1
  271. package/dest/test-helpers/test_tx_provider.d.ts.map +1 -1
  272. package/dest/test-helpers/test_tx_provider.js +3 -0
  273. package/dest/test-helpers/testbench-utils.d.ts +15 -14
  274. package/dest/test-helpers/testbench-utils.d.ts.map +1 -1
  275. package/dest/test-helpers/testbench-utils.js +49 -15
  276. package/dest/testbench/p2p_client_testbench_worker.d.ts +3 -5
  277. package/dest/testbench/p2p_client_testbench_worker.d.ts.map +1 -1
  278. package/dest/testbench/p2p_client_testbench_worker.js +104 -41
  279. package/dest/testbench/worker_client_manager.d.ts +12 -6
  280. package/dest/testbench/worker_client_manager.d.ts.map +1 -1
  281. package/dest/testbench/worker_client_manager.js +57 -11
  282. package/dest/util.d.ts +12 -7
  283. package/dest/util.d.ts.map +1 -1
  284. package/dest/util.js +35 -14
  285. package/dest/versioning.d.ts +3 -6
  286. package/dest/versioning.d.ts.map +1 -1
  287. package/dest/versioning.js +3 -24
  288. package/package.json +17 -17
  289. package/src/bootstrap/bootstrap.ts +17 -3
  290. package/src/client/factory.ts +62 -9
  291. package/src/client/interface.ts +48 -18
  292. package/src/client/p2p_client.ts +159 -113
  293. package/src/client/test/{tx_proposal_collector/README.md → p2p_client.batch_tx_requester.bench.README.md} +23 -53
  294. package/src/config.ts +233 -20
  295. package/src/errors/p2p-service.error.ts +11 -0
  296. package/src/errors/reqresp.error.ts +13 -19
  297. package/src/index.ts +0 -1
  298. package/src/mem_pools/attestation_pool/attestation_pool.ts +327 -242
  299. package/src/mem_pools/attestation_pool/attestation_pool_test_suite.ts +244 -69
  300. package/src/mem_pools/attestation_pool/mocks.ts +13 -8
  301. package/src/mem_pools/index.ts +0 -3
  302. package/src/mem_pools/instrumentation.ts +18 -12
  303. package/src/mem_pools/tx_pool_v2/README.md +9 -1
  304. package/src/mem_pools/tx_pool_v2/archive/tx_archive.ts +30 -20
  305. package/src/mem_pools/tx_pool_v2/deleted_pool.ts +7 -7
  306. package/src/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.ts +4 -5
  307. package/src/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.ts +3 -2
  308. package/src/mem_pools/tx_pool_v2/eviction/index.ts +1 -0
  309. package/src/mem_pools/tx_pool_v2/eviction/insufficient_fee_per_gas_eviction_rule.ts +67 -0
  310. package/src/mem_pools/tx_pool_v2/eviction/interfaces.ts +11 -1
  311. package/src/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.ts +1 -3
  312. package/src/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.ts +5 -7
  313. package/src/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.ts +5 -6
  314. package/src/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.ts +15 -6
  315. package/src/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.ts +2 -1
  316. package/src/mem_pools/tx_pool_v2/instrumentation.ts +27 -0
  317. package/src/mem_pools/tx_pool_v2/interfaces.ts +40 -8
  318. package/src/mem_pools/tx_pool_v2/tx_metadata.ts +72 -20
  319. package/src/mem_pools/tx_pool_v2/tx_pool_indices.ts +62 -41
  320. package/src/mem_pools/tx_pool_v2/tx_pool_v2.ts +107 -32
  321. package/src/mem_pools/tx_pool_v2/tx_pool_v2_impl.ts +291 -137
  322. package/src/msg_validators/attestation_validator/README.md +49 -0
  323. package/src/msg_validators/attestation_validator/attestation_validator.ts +46 -14
  324. package/src/msg_validators/attestation_validator/fisherman_attestation_validator.ts +15 -7
  325. package/src/msg_validators/proposal_validator/README.md +123 -0
  326. package/src/msg_validators/proposal_validator/block_proposal_validator.ts +26 -4
  327. package/src/msg_validators/proposal_validator/checkpoint_proposal_validator.ts +43 -7
  328. package/src/msg_validators/proposal_validator/proposal_validator.ts +150 -58
  329. package/src/msg_validators/tx_validator/README.md +17 -3
  330. package/src/msg_validators/tx_validator/aggregate_tx_validator.ts +3 -12
  331. package/src/msg_validators/tx_validator/allowed_public_setup.ts +16 -35
  332. package/src/msg_validators/tx_validator/allowed_setup_helpers.ts +31 -0
  333. package/src/msg_validators/tx_validator/archive_cache.ts +1 -1
  334. package/src/msg_validators/tx_validator/cached_tx_validator.ts +31 -0
  335. package/src/msg_validators/tx_validator/contract_instance_validator.ts +56 -0
  336. package/src/msg_validators/tx_validator/data_validator.ts +44 -1
  337. package/src/msg_validators/tx_validator/factory.ts +66 -9
  338. package/src/msg_validators/tx_validator/fee_payer_balance.ts +6 -2
  339. package/src/msg_validators/tx_validator/gas_validator.ts +117 -39
  340. package/src/msg_validators/tx_validator/index.ts +3 -0
  341. package/src/msg_validators/tx_validator/metadata_validator.ts +12 -4
  342. package/src/msg_validators/tx_validator/phases_validator.ts +60 -1
  343. package/src/msg_validators/tx_validator/tx_proof_validator.ts +2 -0
  344. package/src/msg_validators/tx_validator/tx_validation_cache.ts +101 -0
  345. package/src/services/data_store.ts +5 -13
  346. package/src/services/discv5/discV5_service.ts +126 -14
  347. package/src/services/discv5/persisted_enr_store.ts +158 -0
  348. package/src/services/dummy_service.ts +26 -40
  349. package/src/services/encoding.ts +35 -19
  350. package/src/services/gossipsub/README.md +33 -11
  351. package/src/services/gossipsub/topic_score_params.ts +9 -18
  352. package/src/services/libp2p/instrumentation.ts +22 -0
  353. package/src/services/libp2p/libp2p_service.ts +560 -369
  354. package/src/services/peer-manager/peer_manager.ts +138 -24
  355. package/src/services/peer-manager/peer_scoring.ts +102 -8
  356. package/src/services/reqresp/README.md +194 -0
  357. package/src/services/reqresp/batch-tx-requester/README.md +46 -7
  358. package/src/services/reqresp/batch-tx-requester/batch_tx_requester.ts +77 -95
  359. package/src/services/reqresp/batch-tx-requester/interface.ts +13 -5
  360. package/src/services/reqresp/batch-tx-requester/missing_txs.ts +13 -6
  361. package/src/services/reqresp/batch-tx-requester/peer_collection.ts +5 -0
  362. package/src/services/reqresp/batch-tx-requester/tx_validator.ts +12 -25
  363. package/src/services/reqresp/config.ts +19 -2
  364. package/src/services/reqresp/interface.ts +21 -47
  365. package/src/services/reqresp/metrics.ts +0 -1
  366. package/src/services/reqresp/protocols/block_txs/bitvector.ts +3 -2
  367. package/src/services/reqresp/protocols/block_txs/block_txs_handler.ts +34 -30
  368. package/src/services/reqresp/protocols/block_txs/block_txs_reqresp.ts +47 -20
  369. package/src/services/reqresp/protocols/index.ts +0 -1
  370. package/src/services/reqresp/protocols/tx.ts +1 -3
  371. package/src/services/reqresp/rate-limiter/rate_limiter.ts +13 -9
  372. package/src/services/reqresp/rate-limiter/rate_limits.ts +3 -13
  373. package/src/services/reqresp/reqresp.ts +84 -259
  374. package/src/services/service.ts +51 -35
  375. package/src/services/tx_collection/config.ts +3 -80
  376. package/src/services/tx_collection/file_store_tx_collection.ts +54 -103
  377. package/src/services/tx_collection/file_store_tx_source.ts +43 -31
  378. package/src/services/tx_collection/index.ts +1 -6
  379. package/src/services/tx_collection/instrumentation.ts +1 -7
  380. package/src/services/tx_collection/request_tracker.ts +127 -0
  381. package/src/services/tx_collection/tx_collection.ts +331 -176
  382. package/src/services/tx_collection/tx_collection_sink.ts +2 -2
  383. package/src/services/tx_collection/tx_source.ts +10 -8
  384. package/src/services/tx_file_store/tx_file_store.ts +5 -17
  385. package/src/services/tx_provider.ts +5 -0
  386. package/src/test-helpers/make-test-p2p-clients.ts +4 -1
  387. package/src/test-helpers/mock-pubsub.ts +61 -60
  388. package/src/test-helpers/reqresp-nodes.ts +13 -23
  389. package/src/test-helpers/test_tx_provider.ts +5 -0
  390. package/src/test-helpers/testbench-utils.ts +63 -28
  391. package/src/testbench/p2p_client_testbench_worker.ts +111 -57
  392. package/src/testbench/worker_client_manager.ts +72 -25
  393. package/src/util.ts +33 -18
  394. package/src/versioning.ts +3 -33
  395. package/dest/client/test/tx_proposal_collector/proposal_tx_collector_worker.d.ts +0 -2
  396. package/dest/client/test/tx_proposal_collector/proposal_tx_collector_worker.d.ts.map +0 -1
  397. package/dest/client/test/tx_proposal_collector/proposal_tx_collector_worker.js +0 -304
  398. package/dest/client/test/tx_proposal_collector/proposal_tx_collector_worker_protocol.d.ts +0 -73
  399. package/dest/client/test/tx_proposal_collector/proposal_tx_collector_worker_protocol.d.ts.map +0 -1
  400. package/dest/client/test/tx_proposal_collector/proposal_tx_collector_worker_protocol.js +0 -8
  401. package/dest/mem_pools/tx_pool/aztec_kv_tx_pool.d.ts +0 -125
  402. package/dest/mem_pools/tx_pool/aztec_kv_tx_pool.d.ts.map +0 -1
  403. package/dest/mem_pools/tx_pool/aztec_kv_tx_pool.js +0 -596
  404. package/dest/mem_pools/tx_pool/eviction/eviction_manager.d.ts +0 -32
  405. package/dest/mem_pools/tx_pool/eviction/eviction_manager.d.ts.map +0 -1
  406. package/dest/mem_pools/tx_pool/eviction/eviction_manager.js +0 -112
  407. package/dest/mem_pools/tx_pool/eviction/eviction_strategy.d.ts +0 -157
  408. package/dest/mem_pools/tx_pool/eviction/eviction_strategy.d.ts.map +0 -1
  409. package/dest/mem_pools/tx_pool/eviction/eviction_strategy.js +0 -52
  410. package/dest/mem_pools/tx_pool/eviction/fee_payer_balance_eviction_rule.d.ts +0 -16
  411. package/dest/mem_pools/tx_pool/eviction/fee_payer_balance_eviction_rule.d.ts.map +0 -1
  412. package/dest/mem_pools/tx_pool/eviction/fee_payer_balance_eviction_rule.js +0 -122
  413. package/dest/mem_pools/tx_pool/eviction/invalid_txs_after_mining_rule.d.ts +0 -17
  414. package/dest/mem_pools/tx_pool/eviction/invalid_txs_after_mining_rule.d.ts.map +0 -1
  415. package/dest/mem_pools/tx_pool/eviction/invalid_txs_after_mining_rule.js +0 -84
  416. package/dest/mem_pools/tx_pool/eviction/invalid_txs_after_reorg_rule.d.ts +0 -19
  417. package/dest/mem_pools/tx_pool/eviction/invalid_txs_after_reorg_rule.d.ts.map +0 -1
  418. package/dest/mem_pools/tx_pool/eviction/invalid_txs_after_reorg_rule.js +0 -78
  419. package/dest/mem_pools/tx_pool/eviction/low_priority_eviction_rule.d.ts +0 -26
  420. package/dest/mem_pools/tx_pool/eviction/low_priority_eviction_rule.d.ts.map +0 -1
  421. package/dest/mem_pools/tx_pool/eviction/low_priority_eviction_rule.js +0 -84
  422. package/dest/mem_pools/tx_pool/eviction/nullifier_conflict_pre_add_rule.d.ts +0 -25
  423. package/dest/mem_pools/tx_pool/eviction/nullifier_conflict_pre_add_rule.d.ts.map +0 -1
  424. package/dest/mem_pools/tx_pool/eviction/nullifier_conflict_pre_add_rule.js +0 -57
  425. package/dest/mem_pools/tx_pool/index.d.ts +0 -3
  426. package/dest/mem_pools/tx_pool/index.d.ts.map +0 -1
  427. package/dest/mem_pools/tx_pool/index.js +0 -2
  428. package/dest/mem_pools/tx_pool/priority.d.ts +0 -12
  429. package/dest/mem_pools/tx_pool/priority.d.ts.map +0 -1
  430. package/dest/mem_pools/tx_pool/priority.js +0 -15
  431. package/dest/mem_pools/tx_pool/tx_pool.d.ts +0 -127
  432. package/dest/mem_pools/tx_pool/tx_pool.d.ts.map +0 -1
  433. package/dest/mem_pools/tx_pool/tx_pool.js +0 -3
  434. package/dest/mem_pools/tx_pool/tx_pool_test_suite.d.ts +0 -7
  435. package/dest/mem_pools/tx_pool/tx_pool_test_suite.d.ts.map +0 -1
  436. package/dest/mem_pools/tx_pool/tx_pool_test_suite.js +0 -400
  437. package/dest/msg_validators/clock_tolerance.d.ts +0 -21
  438. package/dest/msg_validators/clock_tolerance.d.ts.map +0 -1
  439. package/dest/msg_validators/clock_tolerance.js +0 -37
  440. package/dest/msg_validators/proposal_validator/proposal_validator_test_suite.d.ts +0 -24
  441. package/dest/msg_validators/proposal_validator/proposal_validator_test_suite.d.ts.map +0 -1
  442. package/dest/msg_validators/proposal_validator/proposal_validator_test_suite.js +0 -378
  443. package/dest/services/reqresp/connection-sampler/batch_connection_sampler.d.ts +0 -64
  444. package/dest/services/reqresp/connection-sampler/batch_connection_sampler.d.ts.map +0 -1
  445. package/dest/services/reqresp/connection-sampler/batch_connection_sampler.js +0 -151
  446. package/dest/services/reqresp/protocols/block.d.ts +0 -9
  447. package/dest/services/reqresp/protocols/block.d.ts.map +0 -1
  448. package/dest/services/reqresp/protocols/block.js +0 -32
  449. package/dest/services/tx_collection/fast_tx_collection.d.ts +0 -54
  450. package/dest/services/tx_collection/fast_tx_collection.d.ts.map +0 -1
  451. package/dest/services/tx_collection/fast_tx_collection.js +0 -327
  452. package/dest/services/tx_collection/missing_txs_tracker.d.ts +0 -32
  453. package/dest/services/tx_collection/missing_txs_tracker.d.ts.map +0 -1
  454. package/dest/services/tx_collection/missing_txs_tracker.js +0 -27
  455. package/dest/services/tx_collection/proposal_tx_collector.d.ts +0 -49
  456. package/dest/services/tx_collection/proposal_tx_collector.d.ts.map +0 -1
  457. package/dest/services/tx_collection/proposal_tx_collector.js +0 -50
  458. package/dest/services/tx_collection/slow_tx_collection.d.ts +0 -57
  459. package/dest/services/tx_collection/slow_tx_collection.d.ts.map +0 -1
  460. package/dest/services/tx_collection/slow_tx_collection.js +0 -211
  461. package/src/client/test/tx_proposal_collector/proposal_tx_collector_worker.ts +0 -345
  462. package/src/client/test/tx_proposal_collector/proposal_tx_collector_worker_protocol.ts +0 -43
  463. package/src/mem_pools/tx_pool/README.md +0 -270
  464. package/src/mem_pools/tx_pool/aztec_kv_tx_pool.ts +0 -746
  465. package/src/mem_pools/tx_pool/eviction/eviction_manager.ts +0 -132
  466. package/src/mem_pools/tx_pool/eviction/eviction_strategy.ts +0 -208
  467. package/src/mem_pools/tx_pool/eviction/fee_payer_balance_eviction_rule.ts +0 -162
  468. package/src/mem_pools/tx_pool/eviction/invalid_txs_after_mining_rule.ts +0 -104
  469. package/src/mem_pools/tx_pool/eviction/invalid_txs_after_reorg_rule.ts +0 -93
  470. package/src/mem_pools/tx_pool/eviction/low_priority_eviction_rule.ts +0 -106
  471. package/src/mem_pools/tx_pool/eviction/nullifier_conflict_pre_add_rule.ts +0 -75
  472. package/src/mem_pools/tx_pool/index.ts +0 -2
  473. package/src/mem_pools/tx_pool/priority.ts +0 -20
  474. package/src/mem_pools/tx_pool/tx_pool.ts +0 -141
  475. package/src/mem_pools/tx_pool/tx_pool_test_suite.ts +0 -319
  476. package/src/msg_validators/clock_tolerance.ts +0 -51
  477. package/src/msg_validators/proposal_validator/proposal_validator_test_suite.ts +0 -373
  478. package/src/services/reqresp/connection-sampler/batch_connection_sampler.ts +0 -161
  479. package/src/services/reqresp/protocols/block.ts +0 -37
  480. package/src/services/tx_collection/fast_tx_collection.ts +0 -387
  481. package/src/services/tx_collection/missing_txs_tracker.ts +0 -52
  482. package/src/services/tx_collection/proposal_tx_collector.ts +0 -113
  483. package/src/services/tx_collection/slow_tx_collection.ts +0 -266
@@ -1,32 +1,41 @@
1
1
  import type { EpochCacheInterface } from '@aztec/epoch-cache';
2
2
  import { BlockNumber, type SlotNumber } from '@aztec/foundation/branded-types';
3
- import { Fr } from '@aztec/foundation/curves/bn254';
3
+ import { compactArray, maxBy, merge } from '@aztec/foundation/collection';
4
4
  import { type Logger, createLibp2pComponentLogger, createLogger } from '@aztec/foundation/log';
5
5
  import { RunningPromise } from '@aztec/foundation/running-promise';
6
6
  import { Timer } from '@aztec/foundation/timer';
7
7
  import type { AztecAsyncKVStore } from '@aztec/kv-store';
8
8
  import { protocolContractsHash } from '@aztec/protocol-contracts';
9
- import type { EthAddress, L2Block, L2BlockSource } from '@aztec/stdlib/block';
9
+ import type { EthAddress, L2BlockSource } from '@aztec/stdlib/block';
10
+ import { DEFAULT_MAX_BLOCKS_PER_CHECKPOINT } from '@aztec/stdlib/config';
10
11
  import type { ContractDataSource } from '@aztec/stdlib/contract';
11
- import { GasFees } from '@aztec/stdlib/gas';
12
- import type { ClientProtocolCircuitVerifier, PeerInfo, WorldStateSynchronizer } from '@aztec/stdlib/interfaces/server';
12
+ import { type BlockMinFeesProvider, GasFees, getNetworkTxGasLimits } from '@aztec/stdlib/gas';
13
+ import type {
14
+ ClientProtocolCircuitVerifier,
15
+ P2PConnectivity,
16
+ PeerInfo,
17
+ WorldStateSynchronizer,
18
+ } from '@aztec/stdlib/interfaces/server';
13
19
  import {
14
20
  BlockProposal,
15
21
  CheckpointAttestation,
16
22
  CheckpointProposal,
17
- type CheckpointProposalCore,
18
23
  type Gossipable,
19
24
  P2PMessage,
20
- type ValidationResult as P2PValidationResult,
21
25
  PeerErrorSeverity,
26
+ PeerErrorSeverityByHarshness,
22
27
  TopicType,
28
+ ValidatedBlockProposal,
29
+ ValidatedCheckpointProposalCore,
23
30
  createTopicString,
24
31
  getTopicsForConfig,
25
32
  metricsTopicStrToLabels,
26
33
  } from '@aztec/stdlib/p2p';
34
+ import { ConsensusTimetable, getDefaultCheckpointProposalSyncGrace } from '@aztec/stdlib/timetable';
27
35
  import { MerkleTreeId } from '@aztec/stdlib/trees';
28
- import { Tx, type TxHash, type TxValidationResult, type TxValidator } from '@aztec/stdlib/tx';
36
+ import { Tx, type TxValidationResult } from '@aztec/stdlib/tx';
29
37
  import type { UInt64 } from '@aztec/stdlib/types';
38
+ import { InvalidBlockProposalTxsError } from '@aztec/stdlib/validators';
30
39
  import { compressComponentVersions } from '@aztec/stdlib/versioning';
31
40
  import {
32
41
  Attributes,
@@ -50,13 +59,15 @@ import { yamux } from '@chainsafe/libp2p-yamux';
50
59
  import { bootstrap } from '@libp2p/bootstrap';
51
60
  import { identify } from '@libp2p/identify';
52
61
  import { type Message, type MultiaddrConnection, type PeerId, TopicValidatorResult } from '@libp2p/interface';
53
- import type { ConnectionManager } from '@libp2p/interface-internal';
62
+ import type { AddressManager, ConnectionManager } from '@libp2p/interface-internal';
54
63
  import { mplex } from '@libp2p/mplex';
55
64
  import { tcp } from '@libp2p/tcp';
65
+ import { multiaddr } from '@multiformats/multiaddr';
56
66
  import { ENR } from '@nethermindeth/enr';
57
67
  import { createLibp2p } from 'libp2p';
58
68
 
59
69
  import type { P2PConfig } from '../../config.js';
70
+ import { CheckpointProposalReceivedCallbackNotRegisteredError } from '../../errors/p2p-service.error.js';
60
71
  import type { MemPools } from '../../mem_pools/interface.js';
61
72
  import {
62
73
  BlockProposalValidator,
@@ -72,38 +83,34 @@ import {
72
83
  createFirstStageTxValidationsForGossipedTransactions,
73
84
  createSecondStageTxValidationsForGossipedTransactions,
74
85
  createTxValidatorForBlockProposalReceivedTxs,
75
- createTxValidatorForReqResponseReceivedTxs,
76
86
  } from '../../msg_validators/tx_validator/factory.js';
87
+ import { TxValidationCache } from '../../msg_validators/tx_validator/tx_validation_cache.js';
77
88
  import { GossipSubEvent } from '../../types/index.js';
78
89
  import { type PubSubLibp2p, convertToMultiaddr } from '../../util.js';
79
90
  import { getVersions } from '../../versioning.js';
80
91
  import { AztecDatastore } from '../data_store.js';
81
92
  import { DiscV5Service } from '../discv5/discV5_service.js';
82
- import { SnappyTransform, fastMsgIdFn, getMsgIdFn, msgIdToStrFn } from '../encoding.js';
93
+ import { SnappyTransform, getMsgIdFn, msgIdToStrFn } from '../encoding.js';
83
94
  import { APP_SPECIFIC_WEIGHT, gossipScoreThresholds } from '../gossipsub/scoring.js';
84
95
  import { createAllTopicScoreParams } from '../gossipsub/topic_score_params.js';
85
96
  import type { PeerManagerInterface } from '../peer-manager/interface.js';
86
97
  import { PeerManager } from '../peer-manager/peer_manager.js';
87
98
  import { PeerScoring } from '../peer-manager/peer_scoring.js';
88
99
  import type { BatchTxRequesterLibP2PService } from '../reqresp/batch-tx-requester/interface.js';
89
- import type { P2PReqRespConfig } from '../reqresp/config.js';
100
+ import { type P2PReqRespConfig, YAMUX_MAX_MESSAGE_SIZE_BYTES } from '../reqresp/config.js';
90
101
  import {
91
102
  AuthRequest,
92
103
  BlockTxsRequest,
93
104
  BlockTxsResponse,
94
- DEFAULT_SUB_PROTOCOL_VALIDATORS,
95
105
  type ReqRespInterface,
96
106
  type ReqRespResponse,
97
107
  ReqRespSubProtocol,
98
108
  type ReqRespSubProtocolHandler,
99
109
  type ReqRespSubProtocolHandlers,
100
- type ReqRespSubProtocolValidators,
101
110
  StatusMessage,
102
- type SubProtocolMap,
103
111
  ValidationError,
104
112
  pingHandler,
105
113
  reqGoodbyeHandler,
106
- reqRespBlockHandler,
107
114
  reqRespBlockTxsHandler,
108
115
  reqRespStatusHandler,
109
116
  reqRespTxHandler,
@@ -111,13 +118,33 @@ import {
111
118
  import { ReqResp } from '../reqresp/reqresp.js';
112
119
  import type {
113
120
  P2PBlockReceivedCallback,
121
+ P2PCheckpointAttestationCallback,
114
122
  P2PCheckpointReceivedCallback,
115
123
  P2PDuplicateAttestationCallback,
124
+ P2POversizedProposalCallback,
116
125
  P2PService,
117
126
  PeerDiscoveryService,
118
127
  } from '../service.js';
119
128
  import { P2PInstrumentation } from './instrumentation.js';
120
129
 
130
+ /**
131
+ * Builds the {@link ConsensusTimetable} shared by the gossip validators for proposal/attestation receive-window
132
+ * bounds. Derived purely from protocol slot-timing constants plus the block sub-slot duration and the consensus
133
+ * materialization grace, so every node agrees on these bounds without depending on proposer operational budgets.
134
+ */
135
+ function buildConsensusTimetable(
136
+ config: P2PConfig,
137
+ l1Constants: ReturnType<EpochCacheInterface['getL1Constants']>,
138
+ ): ConsensusTimetable {
139
+ const blockDuration = config.blockDurationMs / 1000;
140
+ return new ConsensusTimetable({
141
+ l1Constants,
142
+ blockDuration,
143
+ checkpointProposalSyncGrace:
144
+ config.checkpointProposalSyncGraceSeconds ?? getDefaultCheckpointProposalSyncGrace(blockDuration),
145
+ });
146
+ }
147
+
121
148
  interface ValidationResult {
122
149
  name: string;
123
150
  isValid: TxValidationResult;
@@ -129,7 +156,7 @@ type ValidationOutcome = { allPassed: true } | { allPassed: false; failure: Vali
129
156
  // REFACTOR: Unify with the type above
130
157
  type ReceivedMessageValidationResult<T, M = undefined> =
131
158
  | { obj: T; result: Exclude<TopicValidatorResult, TopicValidatorResult.Reject>; metadata?: M }
132
- | { obj?: T; result: TopicValidatorResult.Reject; metadata?: M };
159
+ | { obj?: T; result: TopicValidatorResult.Reject; metadata?: M; severity: PeerErrorSeverity };
133
160
 
134
161
  /**
135
162
  * Lib P2P implementation of the P2PService interface.
@@ -146,8 +173,6 @@ export class LibP2PService extends WithTracer implements P2PService {
146
173
  private protocolVersion = '';
147
174
  private topicStrings: Record<TopicType, string> = {} as Record<TopicType, string>;
148
175
 
149
- private feesCache: { blockNumber: BlockNumber; gasFees: GasFees } | undefined;
150
-
151
176
  /** Callback invoked when a duplicate proposal is detected (triggers slashing). */
152
177
  private duplicateProposalCallback?: (info: {
153
178
  slot: SlotNumber;
@@ -155,9 +180,15 @@ export class LibP2PService extends WithTracer implements P2PService {
155
180
  type: 'checkpoint' | 'block';
156
181
  }) => void;
157
182
 
183
+ /** Callback invoked when an oversized block proposal is stored as slashing evidence (triggers slashing). */
184
+ private oversizedProposalCallback?: P2POversizedProposalCallback;
185
+
158
186
  /** Callback invoked when a duplicate attestation is detected (triggers slashing). */
159
187
  private duplicateAttestationCallback?: P2PDuplicateAttestationCallback;
160
188
 
189
+ /** Callback invoked when a valid checkpoint attestation is accepted into the pool. */
190
+ private checkpointAttestationCallback?: P2PCheckpointAttestationCallback;
191
+
161
192
  /**
162
193
  * Callback for when a block is received from a peer.
163
194
  * @param block - The block received from the peer.
@@ -170,10 +201,19 @@ export class LibP2PService extends WithTracer implements P2PService {
170
201
  * @param checkpoint - The checkpoint proposal received from the peer.
171
202
  * @returns The attestations for the checkpoint, if any.
172
203
  */
173
- private checkpointReceivedCallback: P2PCheckpointReceivedCallback;
204
+ private allNodesCheckpointReceivedCallback: P2PCheckpointReceivedCallback;
205
+ /**
206
+ * Callback for when a checkpoint proposal is received - specifically for validators - from a peer.
207
+ * @param checkpoint - The checkpoint proposal received from the peer.
208
+ * @returns The attestations for the checkpoint, if any.
209
+ */
210
+ private validatorCheckpointReceivedCallback: P2PCheckpointReceivedCallback;
174
211
 
175
212
  private gossipSubEventHandler: (e: CustomEvent<GossipsubMessage>) => void;
176
213
 
214
+ private ipChangedHandler?: (ip: string) => void;
215
+ private discoveredP2pIp?: string;
216
+
177
217
  private instrumentation: P2PInstrumentation;
178
218
 
179
219
  private telemetry: TelemetryClient;
@@ -191,8 +231,10 @@ export class LibP2PService extends WithTracer implements P2PService {
191
231
  private epochCache: EpochCacheInterface,
192
232
  private proofVerifier: ClientProtocolCircuitVerifier,
193
233
  private worldStateSynchronizer: WorldStateSynchronizer,
234
+ private blockMinFeesProvider: BlockMinFeesProvider,
194
235
  telemetry: TelemetryClient,
195
236
  logger: Logger = createLogger('p2p:libp2p_service'),
237
+ private txValidationCache?: TxValidationCache,
196
238
  ) {
197
239
  super(telemetry, 'LibP2PService');
198
240
  this.telemetry = telemetry;
@@ -222,40 +264,66 @@ export class LibP2PService extends WithTracer implements P2PService {
222
264
  this.protocolVersion,
223
265
  );
224
266
 
225
- this.blockProposalValidator = new BlockProposalValidator(epochCache, {
226
- txsPermitted: !config.disableTransactions,
227
- maxTxsPerBlock: config.maxTxsPerBlock,
228
- });
229
- this.checkpointProposalValidator = new CheckpointProposalValidator(epochCache, {
267
+ // Build the consensus timetable once from protocol slot-timing constants and inject it into every
268
+ // validator so they share one set of receive-window bounds, independent of proposer operational budgets.
269
+ const consensusTimetable = buildConsensusTimetable(config, epochCache.getL1Constants());
270
+ const proposalValidatorOpts = {
230
271
  txsPermitted: !config.disableTransactions,
231
- maxTxsPerBlock: config.maxTxsPerBlock,
232
- });
272
+ maxTxsPerBlock: config.validateMaxTxsPerBlock ?? config.validateMaxTxsPerCheckpoint,
273
+ maxBlocksPerCheckpoint: config.maxBlocksPerCheckpoint,
274
+ skipSlotValidation: config.skipProposalSlotValidation,
275
+ signatureContext: {
276
+ chainId: config.l1ChainId,
277
+ rollupAddress: config.rollupAddress,
278
+ },
279
+ clockDisparityMs: config.maxGossipClockDisparityMs,
280
+ };
281
+ this.blockProposalValidator = new BlockProposalValidator(epochCache, consensusTimetable, proposalValidatorOpts);
282
+ this.checkpointProposalValidator = new CheckpointProposalValidator(
283
+ epochCache,
284
+ consensusTimetable,
285
+ proposalValidatorOpts,
286
+ );
287
+ const attestationValidatorOpts = {
288
+ signatureContext: proposalValidatorOpts.signatureContext,
289
+ clockDisparityMs: config.maxGossipClockDisparityMs,
290
+ };
233
291
  this.checkpointAttestationValidator = config.fishermanMode
234
- ? new FishermanAttestationValidator(epochCache, mempools.attestationPool, telemetry)
235
- : new CheckpointAttestationValidator(epochCache);
292
+ ? new FishermanAttestationValidator(
293
+ epochCache,
294
+ consensusTimetable,
295
+ mempools.attestationPool,
296
+ telemetry,
297
+ attestationValidatorOpts,
298
+ )
299
+ : new CheckpointAttestationValidator(epochCache, consensusTimetable, attestationValidatorOpts);
236
300
 
237
301
  this.gossipSubEventHandler = this.handleGossipSubEvent.bind(this);
238
302
 
239
303
  this.blockReceivedCallback = async (block: BlockProposal): Promise<boolean> => {
240
- this.logger.debug(
241
- `Handler not yet registered: Block received callback not set. Received block for slot ${block.slotNumber} from peer.`,
304
+ this.logger.warn(
305
+ `Handler for block received not yet registered on P2P service. Received block ${block.blockNumber} for slot ${block.slotNumber} from peer.`,
242
306
  { p2pMessageIdentifier: await block.p2pMessageLoggingIdentifier() },
243
307
  );
244
- return false;
308
+ return true;
245
309
  };
246
310
 
247
- this.checkpointReceivedCallback = (
248
- checkpoint: CheckpointProposalCore,
311
+ this.allNodesCheckpointReceivedCallback = (
312
+ _checkpoint: ValidatedCheckpointProposalCore,
313
+ ): Promise<CheckpointAttestation[] | undefined> => {
314
+ throw new CheckpointProposalReceivedCallbackNotRegisteredError();
315
+ };
316
+
317
+ this.validatorCheckpointReceivedCallback = (
318
+ _checkpoint: ValidatedCheckpointProposalCore,
249
319
  ): Promise<CheckpointAttestation[] | undefined> => {
250
- this.logger.debug(
251
- `Handler not yet registered: Checkpoint received callback not set. Received checkpoint for slot ${checkpoint.slotNumber} from peer.`,
252
- );
253
320
  return Promise.resolve(undefined);
254
321
  };
255
322
  }
256
323
 
257
- public updateConfig(config: Partial<P2PReqRespConfig>) {
324
+ public updateConfig(config: Partial<P2PReqRespConfig & Pick<P2PConfig, 'skipIncomingProposals'>>) {
258
325
  this.reqresp.updateConfig(config);
326
+ this.config = merge(this.config, config);
259
327
  }
260
328
 
261
329
  /**
@@ -274,9 +342,11 @@ export class LibP2PService extends WithTracer implements P2PService {
274
342
  proofVerifier: ClientProtocolCircuitVerifier;
275
343
  worldStateSynchronizer: WorldStateSynchronizer;
276
344
  peerStore: AztecAsyncKVStore;
345
+ blockMinFeesProvider: BlockMinFeesProvider;
277
346
  telemetry: TelemetryClient;
278
347
  logger: Logger;
279
348
  packageVersion: string;
349
+ txValidationCache?: TxValidationCache;
280
350
  },
281
351
  ) {
282
352
  const {
@@ -286,9 +356,11 @@ export class LibP2PService extends WithTracer implements P2PService {
286
356
  mempools,
287
357
  proofVerifier,
288
358
  peerStore,
359
+ blockMinFeesProvider,
289
360
  telemetry,
290
361
  logger,
291
362
  packageVersion,
363
+ txValidationCache,
292
364
  } = deps;
293
365
  const { p2pPort, maxPeerCount, listenAddress } = config;
294
366
  const bindAddrTcp = convertToMultiaddr(listenAddress, p2pPort, 'tcp');
@@ -303,6 +375,7 @@ export class LibP2PService extends WithTracer implements P2PService {
303
375
  packageVersion,
304
376
  telemetry,
305
377
  createLogger(`${logger.module}:discv5_service`, logger.getBindings()),
378
+ peerStore,
306
379
  );
307
380
 
308
381
  // Seed libp2p's bootstrap discovery with private and trusted peers
@@ -317,34 +390,49 @@ export class LibP2PService extends WithTracer implements P2PService {
317
390
  const protocolVersion = compressComponentVersions(versions);
318
391
 
319
392
  const preferredPeersEnrs: ENR[] = config.preferredPeers.map(enr => ENR.decodeTxt(enr));
320
- const directPeers = (
393
+ const directPeers = compactArray(
321
394
  await Promise.all(
322
395
  preferredPeersEnrs.map(async enr => {
323
- const peerId = await enr.peerId();
324
- const address = enr.getLocationMultiaddr('tcp');
325
- if (address === undefined) {
326
- throw new Error(`Direct peer ${peerId.toString()} has no TCP address, ENR: ${enr.encodeTxt()}`);
396
+ try {
397
+ const peerId = await enr.peerId();
398
+ const address = enr.getLocationMultiaddr('tcp');
399
+ if (address === undefined) {
400
+ throw new Error(`Direct peer ${peerId.toString()} has no TCP address, ENR: ${enr.encodeTxt()}`);
401
+ }
402
+ return {
403
+ id: peerId,
404
+ addrs: [address],
405
+ };
406
+ } catch (err) {
407
+ // A malformed configured ENR shouldn't abort node setup — skip it and log.
408
+ logger.warn(`Skipping preferred peer with invalid ENR`, { err });
409
+ return undefined;
327
410
  }
328
- return {
329
- id: peerId,
330
- addrs: [address],
331
- };
332
411
  }),
333
- )
334
- ).filter(peer => peer !== undefined);
412
+ ),
413
+ );
335
414
 
336
415
  const announceTcpMultiaddr = config.p2pIp ? [convertToMultiaddr(config.p2pIp, p2pPort, 'tcp')] : [];
337
416
 
338
- // Create dynamic topic score params based on network configuration
417
+ // Create dynamic topic score params based on network configuration. Scoring uses the network-wide
418
+ // max-blocks-per-checkpoint config value directly to size expected per-slot message rates; these are
419
+ // peer-rate thresholds, not consensus deadlines, so they need no proposer operational budgets.
339
420
  const l1Constants = epochCache.getL1Constants();
340
421
  const topicScoreParams = createAllTopicScoreParams(protocolVersion, {
341
422
  slotDurationMs: l1Constants.slotDuration * 1000,
342
423
  heartbeatIntervalMs: config.gossipsubInterval,
343
424
  targetCommitteeSize: l1Constants.targetCommitteeSize,
344
- blockDurationMs: config.blockDurationMs,
425
+ maxBlocksPerCheckpoint: config.maxBlocksPerCheckpoint ?? DEFAULT_MAX_BLOCKS_PER_CHECKPOINT,
345
426
  expectedBlockProposalsPerSlot: config.expectedBlockProposalsPerSlot,
346
427
  });
347
428
 
429
+ // Restrict gossipsub to exactly the topics we subscribe to. Without this, an arbitrary-topic
430
+ // message is transformed, msg-id'd and inserted into the seenCache before the subscription check,
431
+ // so a crafted topic colliding on msg id can suppress a real message as a duplicate.
432
+ const allowedTopics = getTopicsForConfig(config.disableTransactions).map(topic =>
433
+ createTopicString(topic, protocolVersion),
434
+ );
435
+
348
436
  const node = await createLibp2p({
349
437
  start: false,
350
438
  peerId,
@@ -376,7 +464,8 @@ export class LibP2PService extends WithTracer implements P2PService {
376
464
  ],
377
465
  datastore,
378
466
  peerDiscovery,
379
- streamMuxers: [yamux(), mplex()],
467
+ // Pin the yamux frame size: MAX_REQRESP_REQUEST_SIZE_BYTES relies on a reqresp request fitting in one frame.
468
+ streamMuxers: [yamux({ maxMessageSize: YAMUX_MAX_MESSAGE_SIZE_BYTES }), mplex()],
380
469
  connectionEncryption: [noise()],
381
470
  connectionManager: {
382
471
  minConnections: 0, // Disable libp2p peer dialing, we do it manually
@@ -390,7 +479,7 @@ export class LibP2PService extends WithTracer implements P2PService {
390
479
  },
391
480
  connectionGater: {
392
481
  denyInboundConnection: (maConn: MultiaddrConnection) => {
393
- const allowed = peerManager.isNodeAllowedToConnect(maConn.remoteAddr.nodeAddress().address);
482
+ const allowed = peerManager.isAddressAllowedToConnect(maConn.remoteAddr.nodeAddress().address);
394
483
  if (allowed) {
395
484
  return false;
396
485
  }
@@ -401,7 +490,7 @@ export class LibP2PService extends WithTracer implements P2PService {
401
490
  denyInboundEncryptedConnection: (peerId: PeerId, _maConn: MultiaddrConnection) => {
402
491
  //NOTE: it is not necessary to check address here because this was already done by
403
492
  // denyInboundConnection
404
- const allowed = peerManager.isNodeAllowedToConnect(peerId);
493
+ const allowed = peerManager.isPeerAllowedToConnect(peerId);
405
494
  if (allowed) {
406
495
  return false;
407
496
  }
@@ -429,9 +518,13 @@ export class LibP2PService extends WithTracer implements P2PService {
429
518
  mcacheLength: config.gossipsubMcacheLength,
430
519
  mcacheGossip: config.gossipsubMcacheGossip,
431
520
  seenTTL: config.gossipsubSeenTTL,
521
+ allowedTopics,
522
+ // No fastMsgIdFn: the fast-path dedup cache keys on a non-cryptographic 64-bit hash of the
523
+ // raw data only (no topic), so a collision — accidental or engineered via a weak seed — drops
524
+ // a different message with no fallback to the full id. Dedup instead rests solely on the
525
+ // cryptographic, topic-framed msgIdFn below.
432
526
  msgIdFn: getMsgIdFn,
433
527
  msgIdToStrFn: msgIdToStrFn,
434
- fastMsgIdFn: fastMsgIdFn,
435
528
  dataTransform: new SnappyTransform(),
436
529
  metricsRegister: otelMetricsAdapter,
437
530
  metricsTopicStrToLabel: metricsTopicStrToLabels(protocolVersion),
@@ -443,8 +536,9 @@ export class LibP2PService extends WithTracer implements P2PService {
443
536
  topics: topicScoreParams,
444
537
  }),
445
538
  }) as (components: GossipSubComponents) => GossipSub,
446
- components: (components: { connectionManager: ConnectionManager }) => ({
539
+ components: (components: { connectionManager: ConnectionManager; addressManager: AddressManager }) => ({
447
540
  connectionManager: components.connectionManager,
541
+ addressManager: components.addressManager,
448
542
  }),
449
543
  },
450
544
  logger: createLibp2pComponentLogger(logger.module, logger.getBindings()),
@@ -466,6 +560,9 @@ export class LibP2PService extends WithTracer implements P2PService {
466
560
  epochCache,
467
561
  );
468
562
 
563
+ // Gate req/resp data protocols for unauthenticated peers when p2pAllowOnlyValidators is enabled
564
+ reqresp.setShouldRejectPeer(peerId => peerManager.shouldDisableP2PGossip(peerId));
565
+
469
566
  // Configure application-specific scoring for gossipsub.
470
567
  // The weight scales app score to align with gossipsub thresholds:
471
568
  // - Disconnect (-50) × 10 = -500 = gossipThreshold (stops receiving gossip)
@@ -486,8 +583,10 @@ export class LibP2PService extends WithTracer implements P2PService {
486
583
  epochCache,
487
584
  proofVerifier,
488
585
  worldStateSynchronizer,
586
+ blockMinFeesProvider,
489
587
  telemetry,
490
588
  logger,
589
+ txValidationCache,
491
590
  );
492
591
  }
493
592
 
@@ -501,24 +600,21 @@ export class LibP2PService extends WithTracer implements P2PService {
501
600
  throw new Error('P2P service already started');
502
601
  }
503
602
 
504
- // Get listen & announce addresses for logging
505
603
  const { p2pIp, p2pPort } = this.config;
506
- if (!p2pIp) {
507
- throw new Error('Announce address not provided.');
604
+ if (!p2pIp && !this.config.queryForIp) {
605
+ throw new Error('Announce address not provided and queryForIp is not enabled.');
508
606
  }
509
- const announceTcpMultiaddr = convertToMultiaddr(p2pIp, p2pPort, 'tcp');
607
+ const announceTcpMultiaddr = p2pIp ? convertToMultiaddr(p2pIp, p2pPort, 'tcp') : undefined;
510
608
 
511
609
  // Create request response protocol handlers
512
610
  const txHandler = reqRespTxHandler(this.mempools);
513
611
  const goodbyeHandler = reqGoodbyeHandler(this.peerManager);
514
- const blockHandler = reqRespBlockHandler(this.archiver);
515
612
  const statusHandler = reqRespStatusHandler(this.protocolVersion, this.worldStateSynchronizer, this.logger);
516
613
 
517
614
  const requestResponseHandlers: Partial<ReqRespSubProtocolHandlers> = {
518
615
  [ReqRespSubProtocol.PING]: pingHandler,
519
616
  [ReqRespSubProtocol.STATUS]: statusHandler.bind(this),
520
617
  [ReqRespSubProtocol.GOODBYE]: goodbyeHandler.bind(this),
521
- [ReqRespSubProtocol.BLOCK]: blockHandler.bind(this),
522
618
  };
523
619
 
524
620
  if (!this.config.disableTransactions) {
@@ -534,17 +630,9 @@ export class LibP2PService extends WithTracer implements P2PService {
534
630
  requestResponseHandlers[ReqRespSubProtocol.TX] = txHandler.bind(this);
535
631
  }
536
632
 
537
- // Define the sub protocol validators - This is done within this start() method to gain a callback to the existing validateTx function
538
- const reqrespSubProtocolValidators = {
539
- ...DEFAULT_SUB_PROTOCOL_VALIDATORS,
540
- [ReqRespSubProtocol.TX]: this.validateRequestedTxs.bind(this),
541
- [ReqRespSubProtocol.BLOCK_TXS]: this.validateRequestedBlockTxs.bind(this),
542
- [ReqRespSubProtocol.BLOCK]: this.validateRequestedBlock.bind(this),
543
- };
544
-
545
633
  await this.peerManager.initializePeers();
546
634
 
547
- await this.reqresp.start(requestResponseHandlers, reqrespSubProtocolValidators);
635
+ await this.reqresp.start(requestResponseHandlers);
548
636
 
549
637
  await this.node.start();
550
638
 
@@ -560,6 +648,38 @@ export class LibP2PService extends WithTracer implements P2PService {
560
648
  if (!this.config.p2pDiscoveryDisabled) {
561
649
  await this.peerDiscoveryService.start();
562
650
  }
651
+
652
+ // Bridge discv5 IP changes to libp2p's AddressManager so peers see the updated address
653
+ if (this.config.queryForIp) {
654
+ this.discoveredP2pIp = this.config.p2pIp;
655
+ this.logger.info('IP change tracking enabled, bridging discv5 IP updates to libp2p AddressManager');
656
+ this.ipChangedHandler = (ip: string) => {
657
+ const addressManager = this.node.services.components.addressManager;
658
+ const newAddr = multiaddr(convertToMultiaddr(ip, this.config.p2pPort, 'tcp'));
659
+ const previousIp = this.discoveredP2pIp;
660
+
661
+ if (previousIp) {
662
+ const oldAddr = multiaddr(convertToMultiaddr(previousIp, this.config.p2pPort, 'tcp'));
663
+ addressManager.removeObservedAddr(oldAddr);
664
+ this.logger.info('Libp2p announce address updated due to IP change', {
665
+ previousIp,
666
+ newIp: ip,
667
+ newMultiaddr: newAddr.toString(),
668
+ });
669
+ } else {
670
+ this.logger.info('Libp2p announce address set from initial discv5 IP discovery', {
671
+ ip,
672
+ multiaddr: newAddr.toString(),
673
+ });
674
+ }
675
+
676
+ addressManager.addObservedAddr(newAddr);
677
+ addressManager.confirmObservedAddr(newAddr);
678
+ this.discoveredP2pIp = ip;
679
+ };
680
+ this.peerDiscoveryService.on('ip:changed', this.ipChangedHandler);
681
+ }
682
+
563
683
  this.discoveryRunningPromise = new RunningPromise(
564
684
  async () => {
565
685
  await this.peerManager.heartbeat();
@@ -585,6 +705,11 @@ export class LibP2PService extends WithTracer implements P2PService {
585
705
  // Remove gossip sub listener
586
706
  this.node.services.pubsub.removeEventListener(GossipSubEvent.MESSAGE, this.gossipSubEventHandler);
587
707
 
708
+ if (this.ipChangedHandler) {
709
+ this.peerDiscoveryService.removeListener('ip:changed', this.ipChangedHandler);
710
+ this.ipChangedHandler = undefined;
711
+ }
712
+
588
713
  // Stop peer manager
589
714
  this.logger.debug('Stopping peer manager...');
590
715
  await this.peerManager.stop();
@@ -599,12 +724,8 @@ export class LibP2PService extends WithTracer implements P2PService {
599
724
  this.logger.info('LibP2P service stopped');
600
725
  }
601
726
 
602
- addReqRespSubProtocol(
603
- subProtocol: ReqRespSubProtocol,
604
- handler: ReqRespSubProtocolHandler,
605
- validator?: ReqRespSubProtocolValidators[ReqRespSubProtocol],
606
- ): Promise<void> {
607
- return this.reqresp.addSubProtocol(subProtocol, handler, validator);
727
+ addReqRespSubProtocol(subProtocol: ReqRespSubProtocol, handler: ReqRespSubProtocolHandler): Promise<void> {
728
+ return this.reqresp.addSubProtocol(subProtocol, handler);
608
729
  }
609
730
 
610
731
  public registerThisValidatorAddresses(address: EthAddress[]): void {
@@ -615,6 +736,11 @@ export class LibP2PService extends WithTracer implements P2PService {
615
736
  return this.peerManager.getPeers(includePending);
616
737
  }
617
738
 
739
+ public getP2PConnectivity(): P2PConnectivity {
740
+ const connectedPeers = this.peerManager.getPeers().filter(peer => peer.status === 'connected').length;
741
+ return { enabled: true, connectedPeers };
742
+ }
743
+
618
744
  public getGossipMeshPeerCount(topicType: TopicType): number {
619
745
  return this.node.services.pubsub.getMeshPeers(this.topicStrings[topicType]).length;
620
746
  }
@@ -632,20 +758,6 @@ export class LibP2PService extends WithTracer implements P2PService {
632
758
  setImmediate(() => void safeJob());
633
759
  }
634
760
 
635
- /**
636
- * Send a batch of requests to peers, and return the responses
637
- * @param protocol - The request response protocol to use
638
- * @param requests - The requests to send to the peers
639
- * @returns The responses to the requests
640
- */
641
- sendBatchRequest<SubProtocol extends ReqRespSubProtocol>(
642
- protocol: SubProtocol,
643
- requests: InstanceType<SubProtocolMap[SubProtocol]['request']>[],
644
- pinnedPeerId: PeerId | undefined,
645
- ): Promise<InstanceType<SubProtocolMap[SubProtocol]['response']>[]> {
646
- return this.reqresp.sendBatchRequest(protocol, requests, pinnedPeerId);
647
- }
648
-
649
761
  public sendRequestToPeer(
650
762
  peerId: PeerId,
651
763
  subProtocol: ReqRespSubProtocol,
@@ -667,8 +779,12 @@ export class LibP2PService extends WithTracer implements P2PService {
667
779
  this.blockReceivedCallback = callback;
668
780
  }
669
781
 
670
- public registerCheckpointReceivedCallback(callback: P2PCheckpointReceivedCallback) {
671
- this.checkpointReceivedCallback = callback;
782
+ public registerValidatorCheckpointReceivedCallback(callback: P2PCheckpointReceivedCallback) {
783
+ this.validatorCheckpointReceivedCallback = callback;
784
+ }
785
+
786
+ public registerAllNodesCheckpointReceivedCallback(callback: P2PCheckpointReceivedCallback) {
787
+ this.allNodesCheckpointReceivedCallback = callback;
672
788
  }
673
789
 
674
790
  /**
@@ -681,6 +797,13 @@ export class LibP2PService extends WithTracer implements P2PService {
681
797
  this.duplicateProposalCallback = callback;
682
798
  }
683
799
 
800
+ /**
801
+ * Registers a callback to be invoked when an oversized block proposal is stored as slashing evidence.
802
+ */
803
+ public registerOversizedProposalCallback(callback: P2POversizedProposalCallback): void {
804
+ this.oversizedProposalCallback = callback;
805
+ }
806
+
684
807
  /**
685
808
  * Registers a callback to be invoked when a duplicate attestation is detected.
686
809
  * A validator signing attestations for different proposals at the same slot.
@@ -690,6 +813,10 @@ export class LibP2PService extends WithTracer implements P2PService {
690
813
  this.duplicateAttestationCallback = callback;
691
814
  }
692
815
 
816
+ public registerCheckpointAttestationCallback(callback: P2PCheckpointAttestationCallback): void {
817
+ this.checkpointAttestationCallback = callback;
818
+ }
819
+
693
820
  /**
694
821
  * Subscribes to a topic.
695
822
  * @param topic - The topic to subscribe to.
@@ -754,6 +881,9 @@ export class LibP2PService extends WithTracer implements P2PService {
754
881
  if (!validator || !validator.addMessage(msgId)) {
755
882
  this.instrumentation.incMessagePrevalidationStatus(false, topicType);
756
883
  this.node.services.pubsub.reportMessageValidationResult(msgId, source.toString(), TopicValidatorResult.Ignore);
884
+ if (topicType === TopicType.tx) {
885
+ this.logger.verbose(`Ignoring already-seen tx gossip message`, { msgId, source: source.toString() });
886
+ }
757
887
  return { result: false, topicType };
758
888
  }
759
889
 
@@ -815,6 +945,15 @@ export class LibP2PService extends WithTracer implements P2PService {
815
945
 
816
946
  // Process the message, optionally within a linked span for trace propagation
817
947
  const processMessage = async () => {
948
+ if (
949
+ this.config.skipIncomingProposals &&
950
+ (msg.topic === this.topicStrings[TopicType.block_proposal] ||
951
+ msg.topic === this.topicStrings[TopicType.checkpoint_proposal])
952
+ ) {
953
+ this.logger.warn(`Ignoring incoming proposal (skipIncomingProposals is set)`, { topic: msg.topic });
954
+ this.node.services.pubsub.reportMessageValidationResult(msgId, source.toString(), TopicValidatorResult.Ignore);
955
+ return;
956
+ }
818
957
  if (msg.topic === this.topicStrings[TopicType.tx]) {
819
958
  await this.handleGossipedTx(p2pMessage.payload, msgId, source);
820
959
  } else if (msg.topic === this.topicStrings[TopicType.checkpoint_attestation]) {
@@ -879,38 +1018,102 @@ export class LibP2PService extends WithTracer implements P2PService {
879
1018
  msgId: string,
880
1019
  source: PeerId,
881
1020
  topicType: TopicType,
1021
+ stageTimings?: Record<string, number>,
882
1022
  ): Promise<ReceivedMessageValidationResult<T, M>> {
883
- let resultAndObj: ReceivedMessageValidationResult<T, M> = { result: TopicValidatorResult.Reject };
1023
+ // Default to reject result with a penalty if validation function throws an error
1024
+ let resultAndObj: ReceivedMessageValidationResult<T, M> = {
1025
+ result: TopicValidatorResult.Reject,
1026
+ severity: PeerErrorSeverity.MidToleranceError,
1027
+ };
884
1028
  const timer = new Timer();
885
1029
  try {
886
1030
  resultAndObj = await validationFunc();
887
1031
  } catch (err) {
888
- this.peerManager.penalizePeer(source, PeerErrorSeverity.LowToleranceError);
889
- this.logger.error(`Error deserializing and validating gossipsub message`, err, {
1032
+ this.logger.error(`Error validating gossipsub message`, err, { msgId, source: source.toString(), topicType });
1033
+ }
1034
+
1035
+ const validationTimeMs = timer.ms();
1036
+ const mcacheWindowMs = this.config.gossipsubMcacheLength * this.config.gossipsubInterval;
1037
+ if (validationTimeMs > mcacheWindowMs * 0.75) {
1038
+ this.instrumentation.incSlowValidation(topicType);
1039
+ this.logger.warn(
1040
+ `Gossip validation for ${topicType} took ${validationTimeMs}ms, approaching mcache eviction window of ${mcacheWindowMs}ms. ` +
1041
+ `Message forwarding may be skipped if validation exceeds the window.`,
1042
+ { msgId, source: source.toString(), topicType, validationTimeMs, mcacheWindowMs, stageTimings },
1043
+ );
1044
+ }
1045
+
1046
+ if (resultAndObj.result === TopicValidatorResult.Accept) {
1047
+ this.logger.debug(`Message ${topicType} accepted by validator`, {
890
1048
  msgId,
891
1049
  source: source.toString(),
892
1050
  topicType,
1051
+ validationTimeMs,
1052
+ stageTimings,
893
1053
  });
894
- }
895
-
896
- if (resultAndObj.result === TopicValidatorResult.Accept) {
897
1054
  this.instrumentation.recordMessageValidation(topicType, timer);
1055
+ } else if (resultAndObj.result === TopicValidatorResult.Reject) {
1056
+ this.logger.warn(`Message ${topicType} rejected by validator with severity ${resultAndObj.severity}`, {
1057
+ msgId,
1058
+ source: source.toString(),
1059
+ topicType,
1060
+ severity: resultAndObj.severity,
1061
+ });
1062
+ this.peerManager.penalizePeer(source, resultAndObj.severity);
1063
+ } else {
1064
+ this.logger.trace(`Message ${topicType} ignored by validator`, { msgId, source: source.toString(), topicType });
898
1065
  }
899
1066
 
900
1067
  this.node.services.pubsub.reportMessageValidationResult(msgId, source.toString(), resultAndObj.result);
901
1068
  return resultAndObj;
902
1069
  }
903
1070
 
1071
+ private tryDeserialize<T>(deserializeFunc: () => T, msgId: string, source: PeerId): T | undefined {
1072
+ try {
1073
+ return deserializeFunc();
1074
+ } catch (err) {
1075
+ this.logger.warn(`Failed to deserialize gossipsub message from buffer`, {
1076
+ err,
1077
+ msgId,
1078
+ source: source.toString(),
1079
+ });
1080
+ return undefined;
1081
+ }
1082
+ }
1083
+
904
1084
  protected async handleGossipedTx(payloadData: Buffer, msgId: string, source: PeerId) {
1085
+ // Per-stage timings so slow validations can be attributed to a specific stage (see A-1656).
1086
+ const stageTimings: Record<string, number> = {};
1087
+ const timed = async <T>(stage: string, fn: () => T | Promise<T>): Promise<T> => {
1088
+ const timer = new Timer();
1089
+ try {
1090
+ return await fn();
1091
+ } finally {
1092
+ const ms = timer.ms();
1093
+ stageTimings[stage] = Math.ceil(ms);
1094
+ this.instrumentation.recordTxValidationStage(stage, ms);
1095
+ }
1096
+ };
1097
+
905
1098
  const validationFunc: () => Promise<ReceivedMessageValidationResult<Tx>> = async () => {
906
- const tx = Tx.fromBuffer(payloadData);
1099
+ const tx = await timed('deserialize', () => this.tryDeserialize(() => Tx.fromBuffer(payloadData), msgId, source));
1100
+ if (!tx) {
1101
+ return { result: TopicValidatorResult.Reject, severity: PeerErrorSeverity.LowToleranceError };
1102
+ }
907
1103
 
908
- const currentBlockNumber = await this.archiver.getBlockNumber();
909
- const { ts: nextSlotTimestamp } = this.epochCache.getEpochAndSlotInNextL1Slot();
1104
+ // Stage 1 setup: chain tip, epoch info, gas fees, and L1 constants reads
1105
+ const { currentBlockNumber, firstStageValidators } = await timed('fast_validation_setup', async () => {
1106
+ const currentBlockNumber = await this.archiver.getBlockNumber();
1107
+ const { ts: nextSlotTimestamp } = this.epochCache.getEpochAndSlotInNextL1Slot();
1108
+ const firstStageValidators = await this.createFirstStageMessageValidators(
1109
+ currentBlockNumber,
1110
+ nextSlotTimestamp,
1111
+ );
1112
+ return { currentBlockNumber, firstStageValidators };
1113
+ });
910
1114
 
911
1115
  // Stage 1: fast validators (metadata, data, timestamps, double-spend, gas, phases, block header)
912
- const firstStageValidators = await this.createFirstStageMessageValidators(currentBlockNumber, nextSlotTimestamp);
913
- const firstStageOutcome = await this.runValidations(tx, firstStageValidators);
1116
+ const firstStageOutcome = await timed('fast_validation', () => this.runValidations(tx, firstStageValidators));
914
1117
  if (!firstStageOutcome.allPassed) {
915
1118
  const { name } = firstStageOutcome.failure;
916
1119
  let { severity } = firstStageOutcome.failure;
@@ -923,33 +1126,44 @@ export class LibP2PService extends WithTracer implements P2PService {
923
1126
  severity = await this.handleDoubleSpendFailure(tx, txBlockNumber);
924
1127
  }
925
1128
 
926
- this.peerManager.penalizePeer(source, severity);
927
- return { result: TopicValidatorResult.Reject };
1129
+ this.logger.verbose(`Rejecting gossiped tx ${tx.getTxHash().toString()}: stage 1 validation failed`, {
1130
+ validator: name,
1131
+ severity,
1132
+ source: source.toString(),
1133
+ });
1134
+ return { result: TopicValidatorResult.Reject, severity };
928
1135
  }
929
1136
 
930
1137
  // Pool pre-check: see if the pool would accept this tx before doing expensive proof verification
931
- const canAdd = await this.mempools.txPool.canAddPendingTx(tx);
1138
+ const canAdd = await timed('pool_precheck', () => this.mempools.txPool.canAddPendingTx(tx));
932
1139
  if (canAdd === 'ignored') {
1140
+ this.logger.verbose(`Ignoring gossiped tx ${tx.getTxHash().toString()}: pool pre-check returned ignored`, {
1141
+ source: source.toString(),
1142
+ });
933
1143
  return { result: TopicValidatorResult.Ignore, obj: tx };
934
1144
  }
935
1145
 
936
1146
  // Stage 2: expensive proof verification
937
1147
  const secondStageValidators = this.createSecondStageMessageValidators();
938
- const secondStageOutcome = await this.runValidations(tx, secondStageValidators);
1148
+ const secondStageOutcome = await timed('proof_verify', () => this.runValidations(tx, secondStageValidators));
939
1149
  if (!secondStageOutcome.allPassed) {
940
- const { severity } = secondStageOutcome.failure;
941
- this.peerManager.penalizePeer(source, severity);
942
- return { result: TopicValidatorResult.Reject };
1150
+ const { severity, name } = secondStageOutcome.failure;
1151
+ this.logger.verbose(`Rejecting gossiped tx ${tx.getTxHash().toString()}: stage 2 validation failed`, {
1152
+ validator: name,
1153
+ severity,
1154
+ source: source.toString(),
1155
+ });
1156
+ return { result: TopicValidatorResult.Reject, severity };
943
1157
  }
944
1158
 
945
1159
  // Pool add: persist the tx
946
1160
  const txHash = tx.getTxHash();
947
- const addResult = await this.mempools.txPool.addPendingTxs([tx], { source: 'gossip' });
1161
+ const addResult = await timed('pool_add', () => this.mempools.txPool.addPendingTxs([tx], { source: 'gossip' }));
948
1162
 
949
1163
  const wasAccepted = addResult.accepted.some(h => h.equals(txHash));
950
1164
  const wasIgnored = addResult.ignored.some(h => h.equals(txHash));
951
1165
 
952
- this.logger.trace(`Validate propagated tx`, {
1166
+ this.logger.verbose(`Validate propagated tx ${txHash.toString()}`, {
953
1167
  wasAccepted,
954
1168
  wasIgnored,
955
1169
  [Attributes.P2P_ID]: source.toString(),
@@ -960,11 +1174,21 @@ export class LibP2PService extends WithTracer implements P2PService {
960
1174
  } else if (wasIgnored) {
961
1175
  return { result: TopicValidatorResult.Ignore, obj: tx };
962
1176
  } else {
963
- return { result: TopicValidatorResult.Reject };
1177
+ this.logger.warn(`Gossiped tx ${txHash.toString()} unexpectedly rejected by pool`, {
1178
+ source: source.toString(),
1179
+ txHash: txHash.toString(),
1180
+ });
1181
+ return { result: TopicValidatorResult.Reject, severity: PeerErrorSeverity.HighToleranceError };
964
1182
  }
965
1183
  };
966
1184
 
967
- const { result, obj: tx } = await this.validateReceivedMessage<Tx>(validationFunc, msgId, source, TopicType.tx);
1185
+ const { result, obj: tx } = await this.validateReceivedMessage<Tx>(
1186
+ validationFunc,
1187
+ msgId,
1188
+ source,
1189
+ TopicType.tx,
1190
+ stageTimings,
1191
+ );
968
1192
  if (result !== TopicValidatorResult.Accept || !tx) {
969
1193
  return;
970
1194
  }
@@ -990,7 +1214,16 @@ export class LibP2PService extends WithTracer implements P2PService {
990
1214
  source: PeerId,
991
1215
  ): Promise<void> {
992
1216
  const { result, obj: attestation } = await this.validateReceivedMessage<CheckpointAttestation>(
993
- () => this.validateAndStoreCheckpointAttestation(source, CheckpointAttestation.fromBuffer(payloadData)),
1217
+ () => {
1218
+ const attestation = this.tryDeserialize(() => CheckpointAttestation.fromBuffer(payloadData), msgId, source);
1219
+ if (!attestation) {
1220
+ return Promise.resolve({
1221
+ result: TopicValidatorResult.Reject,
1222
+ severity: PeerErrorSeverity.LowToleranceError,
1223
+ });
1224
+ }
1225
+ return this.validateAndStoreCheckpointAttestation(source, attestation);
1226
+ },
994
1227
  msgId,
995
1228
  source,
996
1229
  TopicType.checkpoint_attestation,
@@ -1023,8 +1256,7 @@ export class LibP2PService extends WithTracer implements P2PService {
1023
1256
 
1024
1257
  if (validationResult.result === 'reject') {
1025
1258
  this.logger.warn(`Penalizing peer ${peerId} for checkpoint attestation validation failure`);
1026
- this.peerManager.penalizePeer(peerId, validationResult.severity);
1027
- return { result: TopicValidatorResult.Reject };
1259
+ return { result: TopicValidatorResult.Reject, severity: validationResult.severity };
1028
1260
  }
1029
1261
 
1030
1262
  if (validationResult.result === 'ignore') {
@@ -1050,16 +1282,16 @@ export class LibP2PService extends WithTracer implements P2PService {
1050
1282
  return { result: TopicValidatorResult.Ignore, obj: attestation };
1051
1283
  }
1052
1284
 
1053
- // Could not add (cap reached for signer), no need to re-broadcast
1285
+ // Could not add (cap reached for signer), penalize and do not re-broadcast
1054
1286
  if (!added) {
1055
- this.logger.warn(`Dropping checkpoint attestation due to cap`, {
1287
+ this.logger.warn(`Rejecting checkpoint attestation due to cap`, {
1056
1288
  slot: slot.toString(),
1057
1289
  archive: attestation.archive.toString(),
1058
1290
  source: peerId.toString(),
1059
1291
  attester: attestation.getSender()?.toString(),
1060
1292
  count,
1061
1293
  });
1062
- return { result: TopicValidatorResult.Ignore, obj: attestation };
1294
+ return { result: TopicValidatorResult.Reject, severity: PeerErrorSeverity.HighToleranceError };
1063
1295
  }
1064
1296
 
1065
1297
  // Check if this is a duplicate attestation (signer attested to a different proposal at the same slot)
@@ -1078,6 +1310,7 @@ export class LibP2PService extends WithTracer implements P2PService {
1078
1310
  }
1079
1311
 
1080
1312
  // Attestation was added successfully - accept it so other nodes can also detect the equivocation
1313
+ this.checkpointAttestationCallback?.(attestation);
1081
1314
  return { result: TopicValidatorResult.Accept, obj: attestation };
1082
1315
  }
1083
1316
 
@@ -1085,20 +1318,21 @@ export class LibP2PService extends WithTracer implements P2PService {
1085
1318
  const {
1086
1319
  result,
1087
1320
  obj: block,
1088
- metadata: { isEquivocated } = {},
1089
- } = await this.validateReceivedMessage<BlockProposal, { isEquivocated: boolean }>(
1321
+ metadata: { isEquivocated, isOversized } = {},
1322
+ } = await this.validateReceivedMessage<BlockProposal, { isEquivocated: boolean; isOversized: boolean }>(
1090
1323
  () => this.validateAndStoreBlockProposal(source, BlockProposal.fromBuffer(payloadData)),
1091
1324
  msgId,
1092
1325
  source,
1093
1326
  TopicType.block_proposal,
1094
1327
  );
1095
1328
 
1096
- // If not accepted or equivocated, return
1097
- if (result !== TopicValidatorResult.Accept || !block || isEquivocated) {
1329
+ // If not accepted, equivocated, or oversized, return. Oversized proposals are re-broadcast as
1330
+ // slashing evidence but never attested or processed.
1331
+ if (result !== TopicValidatorResult.Accept || !block || isEquivocated || isOversized) {
1098
1332
  return;
1099
1333
  }
1100
1334
 
1101
- await this.processValidBlockProposal(block, source);
1335
+ await this.processValidBlockProposal(ValidatedBlockProposal(block), source);
1102
1336
  }
1103
1337
 
1104
1338
  /** Validates a block proposal. Triggers a penalization to the peer that sent it if invalid. Adds to the mempool if valid. */
@@ -1109,13 +1343,12 @@ export class LibP2PService extends WithTracer implements P2PService {
1109
1343
  protected async validateAndStoreBlockProposal(
1110
1344
  peerId: PeerId,
1111
1345
  block: BlockProposal,
1112
- ): Promise<ReceivedMessageValidationResult<BlockProposal, { isEquivocated: boolean }>> {
1346
+ ): Promise<ReceivedMessageValidationResult<BlockProposal, { isEquivocated: boolean; isOversized: boolean }>> {
1113
1347
  const validationResult = await this.blockProposalValidator.validate(block);
1114
1348
 
1115
1349
  if (validationResult.result === 'reject') {
1116
1350
  this.logger.warn(`Penalizing peer ${peerId} for block proposal validation failure`);
1117
- this.peerManager.penalizePeer(peerId, validationResult.severity);
1118
- return { result: TopicValidatorResult.Reject };
1351
+ return { result: TopicValidatorResult.Reject, severity: validationResult.severity };
1119
1352
  }
1120
1353
 
1121
1354
  if (validationResult.result === 'ignore') {
@@ -1125,6 +1358,12 @@ export class LibP2PService extends WithTracer implements P2PService {
1125
1358
  // Try to add the proposal: this handles existence check, cap check, and adding in one call
1126
1359
  const { added, alreadyExists, count } = await this.mempools.attestationPool.tryAddBlockProposal(block);
1127
1360
  const isEquivocated = count !== undefined && count > 1;
1361
+ // An oversized proposal (index at or beyond the consensus per-checkpoint limit) is structurally valid
1362
+ // proposer misbehavior: it is stored and re-broadcast as slashing evidence but never processed or
1363
+ // attested to. No-ops when maxBlocksPerCheckpoint is unset (local/test).
1364
+ const isOversized =
1365
+ this.config.maxBlocksPerCheckpoint !== undefined &&
1366
+ block.indexWithinCheckpoint >= this.config.maxBlocksPerCheckpoint;
1128
1367
 
1129
1368
  // Duplicate proposal received, no need to re-broadcast
1130
1369
  if (alreadyExists) {
@@ -1134,12 +1373,11 @@ export class LibP2PService extends WithTracer implements P2PService {
1134
1373
  proposer: block.getSender()?.toString(),
1135
1374
  source: peerId.toString(),
1136
1375
  });
1137
- return { result: TopicValidatorResult.Ignore, obj: block, metadata: { isEquivocated } };
1376
+ return { result: TopicValidatorResult.Ignore, obj: block, metadata: { isEquivocated, isOversized } };
1138
1377
  }
1139
1378
 
1140
1379
  // Too many blocks received for this slot and index, penalize peer and do not re-broadcast
1141
1380
  if (!added) {
1142
- this.peerManager.penalizePeer(peerId, PeerErrorSeverity.HighToleranceError);
1143
1381
  this.logger.warn(`Penalizing peer for block proposal exceeding per-position cap`, {
1144
1382
  ...block.toBlockInfo(),
1145
1383
  indexWithinCheckpoint: block.indexWithinCheckpoint,
@@ -1147,7 +1385,27 @@ export class LibP2PService extends WithTracer implements P2PService {
1147
1385
  proposer: block.getSender()?.toString(),
1148
1386
  source: peerId.toString(),
1149
1387
  });
1150
- return { result: TopicValidatorResult.Reject, metadata: { isEquivocated } };
1388
+ return {
1389
+ result: TopicValidatorResult.Reject,
1390
+ metadata: { isEquivocated, isOversized },
1391
+ severity: PeerErrorSeverity.HighToleranceError,
1392
+ };
1393
+ }
1394
+
1395
+ // The proposal was stored: if oversized, invoke the oversized callback so the proposer can be
1396
+ // slashed. Fired alongside (not instead of) equivocation detection below.
1397
+ if (isOversized) {
1398
+ const proposer = block.getSender();
1399
+ if (proposer) {
1400
+ this.logger.warn(`Detected oversized block proposal at slot ${block.slotNumber}`, {
1401
+ ...block.toBlockInfo(),
1402
+ indexWithinCheckpoint: block.indexWithinCheckpoint,
1403
+ maxBlocksPerCheckpoint: this.config.maxBlocksPerCheckpoint,
1404
+ source: peerId.toString(),
1405
+ proposer: proposer.toString(),
1406
+ });
1407
+ this.oversizedProposalCallback?.({ slot: block.slotNumber, proposer });
1408
+ }
1151
1409
  }
1152
1410
 
1153
1411
  // If this was a duplicate proposal, do not process it, but do invoke the duplicate callback,
@@ -1163,11 +1421,11 @@ export class LibP2PService extends WithTracer implements P2PService {
1163
1421
  if (proposer && count === 2) {
1164
1422
  this.duplicateProposalCallback?.({ slot: block.slotNumber, proposer, type: 'block' });
1165
1423
  }
1166
- return { result: TopicValidatorResult.Accept, obj: block, metadata: { isEquivocated } };
1424
+ return { result: TopicValidatorResult.Accept, obj: block, metadata: { isEquivocated, isOversized } };
1167
1425
  }
1168
1426
 
1169
1427
  // Otherwise, we're good to go!
1170
- return { result: TopicValidatorResult.Accept, obj: block };
1428
+ return { result: TopicValidatorResult.Accept, obj: block, metadata: { isEquivocated: false, isOversized } };
1171
1429
  }
1172
1430
 
1173
1431
  // REFACTOR(palla): This method should be moved to the p2p_client or to a separate component,
@@ -1177,7 +1435,7 @@ export class LibP2PService extends WithTracer implements P2PService {
1177
1435
  [Attributes.BLOCK_ARCHIVE]: block.archive.toString(),
1178
1436
  [Attributes.P2P_ID]: await block.p2pMessageLoggingIdentifier().then(i => i.toString()),
1179
1437
  }))
1180
- protected async processValidBlockProposal(block: BlockProposal, sender: PeerId) {
1438
+ protected async processValidBlockProposal(block: ValidatedBlockProposal, sender: PeerId) {
1181
1439
  const slot = block.slotNumber;
1182
1440
  this.logger.verbose(`Received block proposal for slot ${slot} from external peer ${sender.toString()}.`, {
1183
1441
  p2pMessageIdentifier: await block.p2pMessageLoggingIdentifier(),
@@ -1188,11 +1446,29 @@ export class LibP2PService extends WithTracer implements P2PService {
1188
1446
  // Mark the txs in this proposal as protected
1189
1447
  await this.mempools.txPool.protectTxs(block.txHashes, block.blockHeader);
1190
1448
 
1191
- // Call the block received callback to validate the proposal.
1192
- // Note: Validators do NOT attest to individual blocks, only to checkpoint proposals.
1193
- const isValid = await this.blockReceivedCallback(block, sender);
1194
- if (!isValid) {
1195
- this.logger.warn(`Block proposal validation failed for block ${block.blockNumber}`, block.toBlockInfo());
1449
+ if (!(await this.tryBlockReceivedCallback(block, sender))) {
1450
+ // Release the protections this proposal created so its txs return to pending. Only entries still
1451
+ // keyed to this slot are cleared, so a tx referenced by a live proposal at another slot stays protected.
1452
+ await this.mempools.txPool.unprotectTxs(block.txHashes, slot);
1453
+ }
1454
+ }
1455
+
1456
+ /**
1457
+ * Runs the block received callback to validate a proposal, and returns whether it was accepted.
1458
+ * A callback that throws is reported as a rejection: the proposal is no more usable than one explicitly
1459
+ * rejected, and letting the error escape would leave the proposal's tx protections in place.
1460
+ * Note: Validators do NOT attest to individual blocks, only to checkpoint proposals.
1461
+ */
1462
+ private async tryBlockReceivedCallback(block: ValidatedBlockProposal, sender: PeerId): Promise<boolean> {
1463
+ try {
1464
+ const isValid = await this.blockReceivedCallback(block, sender);
1465
+ if (!isValid) {
1466
+ this.logger.info(`Block proposal validation failed for block ${block.blockNumber}`, block.toBlockInfo());
1467
+ }
1468
+ return isValid;
1469
+ } catch (err) {
1470
+ this.logger.error(`Error validating block proposal for block ${block.blockNumber}`, err, block.toBlockInfo());
1471
+ return false;
1196
1472
  }
1197
1473
  }
1198
1474
 
@@ -1204,25 +1480,45 @@ export class LibP2PService extends WithTracer implements P2PService {
1204
1480
  const {
1205
1481
  result,
1206
1482
  obj: checkpoint,
1207
- metadata: { isEquivocated, processBlock } = {},
1208
- } = await this.validateReceivedMessage<CheckpointProposal, { isEquivocated: boolean; processBlock: boolean }>(
1483
+ metadata: { isEquivocated, processBlock, isOversized } = {},
1484
+ } = await this.validateReceivedMessage<
1485
+ CheckpointProposal,
1486
+ { isEquivocated: boolean; processBlock: boolean; isOversized: boolean }
1487
+ >(
1209
1488
  () => this.validateAndStoreCheckpointProposal(source, CheckpointProposal.fromBuffer(payloadData)),
1210
1489
  msgId,
1211
1490
  source,
1212
1491
  TopicType.checkpoint_proposal,
1213
1492
  );
1214
1493
 
1494
+ // An oversized checkpoint is re-broadcast as slashing evidence but never attested or processed.
1495
+ // Process checkpoint proposal if valid and neither equivocated nor oversized.
1496
+ const processCheckpointFn = () =>
1497
+ result === TopicValidatorResult.Accept && checkpoint && !isEquivocated && !isOversized
1498
+ ? this.processValidCheckpointProposal(ValidatedCheckpointProposalCore(checkpoint.toCore()), source)
1499
+ : Promise.resolve();
1500
+
1215
1501
  // If the checkpoint contained a valid last block, we process it even if the checkpoint itself is to be rejected
1216
1502
  // TODO(palla/mbps): Is this ok? Should we be considering a block from a checkpoint that was equivocated?
1217
- if (processBlock && checkpoint?.getBlockProposal()) {
1218
- await this.processValidBlockProposal(checkpoint.getBlockProposal()!, source);
1219
- }
1220
-
1221
- if (result !== TopicValidatorResult.Accept || !checkpoint || isEquivocated) {
1503
+ const processBlockFn = () =>
1504
+ processBlock && checkpoint && checkpoint.getBlockProposal()
1505
+ ? this.processValidBlockProposal(ValidatedBlockProposal(checkpoint.getBlockProposal()!), source)
1506
+ : Promise.resolve();
1507
+
1508
+ // A node that skips checkpoint validation attests without re-executing the embedded last block, so run
1509
+ // the checkpoint callback first: this creates and broadcasts the attestation before the block is
1510
+ // processed. Otherwise the block's re-execution — which can stall until the re-execution deadline
1511
+ // waiting for a parent that may never arrive — would delay the attestation past the slot's attestation
1512
+ // window, after which peers reject it as stale.
1513
+ if (this.config.skipCheckpointProposalValidation) {
1514
+ await processCheckpointFn();
1515
+ await processBlockFn();
1222
1516
  return;
1223
1517
  }
1224
1518
 
1225
- await this.processValidCheckpointProposal(checkpoint.toCore(), source);
1519
+ // Process the block first, since it's required for the checkpoint proposal validation.
1520
+ await processBlockFn();
1521
+ await processCheckpointFn();
1226
1522
  }
1227
1523
 
1228
1524
  /**
@@ -1235,13 +1531,17 @@ export class LibP2PService extends WithTracer implements P2PService {
1235
1531
  protected async validateAndStoreCheckpointProposal(
1236
1532
  peerId: PeerId,
1237
1533
  checkpoint: CheckpointProposal,
1238
- ): Promise<ReceivedMessageValidationResult<CheckpointProposal, { isEquivocated: boolean; processBlock: boolean }>> {
1534
+ ): Promise<
1535
+ ReceivedMessageValidationResult<
1536
+ CheckpointProposal,
1537
+ { isEquivocated: boolean; processBlock: boolean; isOversized: boolean }
1538
+ >
1539
+ > {
1239
1540
  const validationResult = await this.checkpointProposalValidator.validate(checkpoint);
1240
1541
 
1241
1542
  if (validationResult.result === 'reject') {
1242
1543
  this.logger.warn(`Penalizing peer ${peerId} for checkpoint proposal validation failure`);
1243
- this.peerManager.penalizePeer(peerId, validationResult.severity);
1244
- return { result: TopicValidatorResult.Reject };
1544
+ return { result: TopicValidatorResult.Reject, severity: validationResult.severity };
1245
1545
  }
1246
1546
 
1247
1547
  if (validationResult.result === 'ignore') {
@@ -1251,25 +1551,30 @@ export class LibP2PService extends WithTracer implements P2PService {
1251
1551
  // Extract and try to add the block proposal first if present
1252
1552
  const blockProposal = checkpoint.getBlockProposal();
1253
1553
  let processBlock = false;
1554
+ let isOversized = false;
1254
1555
  if (blockProposal) {
1255
1556
  this.logger.debug(`Validating block proposal from propagated checkpoint`, {
1256
1557
  [Attributes.SLOT_NUMBER]: checkpoint.slotNumber.toString(),
1257
1558
  [Attributes.P2P_ID]: peerId.toString(),
1258
1559
  });
1259
- const {
1260
- result,
1261
- obj,
1262
- metadata: { isEquivocated } = {},
1263
- } = await this.validateAndStoreBlockProposal(peerId, blockProposal);
1264
- if (result === TopicValidatorResult.Reject || !obj || isEquivocated) {
1560
+ const blockProposalResult = await this.validateAndStoreBlockProposal(peerId, blockProposal);
1561
+ const { obj, metadata: { isEquivocated, isOversized: blockIsOversized } = {} } = blockProposalResult;
1562
+ isOversized = blockIsOversized ?? false;
1563
+
1564
+ if (blockProposalResult.result === TopicValidatorResult.Reject || !obj || isEquivocated) {
1265
1565
  this.logger.debug(`Rejecting checkpoint due to invalid last block proposal`, {
1266
1566
  [Attributes.SLOT_NUMBER]: checkpoint.slotNumber.toString(),
1267
1567
  [Attributes.P2P_ID]: peerId.toString(),
1268
1568
  isEquivocated,
1269
- result,
1569
+ result: blockProposalResult.result,
1270
1570
  });
1271
- return { result: TopicValidatorResult.Reject };
1272
- } else if (result === TopicValidatorResult.Accept && obj && !isEquivocated) {
1571
+ return {
1572
+ result: TopicValidatorResult.Reject,
1573
+ severity:
1574
+ 'severity' in blockProposalResult ? blockProposalResult.severity : PeerErrorSeverity.MidToleranceError,
1575
+ };
1576
+ } else if (blockProposalResult.result === TopicValidatorResult.Accept && obj && !isEquivocated && !isOversized) {
1577
+ // An oversized terminal block is re-broadcast as slashing evidence but never processed.
1273
1578
  processBlock = true;
1274
1579
  }
1275
1580
  }
@@ -1289,20 +1594,24 @@ export class LibP2PService extends WithTracer implements P2PService {
1289
1594
  return {
1290
1595
  result: TopicValidatorResult.Ignore,
1291
1596
  obj: checkpoint,
1292
- metadata: { isEquivocated, processBlock },
1597
+ metadata: { isEquivocated, processBlock, isOversized },
1293
1598
  };
1294
1599
  }
1295
1600
 
1296
- // Too many checkpoint proposals received for this slot, penalize peer and do not re-broadcast
1601
+ // Too many checkpoint proposals received for this slot, penalize peer and do not re-broadcast.
1297
1602
  // Note: We still return the checkpoint obj so the lastBlock can be processed if valid
1298
1603
  if (!added) {
1299
- this.peerManager.penalizePeer(peerId, PeerErrorSeverity.HighToleranceError);
1300
1604
  this.logger.warn(`Penalizing peer for checkpoint proposal exceeding per-slot cap`, {
1301
1605
  ...checkpoint.toCheckpointInfo(),
1302
1606
  count,
1303
1607
  source: peerId.toString(),
1304
1608
  });
1305
- return { result: TopicValidatorResult.Reject, obj: checkpoint, metadata: { isEquivocated, processBlock } };
1609
+ return {
1610
+ result: TopicValidatorResult.Reject,
1611
+ obj: checkpoint,
1612
+ metadata: { isEquivocated, processBlock, isOversized },
1613
+ severity: PeerErrorSeverity.HighToleranceError,
1614
+ };
1306
1615
  }
1307
1616
 
1308
1617
  // If this was a duplicate proposal, do not process it, but do invoke the duplicate callback,
@@ -1321,12 +1630,16 @@ export class LibP2PService extends WithTracer implements P2PService {
1321
1630
  return {
1322
1631
  result: TopicValidatorResult.Accept,
1323
1632
  obj: checkpoint,
1324
- metadata: { isEquivocated, processBlock },
1633
+ metadata: { isEquivocated, processBlock, isOversized },
1325
1634
  };
1326
1635
  }
1327
1636
 
1328
1637
  // Otherwise, we're good to go!
1329
- return { result: TopicValidatorResult.Accept, obj: checkpoint, metadata: { processBlock, isEquivocated } };
1638
+ return {
1639
+ result: TopicValidatorResult.Accept,
1640
+ obj: checkpoint,
1641
+ metadata: { processBlock, isEquivocated, isOversized },
1642
+ };
1330
1643
  }
1331
1644
 
1332
1645
  /**
@@ -1338,7 +1651,7 @@ export class LibP2PService extends WithTracer implements P2PService {
1338
1651
  [Attributes.BLOCK_ARCHIVE]: checkpoint.archive.toString(),
1339
1652
  [Attributes.P2P_ID]: await checkpoint.p2pMessageLoggingIdentifier().then(i => i.toString()),
1340
1653
  }))
1341
- protected async processValidCheckpointProposal(checkpoint: CheckpointProposalCore, sender: PeerId) {
1654
+ protected async processValidCheckpointProposal(checkpoint: ValidatedCheckpointProposalCore, sender: PeerId) {
1342
1655
  const slot = checkpoint.slotNumber;
1343
1656
  this.logger.verbose(`Received checkpoint proposal for slot ${slot} from external peer ${sender.toString()}.`, {
1344
1657
  p2pMessageIdentifier: await checkpoint.p2pMessageLoggingIdentifier(),
@@ -1347,9 +1660,11 @@ export class LibP2PService extends WithTracer implements P2PService {
1347
1660
  source: sender.toString(),
1348
1661
  });
1349
1662
 
1663
+ await this.allNodesCheckpointReceivedCallback(checkpoint, sender);
1664
+
1350
1665
  // Call the checkpoint received callback with the core version (without lastBlock)
1351
1666
  // to validate and potentially generate attestations
1352
- const attestations = await this.checkpointReceivedCallback(checkpoint, sender);
1667
+ const attestations = await this.validatorCheckpointReceivedCallback(checkpoint, sender);
1353
1668
  if (attestations && attestations.length > 0) {
1354
1669
  // If the callback returned attestations, add them to the pool and propagate them
1355
1670
  await this.mempools.attestationPool.addOwnCheckpointAttestations(attestations);
@@ -1372,82 +1687,87 @@ export class LibP2PService extends WithTracer implements P2PService {
1372
1687
  }
1373
1688
 
1374
1689
  /**
1375
- * Validate the requested block transactions. Allow partial returns.
1690
+ * Validate the requested block transactions request-response consistency.
1691
+ * It does NOT validate the transactions themselves.
1376
1692
  * @param request - The block transactions request.
1377
1693
  * @param response - The block transactions response.
1378
1694
  * @param peerId - The ID of the peer that made the request.
1379
- * @returns True if the requested block transactions are valid, false otherwise.
1695
+ * @returns True if the request-response is consistent, false otherwise.
1380
1696
  */
1381
- @trackSpan('Libp2pService.validateRequestedBlockTxs', request => ({
1697
+ @trackSpan('Libp2pService.validateRequestedBlockTxsConsistency', request => ({
1382
1698
  [Attributes.BLOCK_ARCHIVE]: request.archiveRoot.toString(),
1383
1699
  }))
1384
- protected async validateRequestedBlockTxs(
1700
+ protected async validateRequestedBlockTxsConsistency(
1385
1701
  request: BlockTxsRequest,
1386
1702
  response: BlockTxsResponse,
1387
1703
  peerId: PeerId,
1388
1704
  ): Promise<boolean> {
1389
- const requestedTxValidator = this.createRequestedTxValidator();
1390
-
1391
1705
  try {
1392
- if (!response.archiveRoot.equals(request.archiveRoot)) {
1706
+ // Check for duplicates txs (or hashes) in the response.
1707
+ const returnedHashes = response.txs.map(tx => tx.getTxHash().toString());
1708
+ const uniqueReturned = new Set(returnedHashes.map(h => h.toString()));
1709
+ if (uniqueReturned.size !== returnedHashes.length) {
1393
1710
  this.peerManager.penalizePeer(peerId, PeerErrorSeverity.MidToleranceError);
1394
- throw new ValidationError(
1395
- `Received block txs for unexpected archive root: expected ${request.archiveRoot.toString()}, got ${response.archiveRoot.toString()}`,
1711
+ throw new ValidationError(`Received duplicate txs in block txs response`);
1712
+ }
1713
+
1714
+ // We get the block tx hashes from the proposal or the archiver.
1715
+ const proposal = await this.mempools.attestationPool.getBlockProposalByArchive(request.archiveRoot.toString());
1716
+ const blockTxHashes =
1717
+ proposal?.txHashes ??
1718
+ (await this.archiver.getBlock({ archive: request.archiveRoot }))?.body.txEffects.map(e => e.txHash);
1719
+
1720
+ // If we don't have the block, we can't verify membership/order of the returned txs.
1721
+ if (!blockTxHashes) {
1722
+ // This shouldn't happen, since we asked for the block (proposal).
1723
+ // Neither a local proposal nor an archived block: we cannot verify membership/order of the
1724
+ // returned txs. This is a local-state gap, not a peer fault, so we do not penalize.
1725
+ this.logger.warn(
1726
+ `Block ${request.archiveRoot.toString()} not found in attestation pool or archiver; cannot validate membership/order of returned txs`,
1396
1727
  );
1728
+ // NOTE: We mark the response as invalid, given the limitations of a true/false return value.
1729
+ return false;
1397
1730
  }
1398
1731
 
1399
- if (response.txIndices.getLength() !== request.txIndices.getLength()) {
1400
- this.peerManager.penalizePeer(peerId, PeerErrorSeverity.MidToleranceError);
1732
+ // Verify that the returned tx hashes are a subset of (tx hashes by index) U (explicitly requested tx hashes).
1733
+ const uniqueRequestedHashes = new Set([
1734
+ // tx hashes requested by index.
1735
+ ...request.txIndices.getTrueIndices().map(i => blockTxHashes[i].toString()),
1736
+ // explicitly requested tx hashes.
1737
+ ...request.txHashes.map(h => h.toString()),
1738
+ ]);
1739
+ if (!returnedHashes.every(h => uniqueRequestedHashes.has(h))) {
1740
+ this.peerManager.penalizePeer(peerId, PeerErrorSeverity.LowToleranceError);
1401
1741
  throw new ValidationError(
1402
- `Received block txs with mismatched bitvector length: expected ${request.txIndices.getLength()}, got ${response.txIndices.getLength()}`,
1742
+ 'Returned txs should be a subset of (tx hashes by index) U (explicitly requested tx hashes)',
1403
1743
  );
1404
1744
  }
1405
1745
 
1406
- // Check no duplicates and not exceeding returnable count
1407
- const requestedIndices = new Set(request.txIndices.getTrueIndices());
1408
- const availableIndices = new Set(response.txIndices.getTrueIndices());
1409
- const maxReturnable = [...requestedIndices].filter(i => availableIndices.has(i)).length;
1410
-
1411
- const returnedHashes = await Promise.all(response.txs.map(tx => tx.getTxHash().toString()));
1412
- const uniqueReturned = new Set(returnedHashes.map(h => h.toString()));
1413
- if (uniqueReturned.size !== returnedHashes.length) {
1414
- this.peerManager.penalizePeer(peerId, PeerErrorSeverity.MidToleranceError);
1415
- throw new ValidationError(`Received duplicate txs in block txs response`);
1746
+ // Tx indices information is optional, but if present, we need to verify a few things.
1747
+ if (!response.peerHasBlock()) {
1748
+ this.logger.debug(`Peer ${peerId.toString()} signalled missing block`);
1749
+ return true;
1416
1750
  }
1417
- if (response.txs.length > maxReturnable) {
1751
+
1752
+ // If the response has a non-empty bitvector, it needs to be consistent with the number of txs in the block.
1753
+ if (response.txIndices.getLength() !== blockTxHashes.length) {
1418
1754
  this.peerManager.penalizePeer(peerId, PeerErrorSeverity.MidToleranceError);
1419
1755
  throw new ValidationError(
1420
- `Received more txs (${response.txs.length}) than requested-and-available (${maxReturnable})`,
1756
+ `Received block txs with mismatched bitvector length: expected ${blockTxHashes.length}, got ${response.txIndices.getLength()}`,
1421
1757
  );
1422
1758
  }
1423
1759
 
1424
- // Given proposal (should have locally), ensure returned txs are valid subset and match request indices
1425
- const proposal = await this.mempools.attestationPool.getBlockProposal(request.archiveRoot.toString());
1426
- if (proposal) {
1427
- // Build intersected indices
1428
- const intersectIdx = request.txIndices.getTrueIndices().filter(i => response.txIndices.isSet(i));
1429
-
1430
- // Enforce subset membership and preserve increasing order by index.
1431
- const hashToIndexInProposal = new Map<string, number>(
1432
- proposal.txHashes.map((h, i) => [h.toString(), i] as [string, number]),
1433
- );
1434
- const allowedIndexSet = new Set(intersectIdx);
1435
- const indices = returnedHashes.map(h => hashToIndexInProposal.get(h));
1436
- const allAllowed = indices.every(idx => idx !== undefined && allowedIndexSet.has(idx));
1437
- const strictlyIncreasing = indices.every((idx, i) => (i === 0 ? idx !== undefined : idx! > indices[i - 1]!));
1438
- if (!allAllowed || !strictlyIncreasing) {
1439
- this.peerManager.penalizePeer(peerId, PeerErrorSeverity.LowToleranceError);
1440
- throw new ValidationError('Returned txs do not match expected subset/order for requested indices');
1441
- }
1442
- } else {
1443
- // No local proposal, cannot check the membership/order of the returned txs
1444
- this.logger.warn(
1445
- `Block proposal not found for archive root ${request.archiveRoot.toString()}; cannot validate membership/order of returned txs`,
1446
- );
1447
- return false;
1760
+ // For every index we requested that the peer claims to have (per its bitvector), the
1761
+ // corresponding tx must be present in the response. A peer advertising availability but
1762
+ // withholding the tx is inconsistent.
1763
+ const returnedHashSet = new Set(returnedHashes);
1764
+ const expectedIndices = request.txIndices.getTrueIndices().filter(i => response.txIndices.isSet(i));
1765
+ const missingExpected = expectedIndices.some(i => !returnedHashSet.has(blockTxHashes[i].toString()));
1766
+ if (missingExpected) {
1767
+ this.peerManager.penalizePeer(peerId, PeerErrorSeverity.LowToleranceError);
1768
+ throw new ValidationError('Peer advertised requested txs via indices but did not return them');
1448
1769
  }
1449
1770
 
1450
- await Promise.all(response.txs.map(tx => this.validateRequestedTx(tx, peerId, requestedTxValidator)));
1451
1771
  return true;
1452
1772
  } catch (e: any) {
1453
1773
  if (e instanceof ValidationError) {
@@ -1460,125 +1780,8 @@ export class LibP2PService extends WithTracer implements P2PService {
1460
1780
  }
1461
1781
  }
1462
1782
 
1463
- /**
1464
- * Validate a collection of txs that has been requested from a peer.
1465
- *
1466
- * The core component of this validator is that each tx hash MUST match the requested tx hash,
1467
- * In order to perform this check, the tx proof must be verified.
1468
- *
1469
- * Note: This function is called from within `ReqResp.sendRequest` as part of the
1470
- * ReqRespSubProtocol.TX subprotocol validation.
1471
- *
1472
- * @param requestedTxHash - The collection of the txs that was requested.
1473
- * @param responseTx - The collection of txs that was received as a response to the request.
1474
- * @param peerId - The peer ID of the peer that sent the tx.
1475
- * @returns True if the whole collection of txs is valid, false otherwise.
1476
- */
1477
- @trackSpan('Libp2pService.validateRequestedTx', (requestedTxHash, _responseTx) => ({
1478
- [Attributes.TX_HASH]: requestedTxHash.toString(),
1479
- }))
1480
- private async validateRequestedTxs(requestedTxHash: TxHash[], responseTx: Tx[], peerId: PeerId): Promise<boolean> {
1481
- const requested = new Set(requestedTxHash.map(h => h.toString()));
1482
- const requestedTxValidator = this.createRequestedTxValidator();
1483
-
1484
- //TODO: (mralj) - this is somewhat naive implementation, if single tx is invalid we consider the whole response invalid.
1485
- // I think we should still extract the valid txs and return them, so that we can still use the response.
1486
- try {
1487
- await Promise.all(responseTx.map(tx => this.validateRequestedTx(tx, peerId, requestedTxValidator, requested)));
1488
- return true;
1489
- } catch (e: any) {
1490
- if (e instanceof ValidationError) {
1491
- this.logger.warn(`Failed to validate requested txs from peer ${peerId.toString()}, reason ${e.message}`);
1492
- } else {
1493
- this.logger.error(`Error during validation of requested txs`, e);
1494
- }
1495
-
1496
- return false;
1497
- }
1498
- }
1499
-
1500
- /**
1501
- * Validates a BLOCK response.
1502
- *
1503
- * If a local copy exists, enforces hash equality. If missing, rejects (no penalty) since the hash cannot be verified.
1504
- * Penalizes on block number mismatch or hash mismatch.
1505
- *
1506
- * @param requestedBlockNumber - The requested block number.
1507
- * @param responseBlock - The block returned by the peer.
1508
- * @param peerId - The peer that returned the block.
1509
- * @returns True if the response is valid, false otherwise.
1510
- */
1511
- @trackSpan('Libp2pService.validateRequestedBlock', (requestedBlockNumber, _responseBlock) => ({
1512
- [Attributes.BLOCK_NUMBER]: requestedBlockNumber.toString(),
1513
- }))
1514
- protected async validateRequestedBlock(
1515
- requestedBlockNumber: Fr,
1516
- responseBlock: L2Block,
1517
- peerId: PeerId,
1518
- ): Promise<boolean> {
1519
- try {
1520
- const reqNum = Number(requestedBlockNumber.toString());
1521
- if (responseBlock.number !== reqNum) {
1522
- this.peerManager.penalizePeer(peerId, PeerErrorSeverity.LowToleranceError);
1523
- return false;
1524
- }
1525
-
1526
- const local = await this.archiver.getBlock(BlockNumber(reqNum));
1527
- if (!local) {
1528
- // We are missing the local block; we cannot verify the hash yet. Reject without penalizing.
1529
- // TODO: Consider extending this validator to accept an expected hash or
1530
- // performing quorum-based checks when using P2P syncing prior to L1 sync.
1531
- this.logger.warn(`Local block ${reqNum} not found; rejecting BLOCK response without hash verification`);
1532
- return false;
1533
- }
1534
- const [localHash, respHash] = await Promise.all([local.hash(), responseBlock.hash()]);
1535
- if (!localHash.equals(respHash)) {
1536
- this.peerManager.penalizePeer(peerId, PeerErrorSeverity.MidToleranceError);
1537
- return false;
1538
- }
1539
-
1540
- return true;
1541
- } catch (e) {
1542
- this.logger.warn(`Error validating requested block`, e);
1543
- return false;
1544
- }
1545
- }
1546
-
1547
- protected async validateRequestedTx(
1548
- tx: Tx,
1549
- peerId: PeerId,
1550
- txValidator: TxValidator,
1551
- requested?: Set<`0x${string}`>,
1552
- ) {
1553
- const penalize = (severity: PeerErrorSeverity) => this.peerManager.penalizePeer(peerId, severity);
1554
- if (requested && !requested.has(tx.getTxHash().toString())) {
1555
- penalize(PeerErrorSeverity.MidToleranceError);
1556
- throw new ValidationError(`Received tx with hash ${tx.getTxHash().toString()} that was not requested.`);
1557
- }
1558
-
1559
- const { result } = await txValidator.validateTx(tx);
1560
- if (result === 'invalid') {
1561
- penalize(PeerErrorSeverity.LowToleranceError);
1562
- throw new ValidationError(`Received tx with hash ${tx.getTxHash().toString()} that is invalid.`);
1563
- }
1564
- }
1565
-
1566
- protected createRequestedTxValidator(): TxValidator {
1567
- return createTxValidatorForReqResponseReceivedTxs(this.proofVerifier, {
1568
- l1ChainId: this.config.l1ChainId,
1569
- rollupVersion: this.config.rollupVersion,
1570
- });
1571
- }
1572
-
1573
- private async getGasFees(blockNumber: BlockNumber): Promise<GasFees> {
1574
- if (blockNumber === this.feesCache?.blockNumber) {
1575
- return this.feesCache.gasFees;
1576
- }
1577
-
1578
- const header = await this.archiver.getBlockHeader(blockNumber);
1579
- const gasFees = header?.globalVariables.gasFees ?? GasFees.empty();
1580
- this.feesCache = { blockNumber, gasFees };
1581
- return gasFees;
1783
+ private getGasFees(): Promise<GasFees> {
1784
+ return this.blockMinFeesProvider.getCurrentMinFees();
1582
1785
  }
1583
1786
 
1584
1787
  /**
@@ -1592,8 +1795,10 @@ export class LibP2PService extends WithTracer implements P2PService {
1592
1795
  l1ChainId: this.config.l1ChainId,
1593
1796
  rollupVersion: this.config.rollupVersion,
1594
1797
  proofVerifier: this.proofVerifier,
1798
+ txValidationCache: this.txValidationCache,
1595
1799
  },
1596
1800
  peerScoring: this.peerManager,
1801
+ validateRequestedBlockTxsConsistency: this.validateRequestedBlockTxsConsistency.bind(this),
1597
1802
  };
1598
1803
  }
1599
1804
 
@@ -1602,16 +1807,19 @@ export class LibP2PService extends WithTracer implements P2PService {
1602
1807
  this.proofVerifier,
1603
1808
  { l1ChainId: this.config.l1ChainId, rollupVersion: this.config.rollupVersion },
1604
1809
  this.logger.getBindings(),
1810
+ this.txValidationCache,
1605
1811
  );
1606
1812
 
1607
1813
  const results = await Promise.all(
1608
- txs.map(async tx => {
1609
- const result = await validator.validateTx(tx);
1610
- return result.result !== 'invalid';
1611
- }),
1814
+ txs.map(async tx => ({ txHash: tx.getTxHash(), result: await validator.validateTx(tx) })),
1612
1815
  );
1613
- if (results.some(value => value === false)) {
1614
- throw new Error('Invalid tx detected');
1816
+
1817
+ const invalidTxs = results.flatMap(({ txHash, result }) =>
1818
+ result.result === 'invalid' ? [{ txHash, reasons: result.reason }] : [],
1819
+ );
1820
+
1821
+ if (invalidTxs.length > 0) {
1822
+ throw new InvalidBlockProposalTxsError(invalidTxs);
1615
1823
  }
1616
1824
  }
1617
1825
 
@@ -1620,12 +1828,14 @@ export class LibP2PService extends WithTracer implements P2PService {
1620
1828
  currentBlockNumber: BlockNumber,
1621
1829
  nextSlotTimestamp: UInt64,
1622
1830
  ): Promise<Record<string, TransactionValidator>> {
1623
- const gasFees = await this.getGasFees(currentBlockNumber);
1831
+ const gasFees = await this.getGasFees();
1624
1832
  const allowedInSetup = [
1625
1833
  ...(await getDefaultAllowedSetupFunctions()),
1626
1834
  ...(this.config.txPublicSetupAllowListExtend ?? []),
1627
1835
  ];
1628
1836
  const blockNumber = BlockNumber(currentBlockNumber + 1);
1837
+ const l1Constants = await this.archiver.getL1Constants();
1838
+ const networkTxGasLimits = getNetworkTxGasLimits(this.config, l1Constants);
1629
1839
 
1630
1840
  return createFirstStageTxValidationsForGossipedTransactions(
1631
1841
  nextSlotTimestamp,
@@ -1639,6 +1849,10 @@ export class LibP2PService extends WithTracer implements P2PService {
1639
1849
  !this.config.disableTransactions,
1640
1850
  allowedInSetup,
1641
1851
  this.logger.getBindings(),
1852
+ {
1853
+ maxTxL2Gas: networkTxGasLimits.l2Gas,
1854
+ maxTxDAGas: networkTxGasLimits.daGas,
1855
+ },
1642
1856
  );
1643
1857
  }
1644
1858
 
@@ -1664,8 +1878,10 @@ export class LibP2PService extends WithTracer implements P2PService {
1664
1878
 
1665
1879
  // A promise that resolves when all validations have been run
1666
1880
  const allValidations = await Promise.all(validationPromises);
1667
- const failed = allValidations.find(x => !x.isValid);
1668
- if (failed) {
1881
+ const failures = allValidations.filter(x => !x.isValid);
1882
+ if (failures.length > 0) {
1883
+ // Pick the most severe failure (lowest tolerance = harshest penalty)
1884
+ const failed = maxBy(failures, f => PeerErrorSeverityByHarshness.indexOf(f.severity))!;
1669
1885
  return {
1670
1886
  allPassed: false,
1671
1887
  failure: {
@@ -1718,31 +1934,6 @@ export class LibP2PService extends WithTracer implements P2PService {
1718
1934
  return PeerErrorSeverity.HighToleranceError;
1719
1935
  }
1720
1936
 
1721
- /**
1722
- * Validate a checkpoint attestation.
1723
- *
1724
- * @param attestation - The checkpoint attestation to validate.
1725
- * @returns True if the checkpoint attestation is valid, false otherwise.
1726
- */
1727
- @trackSpan('Libp2pService.validateCheckpointAttestation', async (_, attestation) => ({
1728
- [Attributes.SLOT_NUMBER]: attestation.payload.header.slotNumber,
1729
- [Attributes.BLOCK_ARCHIVE]: attestation.archive.toString(),
1730
- [Attributes.P2P_ID]: await attestation.p2pMessageLoggingIdentifier().then(i => i.toString()),
1731
- }))
1732
- public async validateCheckpointAttestation(
1733
- peerId: PeerId,
1734
- attestation: CheckpointAttestation,
1735
- ): Promise<P2PValidationResult> {
1736
- const result = await this.checkpointAttestationValidator.validate(attestation);
1737
-
1738
- if (result.result === 'reject') {
1739
- this.logger.warn(`Penalizing peer ${peerId} for checkpoint attestation validation failure`);
1740
- this.peerManager.penalizePeer(peerId, result.severity);
1741
- }
1742
-
1743
- return result;
1744
- }
1745
-
1746
1937
  public getPeerScore(peerId: PeerId): number {
1747
1938
  return this.node.services.pubsub.score.score(peerId.toString());
1748
1939
  }