@aztec/p2p 0.0.1-commit.181e2d196 → 0.0.1-commit.189eedb3

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 (455) hide show
  1. package/README.md +129 -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 +9 -1
  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 +33 -15
  8. package/dest/client/interface.d.ts +14 -5
  9. package/dest/client/interface.d.ts.map +1 -1
  10. package/dest/client/p2p_client.d.ts +13 -9
  11. package/dest/client/p2p_client.d.ts.map +1 -1
  12. package/dest/client/p2p_client.js +93 -49
  13. package/dest/config.d.ts +148 -96
  14. package/dest/config.d.ts.map +1 -1
  15. package/dest/config.js +114 -10
  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 +1 -20
  20. package/dest/errors/reqresp.error.d.ts.map +1 -1
  21. package/dest/errors/reqresp.error.js +0 -21
  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 +99 -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 +265 -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 +181 -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 +1 -1
  37. package/dest/mem_pools/instrumentation.d.ts.map +1 -1
  38. package/dest/mem_pools/instrumentation.js +17 -1
  39. package/dest/mem_pools/tx_pool_v2/archive/tx_archive.d.ts +1 -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 +1 -7
  42. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.d.ts +1 -1
  43. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.d.ts.map +1 -1
  44. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.js +2 -1
  45. package/dest/mem_pools/tx_pool_v2/eviction/index.d.ts +2 -1
  46. package/dest/mem_pools/tx_pool_v2/eviction/index.d.ts.map +1 -1
  47. package/dest/mem_pools/tx_pool_v2/eviction/index.js +1 -0
  48. package/dest/mem_pools/tx_pool_v2/eviction/insufficient_fee_per_gas_eviction_rule.d.ts +16 -0
  49. package/dest/mem_pools/tx_pool_v2/eviction/insufficient_fee_per_gas_eviction_rule.d.ts.map +1 -0
  50. package/dest/mem_pools/tx_pool_v2/eviction/insufficient_fee_per_gas_eviction_rule.js +62 -0
  51. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.d.ts +7 -1
  52. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.d.ts.map +1 -1
  53. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.js +2 -2
  54. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.d.ts +1 -1
  55. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.d.ts.map +1 -1
  56. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.js +8 -6
  57. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.d.ts +2 -2
  58. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.d.ts.map +1 -1
  59. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.js +2 -2
  60. package/dest/mem_pools/tx_pool_v2/interfaces.d.ts +12 -5
  61. package/dest/mem_pools/tx_pool_v2/interfaces.d.ts.map +1 -1
  62. package/dest/mem_pools/tx_pool_v2/interfaces.js +2 -1
  63. package/dest/mem_pools/tx_pool_v2/tx_metadata.d.ts +29 -11
  64. package/dest/mem_pools/tx_pool_v2/tx_metadata.d.ts.map +1 -1
  65. package/dest/mem_pools/tx_pool_v2/tx_metadata.js +46 -16
  66. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.d.ts +1 -1
  67. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.d.ts.map +1 -1
  68. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.js +26 -43
  69. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.d.ts +4 -2
  70. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.d.ts.map +1 -1
  71. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.js +3 -0
  72. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.d.ts +1 -1
  73. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.d.ts.map +1 -1
  74. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.js +94 -88
  75. package/dest/msg_validators/attestation_validator/attestation_validator.d.ts +9 -3
  76. package/dest/msg_validators/attestation_validator/attestation_validator.d.ts.map +1 -1
  77. package/dest/msg_validators/attestation_validator/attestation_validator.js +37 -12
  78. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.d.ts +7 -3
  79. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.d.ts.map +1 -1
  80. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.js +4 -5
  81. package/dest/msg_validators/clock_tolerance.d.ts +12 -1
  82. package/dest/msg_validators/clock_tolerance.d.ts.map +1 -1
  83. package/dest/msg_validators/clock_tolerance.js +56 -3
  84. package/dest/msg_validators/proposal_validator/block_proposal_validator.d.ts +9 -4
  85. package/dest/msg_validators/proposal_validator/block_proposal_validator.d.ts.map +1 -1
  86. package/dest/msg_validators/proposal_validator/block_proposal_validator.js +10 -2
  87. package/dest/msg_validators/proposal_validator/checkpoint_proposal_validator.d.ts +9 -4
  88. package/dest/msg_validators/proposal_validator/checkpoint_proposal_validator.d.ts.map +1 -1
  89. package/dest/msg_validators/proposal_validator/checkpoint_proposal_validator.js +16 -2
  90. package/dest/msg_validators/proposal_validator/proposal_validator.d.ts +20 -9
  91. package/dest/msg_validators/proposal_validator/proposal_validator.d.ts.map +1 -1
  92. package/dest/msg_validators/proposal_validator/proposal_validator.js +88 -52
  93. package/dest/msg_validators/tx_validator/aggregate_tx_validator.d.ts +1 -1
  94. package/dest/msg_validators/tx_validator/aggregate_tx_validator.d.ts.map +1 -1
  95. package/dest/msg_validators/tx_validator/aggregate_tx_validator.js +8 -15
  96. package/dest/msg_validators/tx_validator/allowed_public_setup.d.ts +1 -1
  97. package/dest/msg_validators/tx_validator/allowed_public_setup.d.ts.map +1 -1
  98. package/dest/msg_validators/tx_validator/allowed_public_setup.js +21 -32
  99. package/dest/msg_validators/tx_validator/allowed_setup_helpers.d.ts +17 -0
  100. package/dest/msg_validators/tx_validator/allowed_setup_helpers.d.ts.map +1 -0
  101. package/dest/msg_validators/tx_validator/allowed_setup_helpers.js +24 -0
  102. package/dest/msg_validators/tx_validator/archive_cache.js +1 -1
  103. package/dest/msg_validators/tx_validator/cached_tx_validator.d.ts +15 -0
  104. package/dest/msg_validators/tx_validator/cached_tx_validator.d.ts.map +1 -0
  105. package/dest/msg_validators/tx_validator/cached_tx_validator.js +19 -0
  106. package/dest/msg_validators/tx_validator/contract_instance_validator.d.ts +9 -0
  107. package/dest/msg_validators/tx_validator/contract_instance_validator.d.ts.map +1 -0
  108. package/dest/msg_validators/tx_validator/contract_instance_validator.js +48 -0
  109. package/dest/msg_validators/tx_validator/data_validator.d.ts +2 -1
  110. package/dest/msg_validators/tx_validator/data_validator.d.ts.map +1 -1
  111. package/dest/msg_validators/tx_validator/data_validator.js +36 -2
  112. package/dest/msg_validators/tx_validator/factory.d.ts +27 -7
  113. package/dest/msg_validators/tx_validator/factory.d.ts.map +1 -1
  114. package/dest/msg_validators/tx_validator/factory.js +47 -17
  115. package/dest/msg_validators/tx_validator/fee_payer_balance.d.ts +1 -1
  116. package/dest/msg_validators/tx_validator/fee_payer_balance.d.ts.map +1 -1
  117. package/dest/msg_validators/tx_validator/fee_payer_balance.js +6 -2
  118. package/dest/msg_validators/tx_validator/gas_validator.d.ts +48 -7
  119. package/dest/msg_validators/tx_validator/gas_validator.d.ts.map +1 -1
  120. package/dest/msg_validators/tx_validator/gas_validator.js +88 -41
  121. package/dest/msg_validators/tx_validator/index.d.ts +4 -1
  122. package/dest/msg_validators/tx_validator/index.d.ts.map +1 -1
  123. package/dest/msg_validators/tx_validator/index.js +3 -0
  124. package/dest/msg_validators/tx_validator/metadata_validator.d.ts +1 -1
  125. package/dest/msg_validators/tx_validator/metadata_validator.d.ts.map +1 -1
  126. package/dest/msg_validators/tx_validator/metadata_validator.js +4 -4
  127. package/dest/msg_validators/tx_validator/phases_validator.d.ts +21 -1
  128. package/dest/msg_validators/tx_validator/phases_validator.d.ts.map +1 -1
  129. package/dest/msg_validators/tx_validator/phases_validator.js +49 -2
  130. package/dest/msg_validators/tx_validator/tx_proof_validator.d.ts +2 -1
  131. package/dest/msg_validators/tx_validator/tx_proof_validator.d.ts.map +1 -1
  132. package/dest/msg_validators/tx_validator/tx_proof_validator.js +2 -0
  133. package/dest/msg_validators/tx_validator/tx_validation_cache.d.ts +48 -0
  134. package/dest/msg_validators/tx_validator/tx_validation_cache.d.ts.map +1 -0
  135. package/dest/msg_validators/tx_validator/tx_validation_cache.js +68 -0
  136. package/dest/services/data_store.d.ts +1 -1
  137. package/dest/services/data_store.d.ts.map +1 -1
  138. package/dest/services/data_store.js +5 -5
  139. package/dest/services/discv5/discV5_service.d.ts +2 -1
  140. package/dest/services/discv5/discV5_service.d.ts.map +1 -1
  141. package/dest/services/discv5/discV5_service.js +35 -8
  142. package/dest/services/dummy_service.d.ts +11 -15
  143. package/dest/services/dummy_service.d.ts.map +1 -1
  144. package/dest/services/dummy_service.js +12 -16
  145. package/dest/services/encoding.d.ts +5 -1
  146. package/dest/services/encoding.d.ts.map +1 -1
  147. package/dest/services/encoding.js +7 -1
  148. package/dest/services/gossipsub/topic_score_params.d.ts +13 -2
  149. package/dest/services/gossipsub/topic_score_params.d.ts.map +1 -1
  150. package/dest/services/gossipsub/topic_score_params.js +21 -4
  151. package/dest/services/libp2p/instrumentation.d.ts +3 -1
  152. package/dest/services/libp2p/instrumentation.d.ts.map +1 -1
  153. package/dest/services/libp2p/instrumentation.js +14 -0
  154. package/dest/services/libp2p/libp2p_service.d.ts +36 -46
  155. package/dest/services/libp2p/libp2p_service.d.ts.map +1 -1
  156. package/dest/services/libp2p/libp2p_service.js +311 -276
  157. package/dest/services/peer-manager/peer_manager.d.ts +6 -2
  158. package/dest/services/peer-manager/peer_manager.d.ts.map +1 -1
  159. package/dest/services/peer-manager/peer_manager.js +38 -10
  160. package/dest/services/peer-manager/peer_scoring.d.ts +7 -2
  161. package/dest/services/peer-manager/peer_scoring.d.ts.map +1 -1
  162. package/dest/services/peer-manager/peer_scoring.js +32 -10
  163. package/dest/services/reqresp/batch-tx-requester/batch_tx_requester.d.ts +4 -8
  164. package/dest/services/reqresp/batch-tx-requester/batch_tx_requester.d.ts.map +1 -1
  165. package/dest/services/reqresp/batch-tx-requester/batch_tx_requester.js +81 -86
  166. package/dest/services/reqresp/batch-tx-requester/interface.d.ts +10 -6
  167. package/dest/services/reqresp/batch-tx-requester/interface.d.ts.map +1 -1
  168. package/dest/services/reqresp/batch-tx-requester/missing_txs.d.ts +5 -4
  169. package/dest/services/reqresp/batch-tx-requester/missing_txs.d.ts.map +1 -1
  170. package/dest/services/reqresp/batch-tx-requester/missing_txs.js +13 -7
  171. package/dest/services/reqresp/batch-tx-requester/peer_collection.d.ts +3 -1
  172. package/dest/services/reqresp/batch-tx-requester/peer_collection.d.ts.map +1 -1
  173. package/dest/services/reqresp/batch-tx-requester/peer_collection.js +3 -0
  174. package/dest/services/reqresp/batch-tx-requester/tx_validator.d.ts +5 -14
  175. package/dest/services/reqresp/batch-tx-requester/tx_validator.d.ts.map +1 -1
  176. package/dest/services/reqresp/batch-tx-requester/tx_validator.js +6 -20
  177. package/dest/services/reqresp/config.d.ts +3 -3
  178. package/dest/services/reqresp/config.d.ts.map +1 -1
  179. package/dest/services/reqresp/interface.d.ts +16 -18
  180. package/dest/services/reqresp/interface.d.ts.map +1 -1
  181. package/dest/services/reqresp/interface.js +10 -20
  182. package/dest/services/reqresp/metrics.d.ts +1 -1
  183. package/dest/services/reqresp/metrics.d.ts.map +1 -1
  184. package/dest/services/reqresp/metrics.js +0 -1
  185. package/dest/services/reqresp/protocols/block_txs/bitvector.d.ts +4 -3
  186. package/dest/services/reqresp/protocols/block_txs/bitvector.d.ts.map +1 -1
  187. package/dest/services/reqresp/protocols/block_txs/bitvector.js +3 -2
  188. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.d.ts +1 -1
  189. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.d.ts.map +1 -1
  190. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.js +31 -28
  191. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.d.ts +12 -7
  192. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.d.ts.map +1 -1
  193. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.js +42 -24
  194. package/dest/services/reqresp/protocols/index.d.ts +1 -2
  195. package/dest/services/reqresp/protocols/index.d.ts.map +1 -1
  196. package/dest/services/reqresp/protocols/index.js +0 -1
  197. package/dest/services/reqresp/protocols/tx.d.ts +1 -1
  198. package/dest/services/reqresp/protocols/tx.d.ts.map +1 -1
  199. package/dest/services/reqresp/protocols/tx.js +1 -3
  200. package/dest/services/reqresp/rate-limiter/rate_limiter.d.ts +5 -4
  201. package/dest/services/reqresp/rate-limiter/rate_limiter.d.ts.map +1 -1
  202. package/dest/services/reqresp/rate-limiter/rate_limiter.js +10 -8
  203. package/dest/services/reqresp/rate-limiter/rate_limits.d.ts +1 -1
  204. package/dest/services/reqresp/rate-limiter/rate_limits.d.ts.map +1 -1
  205. package/dest/services/reqresp/rate-limiter/rate_limits.js +0 -10
  206. package/dest/services/reqresp/reqresp.d.ts +7 -29
  207. package/dest/services/reqresp/reqresp.d.ts.map +1 -1
  208. package/dest/services/reqresp/reqresp.js +41 -214
  209. package/dest/services/service.d.ts +9 -12
  210. package/dest/services/service.d.ts.map +1 -1
  211. package/dest/services/tx_collection/config.d.ts +2 -23
  212. package/dest/services/tx_collection/config.d.ts.map +1 -1
  213. package/dest/services/tx_collection/config.js +2 -55
  214. package/dest/services/tx_collection/file_store_tx_collection.d.ts +12 -28
  215. package/dest/services/tx_collection/file_store_tx_collection.d.ts.map +1 -1
  216. package/dest/services/tx_collection/file_store_tx_collection.js +43 -83
  217. package/dest/services/tx_collection/file_store_tx_source.d.ts +5 -4
  218. package/dest/services/tx_collection/file_store_tx_source.d.ts.map +1 -1
  219. package/dest/services/tx_collection/file_store_tx_source.js +39 -29
  220. package/dest/services/tx_collection/index.d.ts +2 -3
  221. package/dest/services/tx_collection/index.d.ts.map +1 -1
  222. package/dest/services/tx_collection/index.js +0 -1
  223. package/dest/services/tx_collection/instrumentation.d.ts +1 -1
  224. package/dest/services/tx_collection/instrumentation.d.ts.map +1 -1
  225. package/dest/services/tx_collection/instrumentation.js +0 -2
  226. package/dest/services/tx_collection/request_tracker.d.ts +53 -0
  227. package/dest/services/tx_collection/request_tracker.d.ts.map +1 -0
  228. package/dest/services/tx_collection/request_tracker.js +84 -0
  229. package/dest/services/tx_collection/tx_collection.d.ts +36 -55
  230. package/dest/services/tx_collection/tx_collection.d.ts.map +1 -1
  231. package/dest/services/tx_collection/tx_collection.js +275 -119
  232. package/dest/services/tx_collection/tx_collection_sink.d.ts +1 -1
  233. package/dest/services/tx_collection/tx_collection_sink.js +2 -2
  234. package/dest/services/tx_collection/tx_source.d.ts +6 -5
  235. package/dest/services/tx_collection/tx_source.d.ts.map +1 -1
  236. package/dest/services/tx_collection/tx_source.js +9 -7
  237. package/dest/services/tx_file_store/tx_file_store.d.ts +1 -3
  238. package/dest/services/tx_file_store/tx_file_store.d.ts.map +1 -1
  239. package/dest/services/tx_file_store/tx_file_store.js +4 -14
  240. package/dest/services/tx_provider.d.ts +3 -1
  241. package/dest/services/tx_provider.d.ts.map +1 -1
  242. package/dest/services/tx_provider.js +3 -0
  243. package/dest/test-helpers/make-test-p2p-clients.d.ts +1 -1
  244. package/dest/test-helpers/make-test-p2p-clients.d.ts.map +1 -1
  245. package/dest/test-helpers/make-test-p2p-clients.js +5 -2
  246. package/dest/test-helpers/mock-pubsub.d.ts +23 -9
  247. package/dest/test-helpers/mock-pubsub.d.ts.map +1 -1
  248. package/dest/test-helpers/mock-pubsub.js +44 -44
  249. package/dest/test-helpers/reqresp-nodes.d.ts +4 -5
  250. package/dest/test-helpers/reqresp-nodes.d.ts.map +1 -1
  251. package/dest/test-helpers/reqresp-nodes.js +16 -18
  252. package/dest/test-helpers/test_tx_provider.d.ts +3 -1
  253. package/dest/test-helpers/test_tx_provider.d.ts.map +1 -1
  254. package/dest/test-helpers/test_tx_provider.js +3 -0
  255. package/dest/test-helpers/testbench-utils.d.ts +12 -14
  256. package/dest/test-helpers/testbench-utils.d.ts.map +1 -1
  257. package/dest/test-helpers/testbench-utils.js +40 -15
  258. package/dest/testbench/p2p_client_testbench_worker.d.ts +3 -5
  259. package/dest/testbench/p2p_client_testbench_worker.d.ts.map +1 -1
  260. package/dest/testbench/p2p_client_testbench_worker.js +85 -39
  261. package/dest/testbench/worker_client_manager.d.ts +12 -6
  262. package/dest/testbench/worker_client_manager.d.ts.map +1 -1
  263. package/dest/testbench/worker_client_manager.js +57 -11
  264. package/dest/util.d.ts +12 -7
  265. package/dest/util.d.ts.map +1 -1
  266. package/dest/util.js +35 -14
  267. package/dest/versioning.d.ts +3 -6
  268. package/dest/versioning.d.ts.map +1 -1
  269. package/dest/versioning.js +3 -24
  270. package/package.json +15 -14
  271. package/src/bootstrap/bootstrap.ts +9 -1
  272. package/src/client/factory.ts +57 -8
  273. package/src/client/interface.ts +15 -11
  274. package/src/client/p2p_client.ts +106 -70
  275. package/src/client/test/{tx_proposal_collector/README.md → p2p_client.batch_tx_requester.bench.README.md} +23 -53
  276. package/src/config.ts +195 -7
  277. package/src/errors/p2p-service.error.ts +11 -0
  278. package/src/errors/reqresp.error.ts +0 -25
  279. package/src/index.ts +0 -1
  280. package/src/mem_pools/attestation_pool/attestation_pool.ts +316 -241
  281. package/src/mem_pools/attestation_pool/attestation_pool_test_suite.ts +204 -68
  282. package/src/mem_pools/attestation_pool/mocks.ts +13 -8
  283. package/src/mem_pools/index.ts +0 -3
  284. package/src/mem_pools/instrumentation.ts +5 -1
  285. package/src/mem_pools/tx_pool_v2/README.md +9 -1
  286. package/src/mem_pools/tx_pool_v2/archive/tx_archive.ts +1 -9
  287. package/src/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.ts +2 -1
  288. package/src/mem_pools/tx_pool_v2/eviction/index.ts +1 -0
  289. package/src/mem_pools/tx_pool_v2/eviction/insufficient_fee_per_gas_eviction_rule.ts +65 -0
  290. package/src/mem_pools/tx_pool_v2/eviction/interfaces.ts +11 -1
  291. package/src/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.ts +3 -3
  292. package/src/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.ts +15 -6
  293. package/src/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.ts +2 -1
  294. package/src/mem_pools/tx_pool_v2/interfaces.ts +12 -4
  295. package/src/mem_pools/tx_pool_v2/tx_metadata.ts +72 -20
  296. package/src/mem_pools/tx_pool_v2/tx_pool_indices.ts +29 -43
  297. package/src/mem_pools/tx_pool_v2/tx_pool_v2.ts +13 -1
  298. package/src/mem_pools/tx_pool_v2/tx_pool_v2_impl.ts +96 -94
  299. package/src/msg_validators/attestation_validator/README.md +49 -0
  300. package/src/msg_validators/attestation_validator/attestation_validator.ts +41 -9
  301. package/src/msg_validators/attestation_validator/fisherman_attestation_validator.ts +14 -7
  302. package/src/msg_validators/clock_tolerance.ts +73 -3
  303. package/src/msg_validators/proposal_validator/README.md +123 -0
  304. package/src/msg_validators/proposal_validator/block_proposal_validator.ts +24 -4
  305. package/src/msg_validators/proposal_validator/checkpoint_proposal_validator.ts +35 -7
  306. package/src/msg_validators/proposal_validator/proposal_validator.ts +109 -56
  307. package/src/msg_validators/tx_validator/README.md +15 -3
  308. package/src/msg_validators/tx_validator/aggregate_tx_validator.ts +3 -12
  309. package/src/msg_validators/tx_validator/allowed_public_setup.ts +16 -35
  310. package/src/msg_validators/tx_validator/allowed_setup_helpers.ts +31 -0
  311. package/src/msg_validators/tx_validator/archive_cache.ts +1 -1
  312. package/src/msg_validators/tx_validator/cached_tx_validator.ts +31 -0
  313. package/src/msg_validators/tx_validator/contract_instance_validator.ts +56 -0
  314. package/src/msg_validators/tx_validator/data_validator.ts +44 -1
  315. package/src/msg_validators/tx_validator/factory.ts +61 -10
  316. package/src/msg_validators/tx_validator/fee_payer_balance.ts +6 -2
  317. package/src/msg_validators/tx_validator/gas_validator.ts +121 -39
  318. package/src/msg_validators/tx_validator/index.ts +3 -0
  319. package/src/msg_validators/tx_validator/metadata_validator.ts +12 -4
  320. package/src/msg_validators/tx_validator/phases_validator.ts +60 -1
  321. package/src/msg_validators/tx_validator/tx_proof_validator.ts +2 -0
  322. package/src/msg_validators/tx_validator/tx_validation_cache.ts +101 -0
  323. package/src/services/data_store.ts +5 -13
  324. package/src/services/discv5/discV5_service.ts +38 -5
  325. package/src/services/dummy_service.ts +14 -39
  326. package/src/services/encoding.ts +9 -1
  327. package/src/services/gossipsub/topic_score_params.ts +36 -4
  328. package/src/services/libp2p/instrumentation.ts +14 -0
  329. package/src/services/libp2p/libp2p_service.ts +339 -313
  330. package/src/services/peer-manager/peer_manager.ts +44 -10
  331. package/src/services/peer-manager/peer_scoring.ts +27 -5
  332. package/src/services/reqresp/README.md +215 -0
  333. package/src/services/reqresp/batch-tx-requester/README.md +46 -7
  334. package/src/services/reqresp/batch-tx-requester/batch_tx_requester.ts +77 -95
  335. package/src/services/reqresp/batch-tx-requester/interface.ts +13 -5
  336. package/src/services/reqresp/batch-tx-requester/missing_txs.ts +13 -6
  337. package/src/services/reqresp/batch-tx-requester/peer_collection.ts +5 -0
  338. package/src/services/reqresp/batch-tx-requester/tx_validator.ts +12 -25
  339. package/src/services/reqresp/config.ts +2 -2
  340. package/src/services/reqresp/interface.ts +21 -47
  341. package/src/services/reqresp/metrics.ts +0 -1
  342. package/src/services/reqresp/protocols/block_txs/bitvector.ts +3 -2
  343. package/src/services/reqresp/protocols/block_txs/block_txs_handler.ts +34 -30
  344. package/src/services/reqresp/protocols/block_txs/block_txs_reqresp.ts +47 -20
  345. package/src/services/reqresp/protocols/index.ts +0 -1
  346. package/src/services/reqresp/protocols/tx.ts +1 -3
  347. package/src/services/reqresp/rate-limiter/rate_limiter.ts +13 -9
  348. package/src/services/reqresp/rate-limiter/rate_limits.ts +0 -10
  349. package/src/services/reqresp/reqresp.ts +45 -260
  350. package/src/services/service.ts +12 -28
  351. package/src/services/tx_collection/config.ts +3 -80
  352. package/src/services/tx_collection/file_store_tx_collection.ts +54 -103
  353. package/src/services/tx_collection/file_store_tx_source.ts +43 -31
  354. package/src/services/tx_collection/index.ts +1 -6
  355. package/src/services/tx_collection/instrumentation.ts +1 -7
  356. package/src/services/tx_collection/request_tracker.ts +127 -0
  357. package/src/services/tx_collection/tx_collection.ts +331 -176
  358. package/src/services/tx_collection/tx_collection_sink.ts +2 -2
  359. package/src/services/tx_collection/tx_source.ts +8 -7
  360. package/src/services/tx_file_store/tx_file_store.ts +5 -17
  361. package/src/services/tx_provider.ts +5 -0
  362. package/src/test-helpers/make-test-p2p-clients.ts +4 -1
  363. package/src/test-helpers/mock-pubsub.ts +46 -60
  364. package/src/test-helpers/reqresp-nodes.ts +13 -23
  365. package/src/test-helpers/test_tx_provider.ts +5 -0
  366. package/src/test-helpers/testbench-utils.ts +51 -28
  367. package/src/testbench/p2p_client_testbench_worker.ts +89 -55
  368. package/src/testbench/worker_client_manager.ts +72 -25
  369. package/src/util.ts +33 -18
  370. package/src/versioning.ts +3 -33
  371. package/dest/client/test/tx_proposal_collector/proposal_tx_collector_worker.d.ts +0 -2
  372. package/dest/client/test/tx_proposal_collector/proposal_tx_collector_worker.d.ts.map +0 -1
  373. package/dest/client/test/tx_proposal_collector/proposal_tx_collector_worker.js +0 -304
  374. package/dest/client/test/tx_proposal_collector/proposal_tx_collector_worker_protocol.d.ts +0 -73
  375. package/dest/client/test/tx_proposal_collector/proposal_tx_collector_worker_protocol.d.ts.map +0 -1
  376. package/dest/client/test/tx_proposal_collector/proposal_tx_collector_worker_protocol.js +0 -8
  377. package/dest/mem_pools/tx_pool/aztec_kv_tx_pool.d.ts +0 -125
  378. package/dest/mem_pools/tx_pool/aztec_kv_tx_pool.d.ts.map +0 -1
  379. package/dest/mem_pools/tx_pool/aztec_kv_tx_pool.js +0 -596
  380. package/dest/mem_pools/tx_pool/eviction/eviction_manager.d.ts +0 -32
  381. package/dest/mem_pools/tx_pool/eviction/eviction_manager.d.ts.map +0 -1
  382. package/dest/mem_pools/tx_pool/eviction/eviction_manager.js +0 -112
  383. package/dest/mem_pools/tx_pool/eviction/eviction_strategy.d.ts +0 -157
  384. package/dest/mem_pools/tx_pool/eviction/eviction_strategy.d.ts.map +0 -1
  385. package/dest/mem_pools/tx_pool/eviction/eviction_strategy.js +0 -52
  386. package/dest/mem_pools/tx_pool/eviction/fee_payer_balance_eviction_rule.d.ts +0 -16
  387. package/dest/mem_pools/tx_pool/eviction/fee_payer_balance_eviction_rule.d.ts.map +0 -1
  388. package/dest/mem_pools/tx_pool/eviction/fee_payer_balance_eviction_rule.js +0 -122
  389. package/dest/mem_pools/tx_pool/eviction/invalid_txs_after_mining_rule.d.ts +0 -17
  390. package/dest/mem_pools/tx_pool/eviction/invalid_txs_after_mining_rule.d.ts.map +0 -1
  391. package/dest/mem_pools/tx_pool/eviction/invalid_txs_after_mining_rule.js +0 -84
  392. package/dest/mem_pools/tx_pool/eviction/invalid_txs_after_reorg_rule.d.ts +0 -19
  393. package/dest/mem_pools/tx_pool/eviction/invalid_txs_after_reorg_rule.d.ts.map +0 -1
  394. package/dest/mem_pools/tx_pool/eviction/invalid_txs_after_reorg_rule.js +0 -78
  395. package/dest/mem_pools/tx_pool/eviction/low_priority_eviction_rule.d.ts +0 -26
  396. package/dest/mem_pools/tx_pool/eviction/low_priority_eviction_rule.d.ts.map +0 -1
  397. package/dest/mem_pools/tx_pool/eviction/low_priority_eviction_rule.js +0 -84
  398. package/dest/mem_pools/tx_pool/eviction/nullifier_conflict_pre_add_rule.d.ts +0 -25
  399. package/dest/mem_pools/tx_pool/eviction/nullifier_conflict_pre_add_rule.d.ts.map +0 -1
  400. package/dest/mem_pools/tx_pool/eviction/nullifier_conflict_pre_add_rule.js +0 -57
  401. package/dest/mem_pools/tx_pool/index.d.ts +0 -3
  402. package/dest/mem_pools/tx_pool/index.d.ts.map +0 -1
  403. package/dest/mem_pools/tx_pool/index.js +0 -2
  404. package/dest/mem_pools/tx_pool/priority.d.ts +0 -12
  405. package/dest/mem_pools/tx_pool/priority.d.ts.map +0 -1
  406. package/dest/mem_pools/tx_pool/priority.js +0 -15
  407. package/dest/mem_pools/tx_pool/tx_pool.d.ts +0 -127
  408. package/dest/mem_pools/tx_pool/tx_pool.d.ts.map +0 -1
  409. package/dest/mem_pools/tx_pool/tx_pool.js +0 -3
  410. package/dest/mem_pools/tx_pool/tx_pool_test_suite.d.ts +0 -7
  411. package/dest/mem_pools/tx_pool/tx_pool_test_suite.d.ts.map +0 -1
  412. package/dest/mem_pools/tx_pool/tx_pool_test_suite.js +0 -400
  413. package/dest/msg_validators/proposal_validator/proposal_validator_test_suite.d.ts +0 -24
  414. package/dest/msg_validators/proposal_validator/proposal_validator_test_suite.d.ts.map +0 -1
  415. package/dest/msg_validators/proposal_validator/proposal_validator_test_suite.js +0 -378
  416. package/dest/services/reqresp/connection-sampler/batch_connection_sampler.d.ts +0 -64
  417. package/dest/services/reqresp/connection-sampler/batch_connection_sampler.d.ts.map +0 -1
  418. package/dest/services/reqresp/connection-sampler/batch_connection_sampler.js +0 -151
  419. package/dest/services/reqresp/protocols/block.d.ts +0 -9
  420. package/dest/services/reqresp/protocols/block.d.ts.map +0 -1
  421. package/dest/services/reqresp/protocols/block.js +0 -32
  422. package/dest/services/tx_collection/fast_tx_collection.d.ts +0 -54
  423. package/dest/services/tx_collection/fast_tx_collection.d.ts.map +0 -1
  424. package/dest/services/tx_collection/fast_tx_collection.js +0 -327
  425. package/dest/services/tx_collection/missing_txs_tracker.d.ts +0 -32
  426. package/dest/services/tx_collection/missing_txs_tracker.d.ts.map +0 -1
  427. package/dest/services/tx_collection/missing_txs_tracker.js +0 -27
  428. package/dest/services/tx_collection/proposal_tx_collector.d.ts +0 -49
  429. package/dest/services/tx_collection/proposal_tx_collector.d.ts.map +0 -1
  430. package/dest/services/tx_collection/proposal_tx_collector.js +0 -50
  431. package/dest/services/tx_collection/slow_tx_collection.d.ts +0 -57
  432. package/dest/services/tx_collection/slow_tx_collection.d.ts.map +0 -1
  433. package/dest/services/tx_collection/slow_tx_collection.js +0 -211
  434. package/src/client/test/tx_proposal_collector/proposal_tx_collector_worker.ts +0 -345
  435. package/src/client/test/tx_proposal_collector/proposal_tx_collector_worker_protocol.ts +0 -43
  436. package/src/mem_pools/tx_pool/README.md +0 -270
  437. package/src/mem_pools/tx_pool/aztec_kv_tx_pool.ts +0 -746
  438. package/src/mem_pools/tx_pool/eviction/eviction_manager.ts +0 -132
  439. package/src/mem_pools/tx_pool/eviction/eviction_strategy.ts +0 -208
  440. package/src/mem_pools/tx_pool/eviction/fee_payer_balance_eviction_rule.ts +0 -162
  441. package/src/mem_pools/tx_pool/eviction/invalid_txs_after_mining_rule.ts +0 -104
  442. package/src/mem_pools/tx_pool/eviction/invalid_txs_after_reorg_rule.ts +0 -93
  443. package/src/mem_pools/tx_pool/eviction/low_priority_eviction_rule.ts +0 -106
  444. package/src/mem_pools/tx_pool/eviction/nullifier_conflict_pre_add_rule.ts +0 -75
  445. package/src/mem_pools/tx_pool/index.ts +0 -2
  446. package/src/mem_pools/tx_pool/priority.ts +0 -20
  447. package/src/mem_pools/tx_pool/tx_pool.ts +0 -141
  448. package/src/mem_pools/tx_pool/tx_pool_test_suite.ts +0 -319
  449. package/src/msg_validators/proposal_validator/proposal_validator_test_suite.ts +0 -373
  450. package/src/services/reqresp/connection-sampler/batch_connection_sampler.ts +0 -161
  451. package/src/services/reqresp/protocols/block.ts +0 -37
  452. package/src/services/tx_collection/fast_tx_collection.ts +0 -387
  453. package/src/services/tx_collection/missing_txs_tracker.ts +0 -52
  454. package/src/services/tx_collection/proposal_tx_collector.ts +0 -113
  455. package/src/services/tx_collection/slow_tx_collection.ts +0 -266
@@ -370,14 +370,14 @@ function applyDecs2203RFactory() {
370
370
  function _apply_decs_2203_r(targetClass, memberDecs, classDecs, parentClass) {
371
371
  return (_apply_decs_2203_r = applyDecs2203RFactory())(targetClass, memberDecs, classDecs, parentClass);
372
372
  }
373
- var _dec, _dec1, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _dec8, _initProto;
373
+ var _dec, _dec1, _dec2, _dec3, _dec4, _dec5, _initProto;
374
374
  import { BlockNumber } from '@aztec/foundation/branded-types';
375
+ import { maxBy, merge } from '@aztec/foundation/collection';
375
376
  import { createLibp2pComponentLogger, createLogger } from '@aztec/foundation/log';
376
377
  import { RunningPromise } from '@aztec/foundation/running-promise';
377
378
  import { Timer } from '@aztec/foundation/timer';
378
379
  import { protocolContractsHash } from '@aztec/protocol-contracts';
379
- import { GasFees } from '@aztec/stdlib/gas';
380
- import { BlockProposal, CheckpointAttestation, CheckpointProposal, P2PMessage, PeerErrorSeverity, TopicType, createTopicString, getTopicsForConfig, metricsTopicStrToLabels } from '@aztec/stdlib/p2p';
380
+ import { BlockProposal, CheckpointAttestation, CheckpointProposal, P2PMessage, PeerErrorSeverity, PeerErrorSeverityByHarshness, TopicType, createTopicString, getTopicsForConfig, metricsTopicStrToLabels } from '@aztec/stdlib/p2p';
381
381
  import { MerkleTreeId } from '@aztec/stdlib/trees';
382
382
  import { Tx } from '@aztec/stdlib/tx';
383
383
  import { compressComponentVersions } from '@aztec/stdlib/versioning';
@@ -392,11 +392,13 @@ import { identify } from '@libp2p/identify';
392
392
  import { TopicValidatorResult } from '@libp2p/interface';
393
393
  import { mplex } from '@libp2p/mplex';
394
394
  import { tcp } from '@libp2p/tcp';
395
+ import { multiaddr } from '@multiformats/multiaddr';
395
396
  import { ENR } from '@nethermindeth/enr';
396
397
  import { createLibp2p } from 'libp2p';
398
+ import { CheckpointProposalReceivedCallbackNotRegisteredError } from '../../errors/p2p-service.error.js';
397
399
  import { BlockProposalValidator, CheckpointAttestationValidator, CheckpointProposalValidator, DoubleSpendTxValidator, FishermanAttestationValidator, getDefaultAllowedSetupFunctions } from '../../msg_validators/index.js';
398
400
  import { MessageSeenValidator } from '../../msg_validators/msg_seen_validator/msg_seen_validator.js';
399
- import { createFirstStageTxValidationsForGossipedTransactions, createSecondStageTxValidationsForGossipedTransactions, createTxValidatorForBlockProposalReceivedTxs, createTxValidatorForReqResponseReceivedTxs } from '../../msg_validators/tx_validator/factory.js';
401
+ import { createFirstStageTxValidationsForGossipedTransactions, createSecondStageTxValidationsForGossipedTransactions, createTxValidatorForBlockProposalReceivedTxs } from '../../msg_validators/tx_validator/factory.js';
400
402
  import { GossipSubEvent } from '../../types/index.js';
401
403
  import { convertToMultiaddr } from '../../util.js';
402
404
  import { getVersions } from '../../versioning.js';
@@ -407,7 +409,7 @@ import { APP_SPECIFIC_WEIGHT, gossipScoreThresholds } from '../gossipsub/scoring
407
409
  import { createAllTopicScoreParams } from '../gossipsub/topic_score_params.js';
408
410
  import { PeerManager } from '../peer-manager/peer_manager.js';
409
411
  import { PeerScoring } from '../peer-manager/peer_scoring.js';
410
- import { DEFAULT_SUB_PROTOCOL_VALIDATORS, ReqRespSubProtocol, ValidationError, pingHandler, reqGoodbyeHandler, reqRespBlockHandler, reqRespBlockTxsHandler, reqRespStatusHandler, reqRespTxHandler } from '../reqresp/index.js';
412
+ import { ReqRespSubProtocol, ValidationError, pingHandler, reqGoodbyeHandler, reqRespBlockTxsHandler, reqRespStatusHandler, reqRespTxHandler } from '../reqresp/index.js';
411
413
  import { ReqResp } from '../reqresp/reqresp.js';
412
414
  import { P2PInstrumentation } from './instrumentation.js';
413
415
  _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId, attestation)=>({
@@ -425,16 +427,8 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
425
427
  [Attributes.SLOT_NUMBER]: checkpoint.slotNumber,
426
428
  [Attributes.BLOCK_ARCHIVE]: checkpoint.archive.toString(),
427
429
  [Attributes.P2P_ID]: await checkpoint.p2pMessageLoggingIdentifier().then((i)=>i.toString())
428
- })), _dec5 = trackSpan('Libp2pService.validateRequestedBlockTxs', (request)=>({
430
+ })), _dec5 = trackSpan('Libp2pService.validateRequestedBlockTxsConsistency', (request)=>({
429
431
  [Attributes.BLOCK_ARCHIVE]: request.archiveRoot.toString()
430
- })), _dec6 = trackSpan('Libp2pService.validateRequestedTx', (requestedTxHash, _responseTx)=>({
431
- [Attributes.TX_HASH]: requestedTxHash.toString()
432
- })), _dec7 = trackSpan('Libp2pService.validateRequestedBlock', (requestedBlockNumber, _responseBlock)=>({
433
- [Attributes.BLOCK_NUMBER]: requestedBlockNumber.toString()
434
- })), _dec8 = trackSpan('Libp2pService.validateCheckpointAttestation', async (_, attestation)=>({
435
- [Attributes.SLOT_NUMBER]: attestation.payload.header.slotNumber,
436
- [Attributes.BLOCK_ARCHIVE]: attestation.archive.toString(),
437
- [Attributes.P2P_ID]: await attestation.p2pMessageLoggingIdentifier().then((i)=>i.toString())
438
432
  }));
439
433
  /**
440
434
  * Lib P2P implementation of the P2PService interface.
@@ -449,6 +443,8 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
449
443
  epochCache;
450
444
  proofVerifier;
451
445
  worldStateSynchronizer;
446
+ blockMinFeesProvider;
447
+ txValidationCache;
452
448
  static{
453
449
  ({ e: [_initProto] } = _apply_decs_2203_r(this, [
454
450
  [
@@ -479,22 +475,7 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
479
475
  [
480
476
  _dec5,
481
477
  2,
482
- "validateRequestedBlockTxs"
483
- ],
484
- [
485
- _dec6,
486
- 2,
487
- "validateRequestedTxs"
488
- ],
489
- [
490
- _dec7,
491
- 2,
492
- "validateRequestedBlock"
493
- ],
494
- [
495
- _dec8,
496
- 2,
497
- "validateCheckpointAttestation"
478
+ "validateRequestedBlockTxsConsistency"
498
479
  ]
499
480
  ], []));
500
481
  }
@@ -506,9 +487,9 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
506
487
  checkpointAttestationValidator;
507
488
  protocolVersion;
508
489
  topicStrings;
509
- feesCache;
510
490
  /** Callback invoked when a duplicate proposal is detected (triggers slashing). */ duplicateProposalCallback;
511
491
  /** Callback invoked when a duplicate attestation is detected (triggers slashing). */ duplicateAttestationCallback;
492
+ /** Callback invoked when a valid checkpoint attestation is accepted into the pool. */ checkpointAttestationCallback;
512
493
  /**
513
494
  * Callback for when a block is received from a peer.
514
495
  * @param block - The block received from the peer.
@@ -518,13 +499,20 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
518
499
  * Callback for when a checkpoint proposal is received from a peer.
519
500
  * @param checkpoint - The checkpoint proposal received from the peer.
520
501
  * @returns The attestations for the checkpoint, if any.
521
- */ checkpointReceivedCallback;
502
+ */ allNodesCheckpointReceivedCallback;
503
+ /**
504
+ * Callback for when a checkpoint proposal is received - specifically for validators - from a peer.
505
+ * @param checkpoint - The checkpoint proposal received from the peer.
506
+ * @returns The attestations for the checkpoint, if any.
507
+ */ validatorCheckpointReceivedCallback;
522
508
  gossipSubEventHandler;
509
+ ipChangedHandler;
510
+ discoveredP2pIp;
523
511
  instrumentation;
524
512
  telemetry;
525
513
  logger;
526
- constructor(config, node, peerDiscoveryService, reqresp, peerManager, mempools, archiver, epochCache, proofVerifier, worldStateSynchronizer, telemetry, logger = createLogger('p2p:libp2p_service')){
527
- super(telemetry, 'LibP2PService'), this.config = config, this.node = node, this.peerDiscoveryService = peerDiscoveryService, this.reqresp = reqresp, this.peerManager = peerManager, this.mempools = mempools, this.archiver = archiver, this.epochCache = epochCache, this.proofVerifier = proofVerifier, this.worldStateSynchronizer = worldStateSynchronizer, this.msgIdSeenValidators = (_initProto(this), {}), this.protocolVersion = '', this.topicStrings = {};
514
+ constructor(config, node, peerDiscoveryService, reqresp, peerManager, mempools, archiver, epochCache, proofVerifier, worldStateSynchronizer, blockMinFeesProvider, telemetry, logger = createLogger('p2p:libp2p_service'), txValidationCache){
515
+ super(telemetry, 'LibP2PService'), this.config = config, this.node = node, this.peerDiscoveryService = peerDiscoveryService, this.reqresp = reqresp, this.peerManager = peerManager, this.mempools = mempools, this.archiver = archiver, this.epochCache = epochCache, this.proofVerifier = proofVerifier, this.worldStateSynchronizer = worldStateSynchronizer, this.blockMinFeesProvider = blockMinFeesProvider, this.txValidationCache = txValidationCache, this.msgIdSeenValidators = (_initProto(this), {}), this.protocolVersion = '', this.topicStrings = {};
528
516
  this.telemetry = telemetry;
529
517
  // Create child logger with fisherman prefix if in fisherman mode
530
518
  this.logger = config.fishermanMode ? logger.createChild('[FISHERMAN]') : logger;
@@ -540,29 +528,43 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
540
528
  this.topicStrings[TopicType.block_proposal] = createTopicString(TopicType.block_proposal, this.protocolVersion);
541
529
  this.topicStrings[TopicType.checkpoint_proposal] = createTopicString(TopicType.checkpoint_proposal, this.protocolVersion);
542
530
  this.topicStrings[TopicType.checkpoint_attestation] = createTopicString(TopicType.checkpoint_attestation, this.protocolVersion);
543
- this.blockProposalValidator = new BlockProposalValidator(epochCache, {
544
- txsPermitted: !config.disableTransactions,
545
- maxTxsPerBlock: config.maxTxsPerBlock
546
- });
547
- this.checkpointProposalValidator = new CheckpointProposalValidator(epochCache, {
531
+ const p2pPropagationTime = config.attestationPropagationTime;
532
+ const proposalValidatorOpts = {
548
533
  txsPermitted: !config.disableTransactions,
549
- maxTxsPerBlock: config.maxTxsPerBlock
550
- });
551
- this.checkpointAttestationValidator = config.fishermanMode ? new FishermanAttestationValidator(epochCache, mempools.attestationPool, telemetry) : new CheckpointAttestationValidator(epochCache);
534
+ maxTxsPerBlock: config.validateMaxTxsPerBlock ?? config.validateMaxTxsPerCheckpoint,
535
+ maxBlocksPerCheckpoint: config.maxBlocksPerCheckpoint,
536
+ p2pPropagationTime,
537
+ skipSlotValidation: config.skipProposalSlotValidation,
538
+ signatureContext: {
539
+ chainId: config.l1ChainId,
540
+ rollupAddress: config.rollupAddress
541
+ }
542
+ };
543
+ this.blockProposalValidator = new BlockProposalValidator(epochCache, proposalValidatorOpts);
544
+ this.checkpointProposalValidator = new CheckpointProposalValidator(epochCache, proposalValidatorOpts);
545
+ const attestationValidatorOpts = {
546
+ l1PublishingTime: config.l1PublishingTime,
547
+ p2pPropagationTime,
548
+ signatureContext: proposalValidatorOpts.signatureContext
549
+ };
550
+ this.checkpointAttestationValidator = config.fishermanMode ? new FishermanAttestationValidator(epochCache, mempools.attestationPool, telemetry, attestationValidatorOpts) : new CheckpointAttestationValidator(epochCache, attestationValidatorOpts);
552
551
  this.gossipSubEventHandler = this.handleGossipSubEvent.bind(this);
553
552
  this.blockReceivedCallback = async (block)=>{
554
- this.logger.debug(`Handler not yet registered: Block received callback not set. Received block for slot ${block.slotNumber} from peer.`, {
553
+ this.logger.warn(`Handler for block received not yet registered on P2P service. Received block ${block.blockNumber} for slot ${block.slotNumber} from peer.`, {
555
554
  p2pMessageIdentifier: await block.p2pMessageLoggingIdentifier()
556
555
  });
557
- return false;
556
+ return true;
557
+ };
558
+ this.allNodesCheckpointReceivedCallback = (_checkpoint)=>{
559
+ throw new CheckpointProposalReceivedCallbackNotRegisteredError();
558
560
  };
559
- this.checkpointReceivedCallback = (checkpoint)=>{
560
- this.logger.debug(`Handler not yet registered: Checkpoint received callback not set. Received checkpoint for slot ${checkpoint.slotNumber} from peer.`);
561
+ this.validatorCheckpointReceivedCallback = (_checkpoint)=>{
561
562
  return Promise.resolve(undefined);
562
563
  };
563
564
  }
564
565
  updateConfig(config) {
565
566
  this.reqresp.updateConfig(config);
567
+ this.config = merge(this.config, config);
566
568
  }
567
569
  /**
568
570
  * Creates an instance of the LibP2P service.
@@ -570,7 +572,7 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
570
572
  * @param txPool - The transaction pool to be accessed by the service.
571
573
  * @returns The new service.
572
574
  */ static async new(config, peerId, deps) {
573
- const { worldStateSynchronizer, epochCache, l2BlockSource, mempools, proofVerifier, peerStore, telemetry, logger, packageVersion } = deps;
575
+ const { worldStateSynchronizer, epochCache, l2BlockSource, mempools, proofVerifier, peerStore, blockMinFeesProvider, telemetry, logger, packageVersion, txValidationCache } = deps;
574
576
  const { p2pPort, maxPeerCount, listenAddress } = config;
575
577
  const bindAddrTcp = convertToMultiaddr(listenAddress, p2pPort, 'tcp');
576
578
  const datastore = new AztecDatastore(peerStore);
@@ -610,9 +612,12 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
610
612
  const l1Constants = epochCache.getL1Constants();
611
613
  const topicScoreParams = createAllTopicScoreParams(protocolVersion, {
612
614
  slotDurationMs: l1Constants.slotDuration * 1000,
615
+ ethereumSlotDuration: l1Constants.ethereumSlotDuration,
613
616
  heartbeatIntervalMs: config.gossipsubInterval,
614
617
  targetCommitteeSize: l1Constants.targetCommitteeSize,
615
618
  blockDurationMs: config.blockDurationMs,
619
+ l1PublishingTime: config.l1PublishingTime,
620
+ p2pPropagationTime: config.attestationPropagationTime,
616
621
  expectedBlockProposalsPerSlot: config.expectedBlockProposalsPerSlot
617
622
  });
618
623
  const node = await createLibp2p({
@@ -719,7 +724,8 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
719
724
  })
720
725
  }),
721
726
  components: (components)=>({
722
- connectionManager: components.connectionManager
727
+ connectionManager: components.connectionManager,
728
+ addressManager: components.addressManager
723
729
  })
724
730
  },
725
731
  logger: createLibp2pComponentLogger(logger.module, logger.getBindings())
@@ -727,6 +733,8 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
727
733
  const peerScoring = new PeerScoring(config, telemetry);
728
734
  const reqresp = new ReqResp(config, node, peerScoring, createLogger(`${logger.module}:reqresp`));
729
735
  const peerManager = new PeerManager(node, peerDiscoveryService, config, telemetry, createLogger(`${logger.module}:peer_manager`), peerScoring, reqresp, worldStateSynchronizer, protocolVersion, epochCache);
736
+ // Gate req/resp data protocols for unauthenticated peers when p2pAllowOnlyValidators is enabled
737
+ reqresp.setShouldRejectPeer((peerId)=>peerManager.shouldDisableP2PGossip(peerId));
730
738
  // Configure application-specific scoring for gossipsub.
731
739
  // The weight scales app score to align with gossipsub thresholds:
732
740
  // - Disconnect (-50) × 10 = -500 = gossipThreshold (stops receiving gossip)
@@ -734,7 +742,7 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
734
742
  // Note: positive topic scores can offset penalties, so alignment is best-effort.
735
743
  node.services.pubsub.score.params.appSpecificWeight = APP_SPECIFIC_WEIGHT;
736
744
  node.services.pubsub.score.params.appSpecificScore = (peerId)=>peerManager.shouldDisableP2PGossip(peerId) ? -Infinity : peerManager.getPeerScore(peerId);
737
- return new LibP2PService(config, node, peerDiscoveryService, reqresp, peerManager, mempools, l2BlockSource, epochCache, proofVerifier, worldStateSynchronizer, telemetry, logger);
745
+ return new LibP2PService(config, node, peerDiscoveryService, reqresp, peerManager, mempools, l2BlockSource, epochCache, proofVerifier, worldStateSynchronizer, blockMinFeesProvider, telemetry, logger, txValidationCache);
738
746
  }
739
747
  /**
740
748
  * Starts the LibP2P service.
@@ -744,22 +752,19 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
744
752
  if (this.node.status === 'started') {
745
753
  throw new Error('P2P service already started');
746
754
  }
747
- // Get listen & announce addresses for logging
748
755
  const { p2pIp, p2pPort } = this.config;
749
- if (!p2pIp) {
750
- throw new Error('Announce address not provided.');
756
+ if (!p2pIp && !this.config.queryForIp) {
757
+ throw new Error('Announce address not provided and queryForIp is not enabled.');
751
758
  }
752
- const announceTcpMultiaddr = convertToMultiaddr(p2pIp, p2pPort, 'tcp');
759
+ const announceTcpMultiaddr = p2pIp ? convertToMultiaddr(p2pIp, p2pPort, 'tcp') : undefined;
753
760
  // Create request response protocol handlers
754
761
  const txHandler = reqRespTxHandler(this.mempools);
755
762
  const goodbyeHandler = reqGoodbyeHandler(this.peerManager);
756
- const blockHandler = reqRespBlockHandler(this.archiver);
757
763
  const statusHandler = reqRespStatusHandler(this.protocolVersion, this.worldStateSynchronizer, this.logger);
758
764
  const requestResponseHandlers = {
759
765
  [ReqRespSubProtocol.PING]: pingHandler,
760
766
  [ReqRespSubProtocol.STATUS]: statusHandler.bind(this),
761
- [ReqRespSubProtocol.GOODBYE]: goodbyeHandler.bind(this),
762
- [ReqRespSubProtocol.BLOCK]: blockHandler.bind(this)
767
+ [ReqRespSubProtocol.GOODBYE]: goodbyeHandler.bind(this)
763
768
  };
764
769
  if (!this.config.disableTransactions) {
765
770
  const blockTxsHandler = reqRespBlockTxsHandler(this.mempools.attestationPool, this.archiver, this.mempools.txPool);
@@ -768,15 +773,8 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
768
773
  if (!this.config.disableTransactions) {
769
774
  requestResponseHandlers[ReqRespSubProtocol.TX] = txHandler.bind(this);
770
775
  }
771
- // Define the sub protocol validators - This is done within this start() method to gain a callback to the existing validateTx function
772
- const reqrespSubProtocolValidators = {
773
- ...DEFAULT_SUB_PROTOCOL_VALIDATORS,
774
- [ReqRespSubProtocol.TX]: this.validateRequestedTxs.bind(this),
775
- [ReqRespSubProtocol.BLOCK_TXS]: this.validateRequestedBlockTxs.bind(this),
776
- [ReqRespSubProtocol.BLOCK]: this.validateRequestedBlock.bind(this)
777
- };
778
776
  await this.peerManager.initializePeers();
779
- await this.reqresp.start(requestResponseHandlers, reqrespSubProtocolValidators);
777
+ await this.reqresp.start(requestResponseHandlers);
780
778
  await this.node.start();
781
779
  // Subscribe to standard GossipSub topics by default
782
780
  for (const topic of getTopicsForConfig(this.config.disableTransactions)){
@@ -788,6 +786,34 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
788
786
  if (!this.config.p2pDiscoveryDisabled) {
789
787
  await this.peerDiscoveryService.start();
790
788
  }
789
+ // Bridge discv5 IP changes to libp2p's AddressManager so peers see the updated address
790
+ if (this.config.queryForIp) {
791
+ this.discoveredP2pIp = this.config.p2pIp;
792
+ this.logger.info('IP change tracking enabled, bridging discv5 IP updates to libp2p AddressManager');
793
+ this.ipChangedHandler = (ip)=>{
794
+ const addressManager = this.node.services.components.addressManager;
795
+ const newAddr = multiaddr(convertToMultiaddr(ip, this.config.p2pPort, 'tcp'));
796
+ const previousIp = this.discoveredP2pIp;
797
+ if (previousIp) {
798
+ const oldAddr = multiaddr(convertToMultiaddr(previousIp, this.config.p2pPort, 'tcp'));
799
+ addressManager.removeObservedAddr(oldAddr);
800
+ this.logger.info('Libp2p announce address updated due to IP change', {
801
+ previousIp,
802
+ newIp: ip,
803
+ newMultiaddr: newAddr.toString()
804
+ });
805
+ } else {
806
+ this.logger.info('Libp2p announce address set from initial discv5 IP discovery', {
807
+ ip,
808
+ multiaddr: newAddr.toString()
809
+ });
810
+ }
811
+ addressManager.addObservedAddr(newAddr);
812
+ addressManager.confirmObservedAddr(newAddr);
813
+ this.discoveredP2pIp = ip;
814
+ };
815
+ this.peerDiscoveryService.on('ip:changed', this.ipChangedHandler);
816
+ }
791
817
  this.discoveryRunningPromise = new RunningPromise(async ()=>{
792
818
  await this.peerManager.heartbeat();
793
819
  }, this.logger, this.config.peerCheckIntervalMS);
@@ -805,6 +831,10 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
805
831
  */ async stop() {
806
832
  // Remove gossip sub listener
807
833
  this.node.services.pubsub.removeEventListener(GossipSubEvent.MESSAGE, this.gossipSubEventHandler);
834
+ if (this.ipChangedHandler) {
835
+ this.peerDiscoveryService.removeListener('ip:changed', this.ipChangedHandler);
836
+ this.ipChangedHandler = undefined;
837
+ }
808
838
  // Stop peer manager
809
839
  this.logger.debug('Stopping peer manager...');
810
840
  await this.peerManager.stop();
@@ -818,8 +848,8 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
818
848
  await this.stopLibP2P();
819
849
  this.logger.info('LibP2P service stopped');
820
850
  }
821
- addReqRespSubProtocol(subProtocol, handler, validator) {
822
- return this.reqresp.addSubProtocol(subProtocol, handler, validator);
851
+ addReqRespSubProtocol(subProtocol, handler) {
852
+ return this.reqresp.addSubProtocol(subProtocol, handler);
823
853
  }
824
854
  registerThisValidatorAddresses(address) {
825
855
  this.peerManager.registerThisValidatorAddresses(address);
@@ -841,14 +871,6 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
841
871
  };
842
872
  setImmediate(()=>void safeJob());
843
873
  }
844
- /**
845
- * Send a batch of requests to peers, and return the responses
846
- * @param protocol - The request response protocol to use
847
- * @param requests - The requests to send to the peers
848
- * @returns The responses to the requests
849
- */ sendBatchRequest(protocol, requests, pinnedPeerId) {
850
- return this.reqresp.sendBatchRequest(protocol, requests, pinnedPeerId);
851
- }
852
874
  sendRequestToPeer(peerId, subProtocol, payload, dialTimeout) {
853
875
  return this.reqresp.sendRequestToPeer(peerId, subProtocol, payload, dialTimeout);
854
876
  }
@@ -861,8 +883,11 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
861
883
  registerBlockReceivedCallback(callback) {
862
884
  this.blockReceivedCallback = callback;
863
885
  }
864
- registerCheckpointReceivedCallback(callback) {
865
- this.checkpointReceivedCallback = callback;
886
+ registerValidatorCheckpointReceivedCallback(callback) {
887
+ this.validatorCheckpointReceivedCallback = callback;
888
+ }
889
+ registerAllNodesCheckpointReceivedCallback(callback) {
890
+ this.allNodesCheckpointReceivedCallback = callback;
866
891
  }
867
892
  /**
868
893
  * Registers a callback to be invoked when a duplicate proposal is detected.
@@ -877,6 +902,9 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
877
902
  */ registerDuplicateAttestationCallback(callback) {
878
903
  this.duplicateAttestationCallback = callback;
879
904
  }
905
+ registerCheckpointAttestationCallback(callback) {
906
+ this.checkpointAttestationCallback = callback;
907
+ }
880
908
  /**
881
909
  * Subscribes to a topic.
882
910
  * @param topic - The topic to subscribe to.
@@ -928,6 +956,12 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
928
956
  if (!validator || !validator.addMessage(msgId)) {
929
957
  this.instrumentation.incMessagePrevalidationStatus(false, topicType);
930
958
  this.node.services.pubsub.reportMessageValidationResult(msgId, source.toString(), TopicValidatorResult.Ignore);
959
+ if (topicType === TopicType.tx) {
960
+ this.logger.verbose(`Ignoring already-seen tx gossip message`, {
961
+ msgId,
962
+ source: source.toString()
963
+ });
964
+ }
931
965
  return {
932
966
  result: false,
933
967
  topicType
@@ -985,6 +1019,13 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
985
1019
  }
986
1020
  // Process the message, optionally within a linked span for trace propagation
987
1021
  const processMessage = async ()=>{
1022
+ if (this.config.skipIncomingProposals && (msg.topic === this.topicStrings[TopicType.block_proposal] || msg.topic === this.topicStrings[TopicType.checkpoint_proposal])) {
1023
+ this.logger.warn(`Ignoring incoming proposal (skipIncomingProposals is set)`, {
1024
+ topic: msg.topic
1025
+ });
1026
+ this.node.services.pubsub.reportMessageValidationResult(msgId, source.toString(), TopicValidatorResult.Ignore);
1027
+ return;
1028
+ }
988
1029
  if (msg.topic === this.topicStrings[TopicType.tx]) {
989
1030
  await this.handleGossipedTx(p2pMessage.payload, msgId, source);
990
1031
  } else if (msg.topic === this.topicStrings[TopicType.checkpoint_attestation]) {
@@ -1033,29 +1074,79 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
1033
1074
  return;
1034
1075
  }
1035
1076
  async validateReceivedMessage(validationFunc, msgId, source, topicType) {
1077
+ // Default to reject result with a penalty if validation function throws an error
1036
1078
  let resultAndObj = {
1037
- result: TopicValidatorResult.Reject
1079
+ result: TopicValidatorResult.Reject,
1080
+ severity: PeerErrorSeverity.MidToleranceError
1038
1081
  };
1039
1082
  const timer = new Timer();
1040
1083
  try {
1041
1084
  resultAndObj = await validationFunc();
1042
1085
  } catch (err) {
1043
- this.peerManager.penalizePeer(source, PeerErrorSeverity.LowToleranceError);
1044
- this.logger.error(`Error deserializing and validating gossipsub message`, err, {
1086
+ this.logger.error(`Error validating gossipsub message`, err, {
1045
1087
  msgId,
1046
1088
  source: source.toString(),
1047
1089
  topicType
1048
1090
  });
1049
1091
  }
1092
+ const validationTimeMs = timer.ms();
1093
+ const mcacheWindowMs = this.config.gossipsubMcacheLength * this.config.gossipsubInterval;
1094
+ if (validationTimeMs > mcacheWindowMs * 0.75) {
1095
+ this.instrumentation.incSlowValidation(topicType);
1096
+ this.logger.warn(`Gossip validation for ${topicType} took ${validationTimeMs}ms, approaching mcache eviction window of ${mcacheWindowMs}ms. ` + `Message forwarding may be skipped if validation exceeds the window.`, {
1097
+ msgId,
1098
+ source: source.toString(),
1099
+ topicType,
1100
+ validationTimeMs,
1101
+ mcacheWindowMs
1102
+ });
1103
+ }
1050
1104
  if (resultAndObj.result === TopicValidatorResult.Accept) {
1105
+ this.logger.debug(`Message ${topicType} accepted by validator`, {
1106
+ msgId,
1107
+ source: source.toString(),
1108
+ topicType
1109
+ });
1051
1110
  this.instrumentation.recordMessageValidation(topicType, timer);
1111
+ } else if (resultAndObj.result === TopicValidatorResult.Reject) {
1112
+ this.logger.warn(`Message ${topicType} rejected by validator with severity ${resultAndObj.severity}`, {
1113
+ msgId,
1114
+ source: source.toString(),
1115
+ topicType,
1116
+ severity: resultAndObj.severity
1117
+ });
1118
+ this.peerManager.penalizePeer(source, resultAndObj.severity);
1119
+ } else {
1120
+ this.logger.trace(`Message ${topicType} ignored by validator`, {
1121
+ msgId,
1122
+ source: source.toString(),
1123
+ topicType
1124
+ });
1052
1125
  }
1053
1126
  this.node.services.pubsub.reportMessageValidationResult(msgId, source.toString(), resultAndObj.result);
1054
1127
  return resultAndObj;
1055
1128
  }
1129
+ tryDeserialize(deserializeFunc, msgId, source) {
1130
+ try {
1131
+ return deserializeFunc();
1132
+ } catch (err) {
1133
+ this.logger.warn(`Failed to deserialize gossipsub message from buffer`, {
1134
+ err,
1135
+ msgId,
1136
+ source: source.toString()
1137
+ });
1138
+ return undefined;
1139
+ }
1140
+ }
1056
1141
  async handleGossipedTx(payloadData, msgId, source) {
1057
1142
  const validationFunc = async ()=>{
1058
- const tx = Tx.fromBuffer(payloadData);
1143
+ const tx = this.tryDeserialize(()=>Tx.fromBuffer(payloadData), msgId, source);
1144
+ if (!tx) {
1145
+ return {
1146
+ result: TopicValidatorResult.Reject,
1147
+ severity: PeerErrorSeverity.LowToleranceError
1148
+ };
1149
+ }
1059
1150
  const currentBlockNumber = await this.archiver.getBlockNumber();
1060
1151
  const { ts: nextSlotTimestamp } = this.epochCache.getEpochAndSlotInNextL1Slot();
1061
1152
  // Stage 1: fast validators (metadata, data, timestamps, double-spend, gas, phases, block header)
@@ -1071,14 +1162,22 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
1071
1162
  const txBlockNumber = BlockNumber(currentBlockNumber + 1);
1072
1163
  severity = await this.handleDoubleSpendFailure(tx, txBlockNumber);
1073
1164
  }
1074
- this.peerManager.penalizePeer(source, severity);
1165
+ this.logger.verbose(`Rejecting gossiped tx ${tx.getTxHash().toString()}: stage 1 validation failed`, {
1166
+ validator: name,
1167
+ severity,
1168
+ source: source.toString()
1169
+ });
1075
1170
  return {
1076
- result: TopicValidatorResult.Reject
1171
+ result: TopicValidatorResult.Reject,
1172
+ severity
1077
1173
  };
1078
1174
  }
1079
1175
  // Pool pre-check: see if the pool would accept this tx before doing expensive proof verification
1080
1176
  const canAdd = await this.mempools.txPool.canAddPendingTx(tx);
1081
1177
  if (canAdd === 'ignored') {
1178
+ this.logger.verbose(`Ignoring gossiped tx ${tx.getTxHash().toString()}: pool pre-check returned ignored`, {
1179
+ source: source.toString()
1180
+ });
1082
1181
  return {
1083
1182
  result: TopicValidatorResult.Ignore,
1084
1183
  obj: tx
@@ -1088,10 +1187,15 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
1088
1187
  const secondStageValidators = this.createSecondStageMessageValidators();
1089
1188
  const secondStageOutcome = await this.runValidations(tx, secondStageValidators);
1090
1189
  if (!secondStageOutcome.allPassed) {
1091
- const { severity } = secondStageOutcome.failure;
1092
- this.peerManager.penalizePeer(source, severity);
1190
+ const { severity, name } = secondStageOutcome.failure;
1191
+ this.logger.verbose(`Rejecting gossiped tx ${tx.getTxHash().toString()}: stage 2 validation failed`, {
1192
+ validator: name,
1193
+ severity,
1194
+ source: source.toString()
1195
+ });
1093
1196
  return {
1094
- result: TopicValidatorResult.Reject
1197
+ result: TopicValidatorResult.Reject,
1198
+ severity
1095
1199
  };
1096
1200
  }
1097
1201
  // Pool add: persist the tx
@@ -1103,7 +1207,7 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
1103
1207
  });
1104
1208
  const wasAccepted = addResult.accepted.some((h)=>h.equals(txHash));
1105
1209
  const wasIgnored = addResult.ignored.some((h)=>h.equals(txHash));
1106
- this.logger.trace(`Validate propagated tx`, {
1210
+ this.logger.verbose(`Validate propagated tx ${txHash.toString()}`, {
1107
1211
  wasAccepted,
1108
1212
  wasIgnored,
1109
1213
  [Attributes.P2P_ID]: source.toString()
@@ -1119,8 +1223,13 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
1119
1223
  obj: tx
1120
1224
  };
1121
1225
  } else {
1226
+ this.logger.warn(`Gossiped tx ${txHash.toString()} unexpectedly rejected by pool`, {
1227
+ source: source.toString(),
1228
+ txHash: txHash.toString()
1229
+ });
1122
1230
  return {
1123
- result: TopicValidatorResult.Reject
1231
+ result: TopicValidatorResult.Reject,
1232
+ severity: PeerErrorSeverity.HighToleranceError
1124
1233
  };
1125
1234
  }
1126
1235
  };
@@ -1141,7 +1250,16 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
1141
1250
  * Process a checkpoint attestation from a peer.
1142
1251
  * Validates the attestation and adds it to the pool.
1143
1252
  */ async processCheckpointAttestationFromPeer(payloadData, msgId, source) {
1144
- const { result, obj: attestation } = await this.validateReceivedMessage(()=>this.validateAndStoreCheckpointAttestation(source, CheckpointAttestation.fromBuffer(payloadData)), msgId, source, TopicType.checkpoint_attestation);
1253
+ const { result, obj: attestation } = await this.validateReceivedMessage(()=>{
1254
+ const attestation = this.tryDeserialize(()=>CheckpointAttestation.fromBuffer(payloadData), msgId, source);
1255
+ if (!attestation) {
1256
+ return Promise.resolve({
1257
+ result: TopicValidatorResult.Reject,
1258
+ severity: PeerErrorSeverity.LowToleranceError
1259
+ });
1260
+ }
1261
+ return this.validateAndStoreCheckpointAttestation(source, attestation);
1262
+ }, msgId, source, TopicType.checkpoint_attestation);
1145
1263
  if (result !== TopicValidatorResult.Accept || !attestation) {
1146
1264
  return;
1147
1265
  }
@@ -1156,9 +1274,9 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
1156
1274
  const validationResult = await this.checkpointAttestationValidator.validate(attestation);
1157
1275
  if (validationResult.result === 'reject') {
1158
1276
  this.logger.warn(`Penalizing peer ${peerId} for checkpoint attestation validation failure`);
1159
- this.peerManager.penalizePeer(peerId, validationResult.severity);
1160
1277
  return {
1161
- result: TopicValidatorResult.Reject
1278
+ result: TopicValidatorResult.Reject,
1279
+ severity: validationResult.severity
1162
1280
  };
1163
1281
  }
1164
1282
  if (validationResult.result === 'ignore') {
@@ -1185,9 +1303,9 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
1185
1303
  obj: attestation
1186
1304
  };
1187
1305
  }
1188
- // Could not add (cap reached for signer), no need to re-broadcast
1306
+ // Could not add (cap reached for signer), penalize and do not re-broadcast
1189
1307
  if (!added) {
1190
- this.logger.warn(`Dropping checkpoint attestation due to cap`, {
1308
+ this.logger.warn(`Rejecting checkpoint attestation due to cap`, {
1191
1309
  slot: slot.toString(),
1192
1310
  archive: attestation.archive.toString(),
1193
1311
  source: peerId.toString(),
@@ -1195,8 +1313,8 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
1195
1313
  count
1196
1314
  });
1197
1315
  return {
1198
- result: TopicValidatorResult.Ignore,
1199
- obj: attestation
1316
+ result: TopicValidatorResult.Reject,
1317
+ severity: PeerErrorSeverity.HighToleranceError
1200
1318
  };
1201
1319
  }
1202
1320
  // Check if this is a duplicate attestation (signer attested to a different proposal at the same slot)
@@ -1217,6 +1335,7 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
1217
1335
  }
1218
1336
  }
1219
1337
  // Attestation was added successfully - accept it so other nodes can also detect the equivocation
1338
+ this.checkpointAttestationCallback?.(attestation);
1220
1339
  return {
1221
1340
  result: TopicValidatorResult.Accept,
1222
1341
  obj: attestation
@@ -1234,9 +1353,9 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
1234
1353
  const validationResult = await this.blockProposalValidator.validate(block);
1235
1354
  if (validationResult.result === 'reject') {
1236
1355
  this.logger.warn(`Penalizing peer ${peerId} for block proposal validation failure`);
1237
- this.peerManager.penalizePeer(peerId, validationResult.severity);
1238
1356
  return {
1239
- result: TopicValidatorResult.Reject
1357
+ result: TopicValidatorResult.Reject,
1358
+ severity: validationResult.severity
1240
1359
  };
1241
1360
  }
1242
1361
  if (validationResult.result === 'ignore') {
@@ -1266,7 +1385,6 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
1266
1385
  }
1267
1386
  // Too many blocks received for this slot and index, penalize peer and do not re-broadcast
1268
1387
  if (!added) {
1269
- this.peerManager.penalizePeer(peerId, PeerErrorSeverity.HighToleranceError);
1270
1388
  this.logger.warn(`Penalizing peer for block proposal exceeding per-position cap`, {
1271
1389
  ...block.toBlockInfo(),
1272
1390
  indexWithinCheckpoint: block.indexWithinCheckpoint,
@@ -1278,7 +1396,8 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
1278
1396
  result: TopicValidatorResult.Reject,
1279
1397
  metadata: {
1280
1398
  isEquivocated
1281
- }
1399
+ },
1400
+ severity: PeerErrorSeverity.HighToleranceError
1282
1401
  };
1283
1402
  }
1284
1403
  // If this was a duplicate proposal, do not process it, but do invoke the duplicate callback,
@@ -1327,7 +1446,7 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
1327
1446
  // Note: Validators do NOT attest to individual blocks, only to checkpoint proposals.
1328
1447
  const isValid = await this.blockReceivedCallback(block, sender);
1329
1448
  if (!isValid) {
1330
- this.logger.warn(`Block proposal validation failed for block ${block.blockNumber}`, block.toBlockInfo());
1449
+ this.logger.info(`Block proposal validation failed for block ${block.blockNumber}`, block.toBlockInfo());
1331
1450
  }
1332
1451
  }
1333
1452
  /**
@@ -1335,15 +1454,24 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
1335
1454
  * Validates and processes the checkpoint proposal, then triggers the callback for attestation.
1336
1455
  */ async handleGossipedCheckpointProposal(payloadData, msgId, source) {
1337
1456
  const { result, obj: checkpoint, metadata: { isEquivocated, processBlock } = {} } = await this.validateReceivedMessage(()=>this.validateAndStoreCheckpointProposal(source, CheckpointProposal.fromBuffer(payloadData)), msgId, source, TopicType.checkpoint_proposal);
1457
+ // Process checkpoint proposal if valid and not equivocated.
1458
+ const processCheckpointFn = ()=>result === TopicValidatorResult.Accept && checkpoint && !isEquivocated ? this.processValidCheckpointProposal(checkpoint.toCore(), source) : Promise.resolve();
1338
1459
  // If the checkpoint contained a valid last block, we process it even if the checkpoint itself is to be rejected
1339
1460
  // TODO(palla/mbps): Is this ok? Should we be considering a block from a checkpoint that was equivocated?
1340
- if (processBlock && checkpoint?.getBlockProposal()) {
1341
- await this.processValidBlockProposal(checkpoint.getBlockProposal(), source);
1342
- }
1343
- if (result !== TopicValidatorResult.Accept || !checkpoint || isEquivocated) {
1461
+ const processBlockFn = ()=>processBlock && checkpoint && checkpoint.getBlockProposal() ? this.processValidBlockProposal(checkpoint.getBlockProposal(), source) : Promise.resolve();
1462
+ // A node that skips checkpoint validation attests without re-executing the embedded last block, so run
1463
+ // the checkpoint callback first: this creates and broadcasts the attestation before the block is
1464
+ // processed. Otherwise the block's re-execution — which can stall until the re-execution deadline
1465
+ // waiting for a parent that may never arrive — would delay the attestation past the slot's attestation
1466
+ // window, after which peers reject it as stale.
1467
+ if (this.config.skipCheckpointProposalValidation) {
1468
+ await processCheckpointFn();
1469
+ await processBlockFn();
1344
1470
  return;
1345
1471
  }
1346
- await this.processValidCheckpointProposal(checkpoint.toCore(), source);
1472
+ // Process the block first, since it's required for the checkpoint proposal validation.
1473
+ await processBlockFn();
1474
+ await processCheckpointFn();
1347
1475
  }
1348
1476
  /**
1349
1477
  * Validates a checkpoint proposal. Penalizes peer if validation fails. Adds the checkpoint and
@@ -1352,9 +1480,9 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
1352
1480
  const validationResult = await this.checkpointProposalValidator.validate(checkpoint);
1353
1481
  if (validationResult.result === 'reject') {
1354
1482
  this.logger.warn(`Penalizing peer ${peerId} for checkpoint proposal validation failure`);
1355
- this.peerManager.penalizePeer(peerId, validationResult.severity);
1356
1483
  return {
1357
- result: TopicValidatorResult.Reject
1484
+ result: TopicValidatorResult.Reject,
1485
+ severity: validationResult.severity
1358
1486
  };
1359
1487
  }
1360
1488
  if (validationResult.result === 'ignore') {
@@ -1371,18 +1499,20 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
1371
1499
  [Attributes.SLOT_NUMBER]: checkpoint.slotNumber.toString(),
1372
1500
  [Attributes.P2P_ID]: peerId.toString()
1373
1501
  });
1374
- const { result, obj, metadata: { isEquivocated } = {} } = await this.validateAndStoreBlockProposal(peerId, blockProposal);
1375
- if (result === TopicValidatorResult.Reject || !obj || isEquivocated) {
1502
+ const blockProposalResult = await this.validateAndStoreBlockProposal(peerId, blockProposal);
1503
+ const { obj, metadata: { isEquivocated } = {} } = blockProposalResult;
1504
+ if (blockProposalResult.result === TopicValidatorResult.Reject || !obj || isEquivocated) {
1376
1505
  this.logger.debug(`Rejecting checkpoint due to invalid last block proposal`, {
1377
1506
  [Attributes.SLOT_NUMBER]: checkpoint.slotNumber.toString(),
1378
1507
  [Attributes.P2P_ID]: peerId.toString(),
1379
1508
  isEquivocated,
1380
- result
1509
+ result: blockProposalResult.result
1381
1510
  });
1382
1511
  return {
1383
- result: TopicValidatorResult.Reject
1512
+ result: TopicValidatorResult.Reject,
1513
+ severity: 'severity' in blockProposalResult ? blockProposalResult.severity : PeerErrorSeverity.MidToleranceError
1384
1514
  };
1385
- } else if (result === TopicValidatorResult.Accept && obj && !isEquivocated) {
1515
+ } else if (blockProposalResult.result === TopicValidatorResult.Accept && obj && !isEquivocated) {
1386
1516
  processBlock = true;
1387
1517
  }
1388
1518
  }
@@ -1409,7 +1539,6 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
1409
1539
  // Too many checkpoint proposals received for this slot, penalize peer and do not re-broadcast
1410
1540
  // Note: We still return the checkpoint obj so the lastBlock can be processed if valid
1411
1541
  if (!added) {
1412
- this.peerManager.penalizePeer(peerId, PeerErrorSeverity.HighToleranceError);
1413
1542
  this.logger.warn(`Penalizing peer for checkpoint proposal exceeding per-slot cap`, {
1414
1543
  ...checkpoint.toCheckpointInfo(),
1415
1544
  count,
@@ -1421,7 +1550,8 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
1421
1550
  metadata: {
1422
1551
  isEquivocated,
1423
1552
  processBlock
1424
- }
1553
+ },
1554
+ severity: PeerErrorSeverity.HighToleranceError
1425
1555
  };
1426
1556
  }
1427
1557
  // If this was a duplicate proposal, do not process it, but do invoke the duplicate callback,
@@ -1471,9 +1601,10 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
1471
1601
  archive: checkpoint.archive.toString(),
1472
1602
  source: sender.toString()
1473
1603
  });
1604
+ await this.allNodesCheckpointReceivedCallback(checkpoint, sender);
1474
1605
  // Call the checkpoint received callback with the core version (without lastBlock)
1475
1606
  // to validate and potentially generate attestations
1476
- const attestations = await this.checkpointReceivedCallback(checkpoint, sender);
1607
+ const attestations = await this.validatorCheckpointReceivedCallback(checkpoint, sender);
1477
1608
  if (attestations && attestations.length > 0) {
1478
1609
  // If the callback returned attestations, add them to the pool and propagate them
1479
1610
  await this.mempools.attestationPool.addOwnCheckpointAttestations(attestations);
@@ -1497,62 +1628,66 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
1497
1628
  });
1498
1629
  }
1499
1630
  /**
1500
- * Validate the requested block transactions. Allow partial returns.
1631
+ * Validate the requested block transactions request-response consistency.
1632
+ * It does NOT validate the transactions themselves.
1501
1633
  * @param request - The block transactions request.
1502
1634
  * @param response - The block transactions response.
1503
1635
  * @param peerId - The ID of the peer that made the request.
1504
- * @returns True if the requested block transactions are valid, false otherwise.
1505
- */ async validateRequestedBlockTxs(request, response, peerId) {
1506
- const requestedTxValidator = this.createRequestedTxValidator();
1636
+ * @returns True if the request-response is consistent, false otherwise.
1637
+ */ async validateRequestedBlockTxsConsistency(request, response, peerId) {
1507
1638
  try {
1508
- if (!response.archiveRoot.equals(request.archiveRoot)) {
1509
- this.peerManager.penalizePeer(peerId, PeerErrorSeverity.MidToleranceError);
1510
- throw new ValidationError(`Received block txs for unexpected archive root: expected ${request.archiveRoot.toString()}, got ${response.archiveRoot.toString()}`);
1511
- }
1512
- if (response.txIndices.getLength() !== request.txIndices.getLength()) {
1513
- this.peerManager.penalizePeer(peerId, PeerErrorSeverity.MidToleranceError);
1514
- throw new ValidationError(`Received block txs with mismatched bitvector length: expected ${request.txIndices.getLength()}, got ${response.txIndices.getLength()}`);
1515
- }
1516
- // Check no duplicates and not exceeding returnable count
1517
- const requestedIndices = new Set(request.txIndices.getTrueIndices());
1518
- const availableIndices = new Set(response.txIndices.getTrueIndices());
1519
- const maxReturnable = [
1520
- ...requestedIndices
1521
- ].filter((i)=>availableIndices.has(i)).length;
1522
- const returnedHashes = await Promise.all(response.txs.map((tx)=>tx.getTxHash().toString()));
1639
+ // Check for duplicates txs (or hashes) in the response.
1640
+ const returnedHashes = response.txs.map((tx)=>tx.getTxHash().toString());
1523
1641
  const uniqueReturned = new Set(returnedHashes.map((h)=>h.toString()));
1524
1642
  if (uniqueReturned.size !== returnedHashes.length) {
1525
1643
  this.peerManager.penalizePeer(peerId, PeerErrorSeverity.MidToleranceError);
1526
1644
  throw new ValidationError(`Received duplicate txs in block txs response`);
1527
1645
  }
1528
- if (response.txs.length > maxReturnable) {
1646
+ // We get the block tx hashes from the proposal or the archiver.
1647
+ const proposal = await this.mempools.attestationPool.getBlockProposalByArchive(request.archiveRoot.toString());
1648
+ const blockTxHashes = proposal?.txHashes ?? (await this.archiver.getBlock({
1649
+ archive: request.archiveRoot
1650
+ }))?.body.txEffects.map((e)=>e.txHash);
1651
+ // If we don't have the block, we can't verify membership/order of the returned txs.
1652
+ if (!blockTxHashes) {
1653
+ // This shouldn't happen, since we asked for the block (proposal).
1654
+ // Neither a local proposal nor an archived block: we cannot verify membership/order of the
1655
+ // returned txs. This is a local-state gap, not a peer fault, so we do not penalize.
1656
+ this.logger.warn(`Block ${request.archiveRoot.toString()} not found in attestation pool or archiver; cannot validate membership/order of returned txs`);
1657
+ // NOTE: We mark the response as invalid, given the limitations of a true/false return value.
1658
+ return false;
1659
+ }
1660
+ // Verify that the returned tx hashes are a subset of (tx hashes by index) U (explicitly requested tx hashes).
1661
+ const uniqueRequestedHashes = new Set([
1662
+ // tx hashes requested by index.
1663
+ ...request.txIndices.getTrueIndices().map((i)=>blockTxHashes[i].toString()),
1664
+ // explicitly requested tx hashes.
1665
+ ...request.txHashes.map((h)=>h.toString())
1666
+ ]);
1667
+ if (!returnedHashes.every((h)=>uniqueRequestedHashes.has(h))) {
1668
+ this.peerManager.penalizePeer(peerId, PeerErrorSeverity.LowToleranceError);
1669
+ throw new ValidationError('Returned txs should be a subset of (tx hashes by index) U (explicitly requested tx hashes)');
1670
+ }
1671
+ // Tx indices information is optional, but if present, we need to verify a few things.
1672
+ if (!response.peerHasBlock()) {
1673
+ this.logger.debug(`Peer ${peerId.toString()} signalled missing block`);
1674
+ return true;
1675
+ }
1676
+ // If the response has a non-empty bitvector, it needs to be consistent with the number of txs in the block.
1677
+ if (response.txIndices.getLength() !== blockTxHashes.length) {
1529
1678
  this.peerManager.penalizePeer(peerId, PeerErrorSeverity.MidToleranceError);
1530
- throw new ValidationError(`Received more txs (${response.txs.length}) than requested-and-available (${maxReturnable})`);
1679
+ throw new ValidationError(`Received block txs with mismatched bitvector length: expected ${blockTxHashes.length}, got ${response.txIndices.getLength()}`);
1531
1680
  }
1532
- // Given proposal (should have locally), ensure returned txs are valid subset and match request indices
1533
- const proposal = await this.mempools.attestationPool.getBlockProposal(request.archiveRoot.toString());
1534
- if (proposal) {
1535
- // Build intersected indices
1536
- const intersectIdx = request.txIndices.getTrueIndices().filter((i)=>response.txIndices.isSet(i));
1537
- // Enforce subset membership and preserve increasing order by index.
1538
- const hashToIndexInProposal = new Map(proposal.txHashes.map((h, i)=>[
1539
- h.toString(),
1540
- i
1541
- ]));
1542
- const allowedIndexSet = new Set(intersectIdx);
1543
- const indices = returnedHashes.map((h)=>hashToIndexInProposal.get(h));
1544
- const allAllowed = indices.every((idx)=>idx !== undefined && allowedIndexSet.has(idx));
1545
- const strictlyIncreasing = indices.every((idx, i)=>i === 0 ? idx !== undefined : idx > indices[i - 1]);
1546
- if (!allAllowed || !strictlyIncreasing) {
1547
- this.peerManager.penalizePeer(peerId, PeerErrorSeverity.LowToleranceError);
1548
- throw new ValidationError('Returned txs do not match expected subset/order for requested indices');
1549
- }
1550
- } else {
1551
- // No local proposal, cannot check the membership/order of the returned txs
1552
- this.logger.warn(`Block proposal not found for archive root ${request.archiveRoot.toString()}; cannot validate membership/order of returned txs`);
1553
- return false;
1681
+ // For every index we requested that the peer claims to have (per its bitvector), the
1682
+ // corresponding tx must be present in the response. A peer advertising availability but
1683
+ // withholding the tx is inconsistent.
1684
+ const returnedHashSet = new Set(returnedHashes);
1685
+ const expectedIndices = request.txIndices.getTrueIndices().filter((i)=>response.txIndices.isSet(i));
1686
+ const missingExpected = expectedIndices.some((i)=>!returnedHashSet.has(blockTxHashes[i].toString()));
1687
+ if (missingExpected) {
1688
+ this.peerManager.penalizePeer(peerId, PeerErrorSeverity.LowToleranceError);
1689
+ throw new ValidationError('Peer advertised requested txs via indices but did not return them');
1554
1690
  }
1555
- await Promise.all(response.txs.map((tx)=>this.validateRequestedTx(tx, peerId, requestedTxValidator)));
1556
1691
  return true;
1557
1692
  } catch (e) {
1558
1693
  if (e instanceof ValidationError) {
@@ -1563,104 +1698,8 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
1563
1698
  return false;
1564
1699
  }
1565
1700
  }
1566
- /**
1567
- * Validate a collection of txs that has been requested from a peer.
1568
- *
1569
- * The core component of this validator is that each tx hash MUST match the requested tx hash,
1570
- * In order to perform this check, the tx proof must be verified.
1571
- *
1572
- * Note: This function is called from within `ReqResp.sendRequest` as part of the
1573
- * ReqRespSubProtocol.TX subprotocol validation.
1574
- *
1575
- * @param requestedTxHash - The collection of the txs that was requested.
1576
- * @param responseTx - The collection of txs that was received as a response to the request.
1577
- * @param peerId - The peer ID of the peer that sent the tx.
1578
- * @returns True if the whole collection of txs is valid, false otherwise.
1579
- */ async validateRequestedTxs(requestedTxHash, responseTx, peerId) {
1580
- const requested = new Set(requestedTxHash.map((h)=>h.toString()));
1581
- const requestedTxValidator = this.createRequestedTxValidator();
1582
- //TODO: (mralj) - this is somewhat naive implementation, if single tx is invalid we consider the whole response invalid.
1583
- // I think we should still extract the valid txs and return them, so that we can still use the response.
1584
- try {
1585
- await Promise.all(responseTx.map((tx)=>this.validateRequestedTx(tx, peerId, requestedTxValidator, requested)));
1586
- return true;
1587
- } catch (e) {
1588
- if (e instanceof ValidationError) {
1589
- this.logger.warn(`Failed to validate requested txs from peer ${peerId.toString()}, reason ${e.message}`);
1590
- } else {
1591
- this.logger.error(`Error during validation of requested txs`, e);
1592
- }
1593
- return false;
1594
- }
1595
- }
1596
- /**
1597
- * Validates a BLOCK response.
1598
- *
1599
- * If a local copy exists, enforces hash equality. If missing, rejects (no penalty) since the hash cannot be verified.
1600
- * Penalizes on block number mismatch or hash mismatch.
1601
- *
1602
- * @param requestedBlockNumber - The requested block number.
1603
- * @param responseBlock - The block returned by the peer.
1604
- * @param peerId - The peer that returned the block.
1605
- * @returns True if the response is valid, false otherwise.
1606
- */ async validateRequestedBlock(requestedBlockNumber, responseBlock, peerId) {
1607
- try {
1608
- const reqNum = Number(requestedBlockNumber.toString());
1609
- if (responseBlock.number !== reqNum) {
1610
- this.peerManager.penalizePeer(peerId, PeerErrorSeverity.LowToleranceError);
1611
- return false;
1612
- }
1613
- const local = await this.archiver.getBlock(BlockNumber(reqNum));
1614
- if (!local) {
1615
- // We are missing the local block; we cannot verify the hash yet. Reject without penalizing.
1616
- // TODO: Consider extending this validator to accept an expected hash or
1617
- // performing quorum-based checks when using P2P syncing prior to L1 sync.
1618
- this.logger.warn(`Local block ${reqNum} not found; rejecting BLOCK response without hash verification`);
1619
- return false;
1620
- }
1621
- const [localHash, respHash] = await Promise.all([
1622
- local.hash(),
1623
- responseBlock.hash()
1624
- ]);
1625
- if (!localHash.equals(respHash)) {
1626
- this.peerManager.penalizePeer(peerId, PeerErrorSeverity.MidToleranceError);
1627
- return false;
1628
- }
1629
- return true;
1630
- } catch (e) {
1631
- this.logger.warn(`Error validating requested block`, e);
1632
- return false;
1633
- }
1634
- }
1635
- async validateRequestedTx(tx, peerId, txValidator, requested) {
1636
- const penalize = (severity)=>this.peerManager.penalizePeer(peerId, severity);
1637
- if (requested && !requested.has(tx.getTxHash().toString())) {
1638
- penalize(PeerErrorSeverity.MidToleranceError);
1639
- throw new ValidationError(`Received tx with hash ${tx.getTxHash().toString()} that was not requested.`);
1640
- }
1641
- const { result } = await txValidator.validateTx(tx);
1642
- if (result === 'invalid') {
1643
- penalize(PeerErrorSeverity.LowToleranceError);
1644
- throw new ValidationError(`Received tx with hash ${tx.getTxHash().toString()} that is invalid.`);
1645
- }
1646
- }
1647
- createRequestedTxValidator() {
1648
- return createTxValidatorForReqResponseReceivedTxs(this.proofVerifier, {
1649
- l1ChainId: this.config.l1ChainId,
1650
- rollupVersion: this.config.rollupVersion
1651
- });
1652
- }
1653
- async getGasFees(blockNumber) {
1654
- if (blockNumber === this.feesCache?.blockNumber) {
1655
- return this.feesCache.gasFees;
1656
- }
1657
- const header = await this.archiver.getBlockHeader(blockNumber);
1658
- const gasFees = header?.globalVariables.gasFees ?? GasFees.empty();
1659
- this.feesCache = {
1660
- blockNumber,
1661
- gasFees
1662
- };
1663
- return gasFees;
1701
+ getGasFees() {
1702
+ return this.blockMinFeesProvider.getCurrentMinFees();
1664
1703
  }
1665
1704
  /**
1666
1705
  * Get the BatchTxRequesterLibP2PService dependencies for creating BatchTxRequester instances
@@ -1671,16 +1710,18 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
1671
1710
  txValidatorConfig: {
1672
1711
  l1ChainId: this.config.l1ChainId,
1673
1712
  rollupVersion: this.config.rollupVersion,
1674
- proofVerifier: this.proofVerifier
1713
+ proofVerifier: this.proofVerifier,
1714
+ txValidationCache: this.txValidationCache
1675
1715
  },
1676
- peerScoring: this.peerManager
1716
+ peerScoring: this.peerManager,
1717
+ validateRequestedBlockTxsConsistency: this.validateRequestedBlockTxsConsistency.bind(this)
1677
1718
  };
1678
1719
  }
1679
1720
  async validateTxsReceivedInBlockProposal(txs) {
1680
1721
  const validator = createTxValidatorForBlockProposalReceivedTxs(this.proofVerifier, {
1681
1722
  l1ChainId: this.config.l1ChainId,
1682
1723
  rollupVersion: this.config.rollupVersion
1683
- }, this.logger.getBindings());
1724
+ }, this.logger.getBindings(), this.txValidationCache);
1684
1725
  const results = await Promise.all(txs.map(async (tx)=>{
1685
1726
  const result = await validator.validateTx(tx);
1686
1727
  return result.result !== 'invalid';
@@ -1690,13 +1731,18 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
1690
1731
  }
1691
1732
  }
1692
1733
  /** Creates the first stage (fast) validators for gossiped transactions. */ async createFirstStageMessageValidators(currentBlockNumber, nextSlotTimestamp) {
1693
- const gasFees = await this.getGasFees(currentBlockNumber);
1734
+ const gasFees = await this.getGasFees();
1694
1735
  const allowedInSetup = [
1695
1736
  ...await getDefaultAllowedSetupFunctions(),
1696
1737
  ...this.config.txPublicSetupAllowListExtend ?? []
1697
1738
  ];
1698
1739
  const blockNumber = BlockNumber(currentBlockNumber + 1);
1699
- return createFirstStageTxValidationsForGossipedTransactions(nextSlotTimestamp, blockNumber, this.worldStateSynchronizer, gasFees, this.config.l1ChainId, this.config.rollupVersion, protocolContractsHash, this.archiver, !this.config.disableTransactions, allowedInSetup, this.logger.getBindings());
1740
+ const l1Constants = await this.archiver.getL1Constants();
1741
+ return createFirstStageTxValidationsForGossipedTransactions(nextSlotTimestamp, blockNumber, this.worldStateSynchronizer, gasFees, this.config.l1ChainId, this.config.rollupVersion, protocolContractsHash, this.archiver, !this.config.disableTransactions, allowedInSetup, this.logger.getBindings(), {
1742
+ rollupManaLimit: l1Constants.rollupManaLimit,
1743
+ maxBlockL2Gas: this.config.validateMaxL2BlockGas,
1744
+ maxBlockDAGas: this.config.validateMaxDABlockGas
1745
+ });
1700
1746
  }
1701
1747
  /** Creates the second stage (expensive proof verification) validators for gossiped transactions. */ createSecondStageMessageValidators() {
1702
1748
  return createSecondStageTxValidationsForGossipedTransactions(this.proofVerifier, this.logger.getBindings());
@@ -1717,8 +1763,10 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
1717
1763
  });
1718
1764
  // A promise that resolves when all validations have been run
1719
1765
  const allValidations = await Promise.all(validationPromises);
1720
- const failed = allValidations.find((x)=>!x.isValid);
1721
- if (failed) {
1766
+ const failures = allValidations.filter((x)=>!x.isValid);
1767
+ if (failures.length > 0) {
1768
+ // Pick the most severe failure (lowest tolerance = harshest penalty)
1769
+ const failed = maxBy(failures, (f)=>PeerErrorSeverityByHarshness.indexOf(f.severity));
1722
1770
  return {
1723
1771
  allPassed: false,
1724
1772
  failure: {
@@ -1765,19 +1813,6 @@ _dec = trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId
1765
1813
  }
1766
1814
  return PeerErrorSeverity.HighToleranceError;
1767
1815
  }
1768
- /**
1769
- * Validate a checkpoint attestation.
1770
- *
1771
- * @param attestation - The checkpoint attestation to validate.
1772
- * @returns True if the checkpoint attestation is valid, false otherwise.
1773
- */ async validateCheckpointAttestation(peerId, attestation) {
1774
- const result = await this.checkpointAttestationValidator.validate(attestation);
1775
- if (result.result === 'reject') {
1776
- this.logger.warn(`Penalizing peer ${peerId} for checkpoint attestation validation failure`);
1777
- this.peerManager.penalizePeer(peerId, result.severity);
1778
- }
1779
- return result;
1780
- }
1781
1816
  getPeerScore(peerId) {
1782
1817
  return this.node.services.pubsub.score.score(peerId.toString());
1783
1818
  }