@aztec/p2p 0.0.1-commit.43c09e3f → 0.0.1-commit.4d3c002

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 (449) hide show
  1. package/README.md +129 -3
  2. package/dest/client/factory.d.ts +11 -11
  3. package/dest/client/factory.d.ts.map +1 -1
  4. package/dest/client/factory.js +55 -17
  5. package/dest/client/interface.d.ts +54 -34
  6. package/dest/client/interface.d.ts.map +1 -1
  7. package/dest/client/p2p_client.d.ts +41 -52
  8. package/dest/client/p2p_client.d.ts.map +1 -1
  9. package/dest/client/p2p_client.js +170 -224
  10. package/dest/client/test/tx_proposal_collector/proposal_tx_collector_worker.js +21 -11
  11. package/dest/config.d.ts +55 -18
  12. package/dest/config.d.ts.map +1 -1
  13. package/dest/config.js +102 -38
  14. package/dest/errors/p2p-service.error.d.ts +9 -0
  15. package/dest/errors/p2p-service.error.d.ts.map +1 -0
  16. package/dest/errors/p2p-service.error.js +10 -0
  17. package/dest/errors/tx-pool.error.d.ts +8 -0
  18. package/dest/errors/tx-pool.error.d.ts.map +1 -0
  19. package/dest/errors/tx-pool.error.js +9 -0
  20. package/dest/index.d.ts +2 -2
  21. package/dest/index.d.ts.map +1 -1
  22. package/dest/index.js +1 -1
  23. package/dest/mem_pools/attestation_pool/attestation_pool.d.ts +104 -88
  24. package/dest/mem_pools/attestation_pool/attestation_pool.d.ts.map +1 -1
  25. package/dest/mem_pools/attestation_pool/attestation_pool.js +446 -3
  26. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.d.ts +2 -2
  27. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.d.ts.map +1 -1
  28. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.js +353 -87
  29. package/dest/mem_pools/attestation_pool/index.d.ts +2 -3
  30. package/dest/mem_pools/attestation_pool/index.d.ts.map +1 -1
  31. package/dest/mem_pools/attestation_pool/index.js +1 -2
  32. package/dest/mem_pools/attestation_pool/mocks.d.ts +2 -2
  33. package/dest/mem_pools/attestation_pool/mocks.d.ts.map +1 -1
  34. package/dest/mem_pools/attestation_pool/mocks.js +2 -2
  35. package/dest/mem_pools/index.d.ts +3 -3
  36. package/dest/mem_pools/index.d.ts.map +1 -1
  37. package/dest/mem_pools/index.js +1 -1
  38. package/dest/mem_pools/instrumentation.d.ts +4 -2
  39. package/dest/mem_pools/instrumentation.d.ts.map +1 -1
  40. package/dest/mem_pools/instrumentation.js +16 -14
  41. package/dest/mem_pools/interface.d.ts +5 -5
  42. package/dest/mem_pools/interface.d.ts.map +1 -1
  43. package/dest/mem_pools/tx_pool_v2/deleted_pool.d.ts +104 -0
  44. package/dest/mem_pools/tx_pool_v2/deleted_pool.d.ts.map +1 -0
  45. package/dest/mem_pools/tx_pool_v2/deleted_pool.js +251 -0
  46. package/dest/mem_pools/tx_pool_v2/eviction/eviction_manager.d.ts +3 -3
  47. package/dest/mem_pools/tx_pool_v2/eviction/eviction_manager.d.ts.map +1 -1
  48. package/dest/mem_pools/tx_pool_v2/eviction/eviction_manager.js +18 -9
  49. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.d.ts +1 -1
  50. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.d.ts.map +1 -1
  51. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.js +7 -3
  52. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.d.ts +3 -3
  53. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.d.ts.map +1 -1
  54. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.js +12 -4
  55. package/dest/mem_pools/tx_pool_v2/eviction/index.d.ts +2 -2
  56. package/dest/mem_pools/tx_pool_v2/eviction/index.d.ts.map +1 -1
  57. package/dest/mem_pools/tx_pool_v2/eviction/index.js +1 -1
  58. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.d.ts +54 -5
  59. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.d.ts.map +1 -1
  60. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.js +8 -0
  61. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.js +7 -5
  62. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.js +7 -5
  63. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.d.ts +2 -2
  64. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.d.ts.map +1 -1
  65. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.js +14 -6
  66. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.d.ts +4 -4
  67. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.d.ts.map +1 -1
  68. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.js +16 -4
  69. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.d.ts +3 -3
  70. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.d.ts.map +1 -1
  71. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.js +3 -3
  72. package/dest/mem_pools/tx_pool_v2/index.d.ts +3 -2
  73. package/dest/mem_pools/tx_pool_v2/index.d.ts.map +1 -1
  74. package/dest/mem_pools/tx_pool_v2/index.js +2 -1
  75. package/dest/mem_pools/tx_pool_v2/instrumentation.d.ts +15 -0
  76. package/dest/mem_pools/tx_pool_v2/instrumentation.d.ts.map +1 -0
  77. package/dest/mem_pools/tx_pool_v2/instrumentation.js +43 -0
  78. package/dest/mem_pools/tx_pool_v2/interfaces.d.ts +34 -12
  79. package/dest/mem_pools/tx_pool_v2/interfaces.d.ts.map +1 -1
  80. package/dest/mem_pools/tx_pool_v2/interfaces.js +5 -1
  81. package/dest/mem_pools/tx_pool_v2/tx_metadata.d.ts +78 -15
  82. package/dest/mem_pools/tx_pool_v2/tx_metadata.d.ts.map +1 -1
  83. package/dest/mem_pools/tx_pool_v2/tx_metadata.js +144 -18
  84. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.d.ts +108 -0
  85. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.d.ts.map +1 -0
  86. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.js +337 -0
  87. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.d.ts +12 -5
  88. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.d.ts.map +1 -1
  89. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.js +23 -6
  90. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.d.ts +14 -5
  91. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.d.ts.map +1 -1
  92. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.js +476 -594
  93. package/dest/msg_validators/attestation_validator/attestation_validator.d.ts +1 -1
  94. package/dest/msg_validators/attestation_validator/attestation_validator.d.ts.map +1 -1
  95. package/dest/msg_validators/attestation_validator/attestation_validator.js +5 -4
  96. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.d.ts +3 -3
  97. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.d.ts.map +1 -1
  98. package/dest/msg_validators/clock_tolerance.d.ts +1 -1
  99. package/dest/msg_validators/clock_tolerance.d.ts.map +1 -1
  100. package/dest/msg_validators/clock_tolerance.js +4 -3
  101. package/dest/msg_validators/proposal_validator/block_proposal_validator.d.ts +6 -4
  102. package/dest/msg_validators/proposal_validator/block_proposal_validator.d.ts.map +1 -1
  103. package/dest/msg_validators/proposal_validator/block_proposal_validator.js +10 -2
  104. package/dest/msg_validators/proposal_validator/checkpoint_proposal_validator.d.ts +6 -4
  105. package/dest/msg_validators/proposal_validator/checkpoint_proposal_validator.d.ts.map +1 -1
  106. package/dest/msg_validators/proposal_validator/checkpoint_proposal_validator.js +16 -2
  107. package/dest/msg_validators/proposal_validator/proposal_validator.d.ts +13 -8
  108. package/dest/msg_validators/proposal_validator/proposal_validator.d.ts.map +1 -1
  109. package/dest/msg_validators/proposal_validator/proposal_validator.js +53 -41
  110. package/dest/msg_validators/tx_validator/aggregate_tx_validator.d.ts +4 -4
  111. package/dest/msg_validators/tx_validator/aggregate_tx_validator.d.ts.map +1 -1
  112. package/dest/msg_validators/tx_validator/aggregate_tx_validator.js +3 -3
  113. package/dest/msg_validators/tx_validator/allowed_public_setup.d.ts +2 -1
  114. package/dest/msg_validators/tx_validator/allowed_public_setup.d.ts.map +1 -1
  115. package/dest/msg_validators/tx_validator/allowed_public_setup.js +24 -20
  116. package/dest/msg_validators/tx_validator/allowed_setup_helpers.d.ts +17 -0
  117. package/dest/msg_validators/tx_validator/allowed_setup_helpers.d.ts.map +1 -0
  118. package/dest/msg_validators/tx_validator/allowed_setup_helpers.js +24 -0
  119. package/dest/msg_validators/tx_validator/block_header_validator.d.ts +16 -3
  120. package/dest/msg_validators/tx_validator/block_header_validator.d.ts.map +1 -1
  121. package/dest/msg_validators/tx_validator/block_header_validator.js +1 -1
  122. package/dest/msg_validators/tx_validator/contract_instance_validator.d.ts +9 -0
  123. package/dest/msg_validators/tx_validator/contract_instance_validator.d.ts.map +1 -0
  124. package/dest/msg_validators/tx_validator/contract_instance_validator.js +48 -0
  125. package/dest/msg_validators/tx_validator/data_validator.d.ts +1 -1
  126. package/dest/msg_validators/tx_validator/data_validator.d.ts.map +1 -1
  127. package/dest/msg_validators/tx_validator/data_validator.js +35 -2
  128. package/dest/msg_validators/tx_validator/double_spend_validator.d.ts +13 -3
  129. package/dest/msg_validators/tx_validator/double_spend_validator.d.ts.map +1 -1
  130. package/dest/msg_validators/tx_validator/double_spend_validator.js +4 -4
  131. package/dest/msg_validators/tx_validator/factory.d.ts +133 -6
  132. package/dest/msg_validators/tx_validator/factory.d.ts.map +1 -1
  133. package/dest/msg_validators/tx_validator/factory.js +247 -60
  134. package/dest/msg_validators/tx_validator/fee_payer_balance.d.ts +1 -1
  135. package/dest/msg_validators/tx_validator/fee_payer_balance.d.ts.map +1 -1
  136. package/dest/msg_validators/tx_validator/fee_payer_balance.js +6 -2
  137. package/dest/msg_validators/tx_validator/gas_validator.d.ts +67 -3
  138. package/dest/msg_validators/tx_validator/gas_validator.d.ts.map +1 -1
  139. package/dest/msg_validators/tx_validator/gas_validator.js +104 -37
  140. package/dest/msg_validators/tx_validator/index.d.ts +3 -1
  141. package/dest/msg_validators/tx_validator/index.d.ts.map +1 -1
  142. package/dest/msg_validators/tx_validator/index.js +2 -0
  143. package/dest/msg_validators/tx_validator/metadata_validator.d.ts +1 -1
  144. package/dest/msg_validators/tx_validator/metadata_validator.d.ts.map +1 -1
  145. package/dest/msg_validators/tx_validator/metadata_validator.js +4 -4
  146. package/dest/msg_validators/tx_validator/nullifier_cache.d.ts +14 -0
  147. package/dest/msg_validators/tx_validator/nullifier_cache.d.ts.map +1 -0
  148. package/dest/msg_validators/tx_validator/nullifier_cache.js +24 -0
  149. package/dest/msg_validators/tx_validator/phases_validator.d.ts +22 -2
  150. package/dest/msg_validators/tx_validator/phases_validator.d.ts.map +1 -1
  151. package/dest/msg_validators/tx_validator/phases_validator.js +72 -24
  152. package/dest/msg_validators/tx_validator/timestamp_validator.d.ts +20 -4
  153. package/dest/msg_validators/tx_validator/timestamp_validator.d.ts.map +1 -1
  154. package/dest/msg_validators/tx_validator/timestamp_validator.js +6 -6
  155. package/dest/services/discv5/discV5_service.d.ts +1 -1
  156. package/dest/services/discv5/discV5_service.d.ts.map +1 -1
  157. package/dest/services/discv5/discV5_service.js +5 -2
  158. package/dest/services/dummy_service.d.ts +16 -6
  159. package/dest/services/dummy_service.d.ts.map +1 -1
  160. package/dest/services/dummy_service.js +15 -5
  161. package/dest/services/encoding.d.ts +7 -3
  162. package/dest/services/encoding.d.ts.map +1 -1
  163. package/dest/services/encoding.js +18 -11
  164. package/dest/services/gossipsub/index.d.ts +3 -0
  165. package/dest/services/gossipsub/index.d.ts.map +1 -0
  166. package/dest/services/gossipsub/index.js +2 -0
  167. package/dest/services/gossipsub/scoring.d.ts +21 -3
  168. package/dest/services/gossipsub/scoring.d.ts.map +1 -1
  169. package/dest/services/gossipsub/scoring.js +24 -7
  170. package/dest/services/gossipsub/topic_score_params.d.ts +173 -0
  171. package/dest/services/gossipsub/topic_score_params.d.ts.map +1 -0
  172. package/dest/services/gossipsub/topic_score_params.js +346 -0
  173. package/dest/services/libp2p/libp2p_service.d.ts +108 -51
  174. package/dest/services/libp2p/libp2p_service.d.ts.map +1 -1
  175. package/dest/services/libp2p/libp2p_service.js +568 -383
  176. package/dest/services/peer-manager/metrics.d.ts +3 -1
  177. package/dest/services/peer-manager/metrics.d.ts.map +1 -1
  178. package/dest/services/peer-manager/metrics.js +6 -0
  179. package/dest/services/peer-manager/peer_manager.d.ts +6 -2
  180. package/dest/services/peer-manager/peer_manager.d.ts.map +1 -1
  181. package/dest/services/peer-manager/peer_manager.js +24 -9
  182. package/dest/services/peer-manager/peer_scoring.d.ts +5 -2
  183. package/dest/services/peer-manager/peer_scoring.d.ts.map +1 -1
  184. package/dest/services/peer-manager/peer_scoring.js +53 -12
  185. package/dest/services/reqresp/batch-tx-requester/batch_tx_requester.d.ts +14 -10
  186. package/dest/services/reqresp/batch-tx-requester/batch_tx_requester.d.ts.map +1 -1
  187. package/dest/services/reqresp/batch-tx-requester/batch_tx_requester.js +89 -112
  188. package/dest/services/reqresp/batch-tx-requester/interface.d.ts +4 -7
  189. package/dest/services/reqresp/batch-tx-requester/interface.d.ts.map +1 -1
  190. package/dest/services/reqresp/batch-tx-requester/missing_txs.d.ts +11 -13
  191. package/dest/services/reqresp/batch-tx-requester/missing_txs.d.ts.map +1 -1
  192. package/dest/services/reqresp/batch-tx-requester/missing_txs.js +31 -46
  193. package/dest/services/reqresp/batch-tx-requester/peer_collection.d.ts +19 -11
  194. package/dest/services/reqresp/batch-tx-requester/peer_collection.d.ts.map +1 -1
  195. package/dest/services/reqresp/batch-tx-requester/peer_collection.js +52 -15
  196. package/dest/services/reqresp/batch-tx-requester/tx_validator.js +2 -2
  197. package/dest/services/reqresp/interface.d.ts +10 -1
  198. package/dest/services/reqresp/interface.d.ts.map +1 -1
  199. package/dest/services/reqresp/interface.js +15 -1
  200. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.d.ts +7 -5
  201. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.d.ts.map +1 -1
  202. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.js +16 -11
  203. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.d.ts +21 -10
  204. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.d.ts.map +1 -1
  205. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.js +27 -11
  206. package/dest/services/reqresp/protocols/tx.d.ts +7 -1
  207. package/dest/services/reqresp/protocols/tx.d.ts.map +1 -1
  208. package/dest/services/reqresp/protocols/tx.js +20 -0
  209. package/dest/services/reqresp/rate-limiter/rate_limiter.d.ts +5 -4
  210. package/dest/services/reqresp/rate-limiter/rate_limiter.d.ts.map +1 -1
  211. package/dest/services/reqresp/rate-limiter/rate_limiter.js +10 -8
  212. package/dest/services/reqresp/reqresp.d.ts +1 -1
  213. package/dest/services/reqresp/reqresp.d.ts.map +1 -1
  214. package/dest/services/reqresp/reqresp.js +30 -14
  215. package/dest/services/service.d.ts +45 -4
  216. package/dest/services/service.d.ts.map +1 -1
  217. package/dest/services/tx_collection/config.d.ts +22 -4
  218. package/dest/services/tx_collection/config.d.ts.map +1 -1
  219. package/dest/services/tx_collection/config.js +49 -3
  220. package/dest/services/tx_collection/fast_tx_collection.d.ts +6 -8
  221. package/dest/services/tx_collection/fast_tx_collection.d.ts.map +1 -1
  222. package/dest/services/tx_collection/fast_tx_collection.js +88 -88
  223. package/dest/services/tx_collection/file_store_tx_collection.d.ts +53 -0
  224. package/dest/services/tx_collection/file_store_tx_collection.d.ts.map +1 -0
  225. package/dest/services/tx_collection/file_store_tx_collection.js +167 -0
  226. package/dest/services/tx_collection/file_store_tx_source.d.ts +38 -0
  227. package/dest/services/tx_collection/file_store_tx_source.d.ts.map +1 -0
  228. package/dest/services/tx_collection/file_store_tx_source.js +100 -0
  229. package/dest/services/tx_collection/index.d.ts +3 -2
  230. package/dest/services/tx_collection/index.d.ts.map +1 -1
  231. package/dest/services/tx_collection/index.js +1 -0
  232. package/dest/services/tx_collection/instrumentation.d.ts +1 -1
  233. package/dest/services/tx_collection/instrumentation.d.ts.map +1 -1
  234. package/dest/services/tx_collection/instrumentation.js +2 -1
  235. package/dest/services/tx_collection/proposal_tx_collector.d.ts +15 -15
  236. package/dest/services/tx_collection/proposal_tx_collector.d.ts.map +1 -1
  237. package/dest/services/tx_collection/proposal_tx_collector.js +6 -6
  238. package/dest/services/tx_collection/request_tracker.d.ts +53 -0
  239. package/dest/services/tx_collection/request_tracker.d.ts.map +1 -0
  240. package/dest/services/tx_collection/request_tracker.js +84 -0
  241. package/dest/services/tx_collection/slow_tx_collection.d.ts +7 -3
  242. package/dest/services/tx_collection/slow_tx_collection.d.ts.map +1 -1
  243. package/dest/services/tx_collection/slow_tx_collection.js +60 -26
  244. package/dest/services/tx_collection/tx_collection.d.ts +23 -13
  245. package/dest/services/tx_collection/tx_collection.d.ts.map +1 -1
  246. package/dest/services/tx_collection/tx_collection.js +75 -3
  247. package/dest/services/tx_collection/tx_collection_sink.d.ts +18 -8
  248. package/dest/services/tx_collection/tx_collection_sink.d.ts.map +1 -1
  249. package/dest/services/tx_collection/tx_collection_sink.js +26 -29
  250. package/dest/services/tx_collection/tx_source.d.ts +13 -7
  251. package/dest/services/tx_collection/tx_source.d.ts.map +1 -1
  252. package/dest/services/tx_collection/tx_source.js +26 -7
  253. package/dest/services/tx_file_store/config.d.ts +1 -3
  254. package/dest/services/tx_file_store/config.d.ts.map +1 -1
  255. package/dest/services/tx_file_store/config.js +0 -4
  256. package/dest/services/tx_file_store/tx_file_store.d.ts +4 -3
  257. package/dest/services/tx_file_store/tx_file_store.d.ts.map +1 -1
  258. package/dest/services/tx_file_store/tx_file_store.js +9 -6
  259. package/dest/services/tx_provider.d.ts +4 -4
  260. package/dest/services/tx_provider.d.ts.map +1 -1
  261. package/dest/services/tx_provider.js +9 -8
  262. package/dest/test-helpers/make-test-p2p-clients.d.ts +7 -8
  263. package/dest/test-helpers/make-test-p2p-clients.d.ts.map +1 -1
  264. package/dest/test-helpers/make-test-p2p-clients.js +1 -2
  265. package/dest/test-helpers/mock-pubsub.d.ts +37 -4
  266. package/dest/test-helpers/mock-pubsub.d.ts.map +1 -1
  267. package/dest/test-helpers/mock-pubsub.js +113 -5
  268. package/dest/test-helpers/reqresp-nodes.d.ts +2 -3
  269. package/dest/test-helpers/reqresp-nodes.d.ts.map +1 -1
  270. package/dest/test-helpers/reqresp-nodes.js +9 -4
  271. package/dest/test-helpers/testbench-utils.d.ts +43 -38
  272. package/dest/test-helpers/testbench-utils.d.ts.map +1 -1
  273. package/dest/test-helpers/testbench-utils.js +149 -61
  274. package/dest/testbench/p2p_client_testbench_worker.d.ts +2 -2
  275. package/dest/testbench/p2p_client_testbench_worker.d.ts.map +1 -1
  276. package/dest/testbench/p2p_client_testbench_worker.js +58 -28
  277. package/dest/testbench/worker_client_manager.d.ts +3 -1
  278. package/dest/testbench/worker_client_manager.d.ts.map +1 -1
  279. package/dest/testbench/worker_client_manager.js +6 -3
  280. package/dest/util.d.ts +9 -5
  281. package/dest/util.d.ts.map +1 -1
  282. package/dest/util.js +2 -10
  283. package/package.json +14 -14
  284. package/src/client/factory.ts +106 -30
  285. package/src/client/interface.ts +65 -35
  286. package/src/client/p2p_client.ts +205 -269
  287. package/src/client/test/tx_proposal_collector/proposal_tx_collector_worker.ts +34 -15
  288. package/src/config.ts +158 -44
  289. package/src/errors/p2p-service.error.ts +11 -0
  290. package/src/errors/tx-pool.error.ts +12 -0
  291. package/src/index.ts +1 -1
  292. package/src/mem_pools/attestation_pool/attestation_pool.ts +499 -91
  293. package/src/mem_pools/attestation_pool/attestation_pool_test_suite.ts +442 -102
  294. package/src/mem_pools/attestation_pool/index.ts +9 -2
  295. package/src/mem_pools/attestation_pool/mocks.ts +2 -1
  296. package/src/mem_pools/index.ts +2 -2
  297. package/src/mem_pools/instrumentation.ts +17 -13
  298. package/src/mem_pools/interface.ts +4 -4
  299. package/src/mem_pools/tx_pool_v2/README.md +112 -17
  300. package/src/mem_pools/tx_pool_v2/deleted_pool.ts +321 -0
  301. package/src/mem_pools/tx_pool_v2/eviction/eviction_manager.ts +21 -8
  302. package/src/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.ts +7 -3
  303. package/src/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.ts +18 -4
  304. package/src/mem_pools/tx_pool_v2/eviction/index.ts +4 -0
  305. package/src/mem_pools/tx_pool_v2/eviction/interfaces.ts +59 -4
  306. package/src/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.ts +5 -5
  307. package/src/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.ts +5 -5
  308. package/src/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.ts +14 -9
  309. package/src/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.ts +33 -6
  310. package/src/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.ts +4 -3
  311. package/src/mem_pools/tx_pool_v2/index.ts +2 -1
  312. package/src/mem_pools/tx_pool_v2/instrumentation.ts +69 -0
  313. package/src/mem_pools/tx_pool_v2/interfaces.ts +34 -12
  314. package/src/mem_pools/tx_pool_v2/tx_metadata.ts +209 -26
  315. package/src/mem_pools/tx_pool_v2/tx_pool_indices.ts +430 -0
  316. package/src/mem_pools/tx_pool_v2/tx_pool_v2.ts +37 -8
  317. package/src/mem_pools/tx_pool_v2/tx_pool_v2_impl.ts +518 -678
  318. package/src/msg_validators/attestation_validator/README.md +49 -0
  319. package/src/msg_validators/attestation_validator/attestation_validator.ts +5 -4
  320. package/src/msg_validators/attestation_validator/fisherman_attestation_validator.ts +2 -2
  321. package/src/msg_validators/clock_tolerance.ts +4 -3
  322. package/src/msg_validators/proposal_validator/README.md +123 -0
  323. package/src/msg_validators/proposal_validator/block_proposal_validator.ts +14 -4
  324. package/src/msg_validators/proposal_validator/checkpoint_proposal_validator.ts +20 -7
  325. package/src/msg_validators/proposal_validator/proposal_validator.ts +69 -45
  326. package/src/msg_validators/tx_validator/README.md +119 -0
  327. package/src/msg_validators/tx_validator/aggregate_tx_validator.ts +5 -5
  328. package/src/msg_validators/tx_validator/allowed_public_setup.ts +22 -27
  329. package/src/msg_validators/tx_validator/allowed_setup_helpers.ts +31 -0
  330. package/src/msg_validators/tx_validator/block_header_validator.ts +15 -3
  331. package/src/msg_validators/tx_validator/contract_instance_validator.ts +56 -0
  332. package/src/msg_validators/tx_validator/data_validator.ts +42 -1
  333. package/src/msg_validators/tx_validator/double_spend_validator.ts +11 -6
  334. package/src/msg_validators/tx_validator/factory.ts +394 -78
  335. package/src/msg_validators/tx_validator/fee_payer_balance.ts +6 -2
  336. package/src/msg_validators/tx_validator/gas_validator.ts +123 -27
  337. package/src/msg_validators/tx_validator/index.ts +2 -0
  338. package/src/msg_validators/tx_validator/metadata_validator.ts +12 -4
  339. package/src/msg_validators/tx_validator/nullifier_cache.ts +30 -0
  340. package/src/msg_validators/tx_validator/phases_validator.ts +82 -27
  341. package/src/msg_validators/tx_validator/timestamp_validator.ts +23 -18
  342. package/src/services/discv5/discV5_service.ts +5 -2
  343. package/src/services/dummy_service.ts +24 -7
  344. package/src/services/encoding.ts +18 -10
  345. package/src/services/gossipsub/README.md +641 -0
  346. package/src/services/gossipsub/index.ts +2 -0
  347. package/src/services/gossipsub/scoring.ts +29 -5
  348. package/src/services/gossipsub/topic_score_params.ts +487 -0
  349. package/src/services/libp2p/libp2p_service.ts +599 -418
  350. package/src/services/peer-manager/metrics.ts +7 -0
  351. package/src/services/peer-manager/peer_manager.ts +28 -9
  352. package/src/services/peer-manager/peer_scoring.ts +46 -5
  353. package/src/services/reqresp/README.md +229 -0
  354. package/src/services/reqresp/batch-tx-requester/README.md +53 -14
  355. package/src/services/reqresp/batch-tx-requester/batch_tx_requester.ts +89 -122
  356. package/src/services/reqresp/batch-tx-requester/interface.ts +3 -6
  357. package/src/services/reqresp/batch-tx-requester/missing_txs.ts +30 -71
  358. package/src/services/reqresp/batch-tx-requester/peer_collection.ts +68 -24
  359. package/src/services/reqresp/batch-tx-requester/tx_validator.ts +2 -2
  360. package/src/services/reqresp/interface.ts +26 -1
  361. package/src/services/reqresp/protocols/block_txs/block_txs_handler.ts +23 -14
  362. package/src/services/reqresp/protocols/block_txs/block_txs_reqresp.ts +38 -15
  363. package/src/services/reqresp/protocols/tx.ts +22 -0
  364. package/src/services/reqresp/rate-limiter/rate_limiter.ts +13 -9
  365. package/src/services/reqresp/reqresp.ts +35 -15
  366. package/src/services/service.ts +60 -3
  367. package/src/services/tx_collection/config.ts +74 -6
  368. package/src/services/tx_collection/fast_tx_collection.ts +94 -97
  369. package/src/services/tx_collection/file_store_tx_collection.ts +202 -0
  370. package/src/services/tx_collection/file_store_tx_source.ts +129 -0
  371. package/src/services/tx_collection/index.ts +2 -1
  372. package/src/services/tx_collection/instrumentation.ts +7 -1
  373. package/src/services/tx_collection/proposal_tx_collector.ts +21 -27
  374. package/src/services/tx_collection/request_tracker.ts +127 -0
  375. package/src/services/tx_collection/slow_tx_collection.ts +66 -33
  376. package/src/services/tx_collection/tx_collection.ts +114 -19
  377. package/src/services/tx_collection/tx_collection_sink.ts +30 -34
  378. package/src/services/tx_collection/tx_source.ts +28 -8
  379. package/src/services/tx_file_store/config.ts +0 -6
  380. package/src/services/tx_file_store/tx_file_store.ts +10 -8
  381. package/src/services/tx_provider.ts +10 -9
  382. package/src/test-helpers/make-test-p2p-clients.ts +4 -6
  383. package/src/test-helpers/mock-pubsub.ts +153 -9
  384. package/src/test-helpers/reqresp-nodes.ts +9 -7
  385. package/src/test-helpers/testbench-utils.ts +156 -74
  386. package/src/testbench/p2p_client_testbench_worker.ts +64 -31
  387. package/src/testbench/worker_client_manager.ts +13 -6
  388. package/src/util.ts +15 -16
  389. package/dest/mem_pools/attestation_pool/kv_attestation_pool.d.ts +0 -40
  390. package/dest/mem_pools/attestation_pool/kv_attestation_pool.d.ts.map +0 -1
  391. package/dest/mem_pools/attestation_pool/kv_attestation_pool.js +0 -218
  392. package/dest/mem_pools/attestation_pool/memory_attestation_pool.d.ts +0 -31
  393. package/dest/mem_pools/attestation_pool/memory_attestation_pool.d.ts.map +0 -1
  394. package/dest/mem_pools/attestation_pool/memory_attestation_pool.js +0 -180
  395. package/dest/mem_pools/tx_pool/aztec_kv_tx_pool.d.ts +0 -125
  396. package/dest/mem_pools/tx_pool/aztec_kv_tx_pool.d.ts.map +0 -1
  397. package/dest/mem_pools/tx_pool/aztec_kv_tx_pool.js +0 -596
  398. package/dest/mem_pools/tx_pool/eviction/eviction_manager.d.ts +0 -32
  399. package/dest/mem_pools/tx_pool/eviction/eviction_manager.d.ts.map +0 -1
  400. package/dest/mem_pools/tx_pool/eviction/eviction_manager.js +0 -112
  401. package/dest/mem_pools/tx_pool/eviction/eviction_strategy.d.ts +0 -157
  402. package/dest/mem_pools/tx_pool/eviction/eviction_strategy.d.ts.map +0 -1
  403. package/dest/mem_pools/tx_pool/eviction/eviction_strategy.js +0 -52
  404. package/dest/mem_pools/tx_pool/eviction/fee_payer_balance_eviction_rule.d.ts +0 -16
  405. package/dest/mem_pools/tx_pool/eviction/fee_payer_balance_eviction_rule.d.ts.map +0 -1
  406. package/dest/mem_pools/tx_pool/eviction/fee_payer_balance_eviction_rule.js +0 -122
  407. package/dest/mem_pools/tx_pool/eviction/invalid_txs_after_mining_rule.d.ts +0 -17
  408. package/dest/mem_pools/tx_pool/eviction/invalid_txs_after_mining_rule.d.ts.map +0 -1
  409. package/dest/mem_pools/tx_pool/eviction/invalid_txs_after_mining_rule.js +0 -84
  410. package/dest/mem_pools/tx_pool/eviction/invalid_txs_after_reorg_rule.d.ts +0 -19
  411. package/dest/mem_pools/tx_pool/eviction/invalid_txs_after_reorg_rule.d.ts.map +0 -1
  412. package/dest/mem_pools/tx_pool/eviction/invalid_txs_after_reorg_rule.js +0 -78
  413. package/dest/mem_pools/tx_pool/eviction/low_priority_eviction_rule.d.ts +0 -26
  414. package/dest/mem_pools/tx_pool/eviction/low_priority_eviction_rule.d.ts.map +0 -1
  415. package/dest/mem_pools/tx_pool/eviction/low_priority_eviction_rule.js +0 -84
  416. package/dest/mem_pools/tx_pool/eviction/nullifier_conflict_pre_add_rule.d.ts +0 -25
  417. package/dest/mem_pools/tx_pool/eviction/nullifier_conflict_pre_add_rule.d.ts.map +0 -1
  418. package/dest/mem_pools/tx_pool/eviction/nullifier_conflict_pre_add_rule.js +0 -57
  419. package/dest/mem_pools/tx_pool/index.d.ts +0 -3
  420. package/dest/mem_pools/tx_pool/index.d.ts.map +0 -1
  421. package/dest/mem_pools/tx_pool/index.js +0 -2
  422. package/dest/mem_pools/tx_pool/priority.d.ts +0 -12
  423. package/dest/mem_pools/tx_pool/priority.d.ts.map +0 -1
  424. package/dest/mem_pools/tx_pool/priority.js +0 -15
  425. package/dest/mem_pools/tx_pool/tx_pool.d.ts +0 -127
  426. package/dest/mem_pools/tx_pool/tx_pool.d.ts.map +0 -1
  427. package/dest/mem_pools/tx_pool/tx_pool.js +0 -3
  428. package/dest/mem_pools/tx_pool/tx_pool_test_suite.d.ts +0 -7
  429. package/dest/mem_pools/tx_pool/tx_pool_test_suite.d.ts.map +0 -1
  430. package/dest/mem_pools/tx_pool/tx_pool_test_suite.js +0 -400
  431. package/dest/msg_validators/proposal_validator/proposal_validator_test_suite.d.ts +0 -23
  432. package/dest/msg_validators/proposal_validator/proposal_validator_test_suite.d.ts.map +0 -1
  433. package/dest/msg_validators/proposal_validator/proposal_validator_test_suite.js +0 -212
  434. package/src/mem_pools/attestation_pool/kv_attestation_pool.ts +0 -320
  435. package/src/mem_pools/attestation_pool/memory_attestation_pool.ts +0 -264
  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 -230
@@ -1,6 +1,6 @@
1
1
  import type { EpochCacheInterface } from '@aztec/epoch-cache';
2
- import { BlockNumber } from '@aztec/foundation/branded-types';
3
- import { randomInt } from '@aztec/foundation/crypto/random';
2
+ import { BlockNumber, type SlotNumber } from '@aztec/foundation/branded-types';
3
+ import { maxBy } from '@aztec/foundation/collection';
4
4
  import { Fr } from '@aztec/foundation/curves/bn254';
5
5
  import { type Logger, createLibp2pComponentLogger, createLogger } from '@aztec/foundation/log';
6
6
  import { RunningPromise } from '@aztec/foundation/running-promise';
@@ -17,13 +17,12 @@ import {
17
17
  CheckpointProposal,
18
18
  type CheckpointProposalCore,
19
19
  type Gossipable,
20
- P2PClientType,
21
20
  P2PMessage,
22
- type ValidationResult as P2PValidationResult,
23
21
  PeerErrorSeverity,
22
+ PeerErrorSeverityByHarshness,
24
23
  TopicType,
25
24
  createTopicString,
26
- getTopicsForClientAndConfig,
25
+ getTopicsForConfig,
27
26
  metricsTopicStrToLabels,
28
27
  } from '@aztec/stdlib/p2p';
29
28
  import { MerkleTreeId } from '@aztec/stdlib/trees';
@@ -45,49 +44,56 @@ import {
45
44
  type GossipsubMessage,
46
45
  gossipsub,
47
46
  } from '@chainsafe/libp2p-gossipsub';
48
- import { createPeerScoreParams, createTopicScoreParams } from '@chainsafe/libp2p-gossipsub/score';
47
+ import { createPeerScoreParams } from '@chainsafe/libp2p-gossipsub/score';
49
48
  import { SignaturePolicy } from '@chainsafe/libp2p-gossipsub/types';
50
49
  import { noise } from '@chainsafe/libp2p-noise';
51
50
  import { yamux } from '@chainsafe/libp2p-yamux';
52
51
  import { bootstrap } from '@libp2p/bootstrap';
53
52
  import { identify } from '@libp2p/identify';
54
53
  import { type Message, type MultiaddrConnection, type PeerId, TopicValidatorResult } from '@libp2p/interface';
55
- import type { ConnectionManager } from '@libp2p/interface-internal';
54
+ import type { AddressManager, ConnectionManager } from '@libp2p/interface-internal';
56
55
  import { mplex } from '@libp2p/mplex';
57
56
  import { tcp } from '@libp2p/tcp';
57
+ import { multiaddr } from '@multiformats/multiaddr';
58
58
  import { ENR } from '@nethermindeth/enr';
59
59
  import { createLibp2p } from 'libp2p';
60
60
 
61
61
  import type { P2PConfig } from '../../config.js';
62
- import { ProposalSlotCapExceededError } from '../../errors/attestation-pool.error.js';
62
+ import { CheckpointProposalReceivedCallbackNotRegisteredError } from '../../errors/p2p-service.error.js';
63
63
  import type { MemPools } from '../../mem_pools/interface.js';
64
64
  import {
65
65
  BlockProposalValidator,
66
66
  CheckpointAttestationValidator,
67
67
  CheckpointProposalValidator,
68
+ DoubleSpendTxValidator,
68
69
  FishermanAttestationValidator,
70
+ getDefaultAllowedSetupFunctions,
69
71
  } from '../../msg_validators/index.js';
70
72
  import { MessageSeenValidator } from '../../msg_validators/msg_seen_validator/msg_seen_validator.js';
71
- import { getDefaultAllowedSetupFunctions } from '../../msg_validators/tx_validator/allowed_public_setup.js';
72
73
  import {
73
- type MessageValidator,
74
- createTxMessageValidators,
75
- createTxReqRespValidator,
74
+ type TransactionValidator,
75
+ createFirstStageTxValidationsForGossipedTransactions,
76
+ createSecondStageTxValidationsForGossipedTransactions,
77
+ createTxValidatorForBlockProposalReceivedTxs,
78
+ createTxValidatorForReqResponseReceivedTxs,
76
79
  } from '../../msg_validators/tx_validator/factory.js';
77
- import { DoubleSpendTxValidator } from '../../msg_validators/tx_validator/index.js';
78
80
  import { GossipSubEvent } from '../../types/index.js';
79
81
  import { type PubSubLibp2p, convertToMultiaddr } from '../../util.js';
80
82
  import { getVersions } from '../../versioning.js';
81
83
  import { AztecDatastore } from '../data_store.js';
82
84
  import { DiscV5Service } from '../discv5/discV5_service.js';
83
85
  import { SnappyTransform, fastMsgIdFn, getMsgIdFn, msgIdToStrFn } from '../encoding.js';
84
- import { gossipScoreThresholds } from '../gossipsub/scoring.js';
86
+ import { APP_SPECIFIC_WEIGHT, gossipScoreThresholds } from '../gossipsub/scoring.js';
87
+ import { createAllTopicScoreParams } from '../gossipsub/topic_score_params.js';
85
88
  import type { PeerManagerInterface } from '../peer-manager/interface.js';
86
89
  import { PeerManager } from '../peer-manager/peer_manager.js';
87
90
  import { PeerScoring } from '../peer-manager/peer_scoring.js';
88
91
  import type { BatchTxRequesterLibP2PService } from '../reqresp/batch-tx-requester/interface.js';
89
92
  import type { P2PReqRespConfig } from '../reqresp/config.js';
90
93
  import {
94
+ AuthRequest,
95
+ BlockTxsRequest,
96
+ BlockTxsResponse,
91
97
  DEFAULT_SUB_PROTOCOL_VALIDATORS,
92
98
  type ReqRespInterface,
93
99
  type ReqRespResponse,
@@ -95,25 +101,21 @@ import {
95
101
  type ReqRespSubProtocolHandler,
96
102
  type ReqRespSubProtocolHandlers,
97
103
  type ReqRespSubProtocolValidators,
104
+ StatusMessage,
98
105
  type SubProtocolMap,
99
106
  ValidationError,
100
- } from '../reqresp/interface.js';
101
- import { reqRespBlockTxsHandler } from '../reqresp/protocols/block_txs/block_txs_handler.js';
102
- import { reqGoodbyeHandler } from '../reqresp/protocols/goodbye.js';
103
- import {
104
- AuthRequest,
105
- BlockTxsRequest,
106
- BlockTxsResponse,
107
- StatusMessage,
108
107
  pingHandler,
108
+ reqGoodbyeHandler,
109
109
  reqRespBlockHandler,
110
+ reqRespBlockTxsHandler,
110
111
  reqRespStatusHandler,
111
112
  reqRespTxHandler,
112
- } from '../reqresp/protocols/index.js';
113
+ } from '../reqresp/index.js';
113
114
  import { ReqResp } from '../reqresp/reqresp.js';
114
115
  import type {
115
116
  P2PBlockReceivedCallback,
116
117
  P2PCheckpointReceivedCallback,
118
+ P2PDuplicateAttestationCallback,
117
119
  P2PService,
118
120
  PeerDiscoveryService,
119
121
  } from '../service.js';
@@ -128,14 +130,14 @@ interface ValidationResult {
128
130
  type ValidationOutcome = { allPassed: true } | { allPassed: false; failure: ValidationResult };
129
131
 
130
132
  // REFACTOR: Unify with the type above
131
- type ReceivedMessageValidationResult<T> =
132
- | { obj: T; result: Exclude<TopicValidatorResult, TopicValidatorResult.Reject> }
133
- | { obj?: undefined; result: TopicValidatorResult.Reject };
133
+ type ReceivedMessageValidationResult<T, M = undefined> =
134
+ | { obj: T; result: Exclude<TopicValidatorResult, TopicValidatorResult.Reject>; metadata?: M }
135
+ | { obj?: T; result: TopicValidatorResult.Reject; metadata?: M; severity: PeerErrorSeverity };
134
136
 
135
137
  /**
136
138
  * Lib P2P implementation of the P2PService interface.
137
139
  */
138
- export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends WithTracer implements P2PService {
140
+ export class LibP2PService extends WithTracer implements P2PService {
139
141
  private discoveryRunningPromise?: RunningPromise;
140
142
  private msgIdSeenValidators: Record<TopicType, MessageSeenValidator> = {} as Record<TopicType, MessageSeenValidator>;
141
143
 
@@ -149,6 +151,16 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
149
151
 
150
152
  private feesCache: { blockNumber: BlockNumber; gasFees: GasFees } | undefined;
151
153
 
154
+ /** Callback invoked when a duplicate proposal is detected (triggers slashing). */
155
+ private duplicateProposalCallback?: (info: {
156
+ slot: SlotNumber;
157
+ proposer: EthAddress;
158
+ type: 'checkpoint' | 'block';
159
+ }) => void;
160
+
161
+ /** Callback invoked when a duplicate attestation is detected (triggers slashing). */
162
+ private duplicateAttestationCallback?: P2PDuplicateAttestationCallback;
163
+
152
164
  /**
153
165
  * Callback for when a block is received from a peer.
154
166
  * @param block - The block received from the peer.
@@ -161,10 +173,19 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
161
173
  * @param checkpoint - The checkpoint proposal received from the peer.
162
174
  * @returns The attestations for the checkpoint, if any.
163
175
  */
164
- private checkpointReceivedCallback: P2PCheckpointReceivedCallback;
176
+ private allNodesCheckpointReceivedCallback: P2PCheckpointReceivedCallback;
177
+ /**
178
+ * Callback for when a checkpoint proposal is received - specifically for validators - from a peer.
179
+ * @param checkpoint - The checkpoint proposal received from the peer.
180
+ * @returns The attestations for the checkpoint, if any.
181
+ */
182
+ private validatorCheckpointReceivedCallback: P2PCheckpointReceivedCallback;
165
183
 
166
184
  private gossipSubEventHandler: (e: CustomEvent<GossipsubMessage>) => void;
167
185
 
186
+ private ipChangedHandler?: (ip: string) => void;
187
+ private discoveredP2pIp?: string;
188
+
168
189
  private instrumentation: P2PInstrumentation;
169
190
 
170
191
  private telemetry: TelemetryClient;
@@ -172,14 +193,13 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
172
193
  protected logger: Logger;
173
194
 
174
195
  constructor(
175
- private clientType: T,
176
196
  private config: P2PConfig,
177
197
  protected node: PubSubLibp2p,
178
198
  private peerDiscoveryService: PeerDiscoveryService,
179
199
  private reqresp: ReqRespInterface,
180
- private peerManager: PeerManagerInterface,
200
+ protected peerManager: PeerManagerInterface,
181
201
  protected mempools: MemPools,
182
- private archiver: L2BlockSource & ContractDataSource,
202
+ protected archiver: L2BlockSource & ContractDataSource,
183
203
  private epochCache: EpochCacheInterface,
184
204
  private proofVerifier: ClientProtocolCircuitVerifier,
185
205
  private worldStateSynchronizer: WorldStateSynchronizer,
@@ -214,10 +234,12 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
214
234
  this.protocolVersion,
215
235
  );
216
236
 
217
- this.blockProposalValidator = new BlockProposalValidator(epochCache, { txsPermitted: !config.disableTransactions });
218
- this.checkpointProposalValidator = new CheckpointProposalValidator(epochCache, {
237
+ const proposalValidatorOpts = {
219
238
  txsPermitted: !config.disableTransactions,
220
- });
239
+ maxTxsPerBlock: config.validateMaxTxsPerBlock ?? config.validateMaxTxsPerCheckpoint,
240
+ };
241
+ this.blockProposalValidator = new BlockProposalValidator(epochCache, proposalValidatorOpts);
242
+ this.checkpointProposalValidator = new CheckpointProposalValidator(epochCache, proposalValidatorOpts);
221
243
  this.checkpointAttestationValidator = config.fishermanMode
222
244
  ? new FishermanAttestationValidator(epochCache, mempools.attestationPool, telemetry)
223
245
  : new CheckpointAttestationValidator(epochCache);
@@ -225,19 +247,22 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
225
247
  this.gossipSubEventHandler = this.handleGossipSubEvent.bind(this);
226
248
 
227
249
  this.blockReceivedCallback = async (block: BlockProposal): Promise<boolean> => {
228
- this.logger.debug(
229
- `Handler not yet registered: Block received callback not set. Received block for slot ${block.slotNumber} from peer.`,
250
+ this.logger.warn(
251
+ `Handler for block received not yet registered on P2P service. Received block ${block.blockNumber} for slot ${block.slotNumber} from peer.`,
230
252
  { p2pMessageIdentifier: await block.p2pMessageLoggingIdentifier() },
231
253
  );
232
- return false;
254
+ return true;
233
255
  };
234
256
 
235
- this.checkpointReceivedCallback = (
236
- checkpoint: CheckpointProposalCore,
257
+ this.allNodesCheckpointReceivedCallback = (
258
+ _checkpoint: CheckpointProposalCore,
259
+ ): Promise<CheckpointAttestation[] | undefined> => {
260
+ throw new CheckpointProposalReceivedCallbackNotRegisteredError();
261
+ };
262
+
263
+ this.validatorCheckpointReceivedCallback = (
264
+ _checkpoint: CheckpointProposalCore,
237
265
  ): Promise<CheckpointAttestation[] | undefined> => {
238
- this.logger.debug(
239
- `Handler not yet registered: Checkpoint received callback not set. Received checkpoint for slot ${checkpoint.slotNumber} from peer.`,
240
- );
241
266
  return Promise.resolve(undefined);
242
267
  };
243
268
  }
@@ -252,8 +277,7 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
252
277
  * @param txPool - The transaction pool to be accessed by the service.
253
278
  * @returns The new service.
254
279
  */
255
- public static async new<T extends P2PClientType>(
256
- clientType: T,
280
+ public static async new(
257
281
  config: P2PConfig,
258
282
  peerId: PeerId,
259
283
  deps: {
@@ -305,11 +329,6 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
305
329
  const versions = getVersions(config);
306
330
  const protocolVersion = compressComponentVersions(versions);
307
331
 
308
- const txTopic = createTopicString(TopicType.tx, protocolVersion);
309
- const blockProposalTopic = createTopicString(TopicType.block_proposal, protocolVersion);
310
- const checkpointProposalTopic = createTopicString(TopicType.checkpoint_proposal, protocolVersion);
311
- const checkpointAttestationTopic = createTopicString(TopicType.checkpoint_attestation, protocolVersion);
312
-
313
332
  const preferredPeersEnrs: ENR[] = config.preferredPeers.map(enr => ENR.decodeTxt(enr));
314
333
  const directPeers = (
315
334
  await Promise.all(
@@ -329,6 +348,16 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
329
348
 
330
349
  const announceTcpMultiaddr = config.p2pIp ? [convertToMultiaddr(config.p2pIp, p2pPort, 'tcp')] : [];
331
350
 
351
+ // Create dynamic topic score params based on network configuration
352
+ const l1Constants = epochCache.getL1Constants();
353
+ const topicScoreParams = createAllTopicScoreParams(protocolVersion, {
354
+ slotDurationMs: l1Constants.slotDuration * 1000,
355
+ heartbeatIntervalMs: config.gossipsubInterval,
356
+ targetCommitteeSize: l1Constants.targetCommitteeSize,
357
+ blockDurationMs: config.blockDurationMs,
358
+ expectedBlockProposalsPerSlot: config.expectedBlockProposalsPerSlot,
359
+ });
360
+
332
361
  const node = await createLibp2p({
333
362
  start: false,
334
363
  peerId,
@@ -424,32 +453,12 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
424
453
  scoreParams: createPeerScoreParams({
425
454
  // IPColocation factor can be disabled for local testing - default to -5
426
455
  IPColocationFactorWeight: config.debugDisableColocationPenalty ? 0 : -5.0,
427
- topics: {
428
- [txTopic]: createTopicScoreParams({
429
- topicWeight: 1,
430
- invalidMessageDeliveriesWeight: -20,
431
- invalidMessageDeliveriesDecay: 0.5,
432
- }),
433
- [blockProposalTopic]: createTopicScoreParams({
434
- topicWeight: 1,
435
- invalidMessageDeliveriesWeight: -20,
436
- invalidMessageDeliveriesDecay: 0.5,
437
- }),
438
- [checkpointProposalTopic]: createTopicScoreParams({
439
- topicWeight: 1,
440
- invalidMessageDeliveriesWeight: -20,
441
- invalidMessageDeliveriesDecay: 0.5,
442
- }),
443
- [checkpointAttestationTopic]: createTopicScoreParams({
444
- topicWeight: 1,
445
- invalidMessageDeliveriesWeight: -20,
446
- invalidMessageDeliveriesDecay: 0.5,
447
- }),
448
- },
456
+ topics: topicScoreParams,
449
457
  }),
450
458
  }) as (components: GossipSubComponents) => GossipSub,
451
- components: (components: { connectionManager: ConnectionManager }) => ({
459
+ components: (components: { connectionManager: ConnectionManager; addressManager: AddressManager }) => ({
452
460
  connectionManager: components.connectionManager,
461
+ addressManager: components.addressManager,
453
462
  }),
454
463
  },
455
464
  logger: createLibp2pComponentLogger(logger.module, logger.getBindings()),
@@ -471,13 +480,16 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
471
480
  epochCache,
472
481
  );
473
482
 
474
- // Update gossipsub score params
475
- node.services.pubsub.score.params.appSpecificWeight = 10;
483
+ // Configure application-specific scoring for gossipsub.
484
+ // The weight scales app score to align with gossipsub thresholds:
485
+ // - Disconnect (-50) × 10 = -500 = gossipThreshold (stops receiving gossip)
486
+ // - Ban (-100) × 10 = -1000 = publishThreshold (cannot publish)
487
+ // Note: positive topic scores can offset penalties, so alignment is best-effort.
488
+ node.services.pubsub.score.params.appSpecificWeight = APP_SPECIFIC_WEIGHT;
476
489
  node.services.pubsub.score.params.appSpecificScore = (peerId: string) =>
477
490
  peerManager.shouldDisableP2PGossip(peerId) ? -Infinity : peerManager.getPeerScore(peerId);
478
491
 
479
492
  return new LibP2PService(
480
- clientType,
481
493
  config,
482
494
  node,
483
495
  peerDiscoveryService,
@@ -503,12 +515,11 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
503
515
  throw new Error('P2P service already started');
504
516
  }
505
517
 
506
- // Get listen & announce addresses for logging
507
518
  const { p2pIp, p2pPort } = this.config;
508
- if (!p2pIp) {
509
- throw new Error('Announce address not provided.');
519
+ if (!p2pIp && !this.config.queryForIp) {
520
+ throw new Error('Announce address not provided and queryForIp is not enabled.');
510
521
  }
511
- const announceTcpMultiaddr = convertToMultiaddr(p2pIp, p2pPort, 'tcp');
522
+ const announceTcpMultiaddr = p2pIp ? convertToMultiaddr(p2pIp, p2pPort, 'tcp') : undefined;
512
523
 
513
524
  // Create request response protocol handlers
514
525
  const txHandler = reqRespTxHandler(this.mempools);
@@ -524,7 +535,11 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
524
535
  };
525
536
 
526
537
  if (!this.config.disableTransactions) {
527
- const blockTxsHandler = reqRespBlockTxsHandler(this.mempools.attestationPool, this.mempools.txPool);
538
+ const blockTxsHandler = reqRespBlockTxsHandler(
539
+ this.mempools.attestationPool,
540
+ this.archiver,
541
+ this.mempools.txPool,
542
+ );
528
543
  requestResponseHandlers[ReqRespSubProtocol.BLOCK_TXS] = blockTxsHandler.bind(this);
529
544
  }
530
545
 
@@ -547,7 +562,7 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
547
562
  await this.node.start();
548
563
 
549
564
  // Subscribe to standard GossipSub topics by default
550
- for (const topic of getTopicsForClientAndConfig(this.clientType, this.config.disableTransactions)) {
565
+ for (const topic of getTopicsForConfig(this.config.disableTransactions)) {
551
566
  this.subscribeToTopic(this.topicStrings[topic]);
552
567
  }
553
568
 
@@ -558,6 +573,26 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
558
573
  if (!this.config.p2pDiscoveryDisabled) {
559
574
  await this.peerDiscoveryService.start();
560
575
  }
576
+
577
+ // Bridge discv5 IP changes to libp2p's AddressManager so peers see the updated address
578
+ if (this.config.queryForIp) {
579
+ this.ipChangedHandler = (ip: string) => {
580
+ const addressManager = this.node.services.components.addressManager;
581
+ const newAddr = multiaddr(convertToMultiaddr(ip, this.config.p2pPort, 'tcp'));
582
+
583
+ if (this.discoveredP2pIp) {
584
+ const oldAddr = multiaddr(convertToMultiaddr(this.discoveredP2pIp, this.config.p2pPort, 'tcp'));
585
+ addressManager.removeObservedAddr(oldAddr);
586
+ }
587
+
588
+ addressManager.addObservedAddr(newAddr);
589
+ addressManager.confirmObservedAddr(newAddr);
590
+ this.discoveredP2pIp = ip;
591
+ this.logger.info('Public IP discovered via discv5', { ip });
592
+ };
593
+ this.peerDiscoveryService.on('ip:changed', this.ipChangedHandler);
594
+ }
595
+
561
596
  this.discoveryRunningPromise = new RunningPromise(
562
597
  async () => {
563
598
  await this.peerManager.heartbeat();
@@ -583,6 +618,11 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
583
618
  // Remove gossip sub listener
584
619
  this.node.services.pubsub.removeEventListener(GossipSubEvent.MESSAGE, this.gossipSubEventHandler);
585
620
 
621
+ if (this.ipChangedHandler) {
622
+ this.peerDiscoveryService.removeListener('ip:changed', this.ipChangedHandler);
623
+ this.ipChangedHandler = undefined;
624
+ }
625
+
586
626
  // Stop peer manager
587
627
  this.logger.debug('Stopping peer manager...');
588
628
  await this.peerManager.stop();
@@ -613,6 +653,10 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
613
653
  return this.peerManager.getPeers(includePending);
614
654
  }
615
655
 
656
+ public getGossipMeshPeerCount(topicType: TopicType): number {
657
+ return this.node.services.pubsub.getMeshPeers(this.topicStrings[topicType]).length;
658
+ }
659
+
616
660
  private handleGossipSubEvent(e: CustomEvent<GossipsubMessage>) {
617
661
  this.logger.trace(`Received PUBSUB message.`);
618
662
 
@@ -661,8 +705,35 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
661
705
  this.blockReceivedCallback = callback;
662
706
  }
663
707
 
664
- public registerCheckpointReceivedCallback(callback: P2PCheckpointReceivedCallback) {
665
- this.checkpointReceivedCallback = callback;
708
+ public registerValidatorCheckpointReceivedCallback(callback: P2PCheckpointReceivedCallback) {
709
+ this.validatorCheckpointReceivedCallback = callback;
710
+ }
711
+
712
+ public registerAllNodesCheckpointReceivedCallback(callback: P2PCheckpointReceivedCallback) {
713
+ this.allNodesCheckpointReceivedCallback = callback;
714
+ }
715
+
716
+ public async notifyOwnCheckpointProposal(checkpoint: CheckpointProposalCore): Promise<void> {
717
+ await this.allNodesCheckpointReceivedCallback(checkpoint, this.node.peerId);
718
+ }
719
+
720
+ /**
721
+ * Registers a callback to be invoked when a duplicate proposal is detected.
722
+ * This callback is triggered on the first duplicate (when count goes from 1 to 2).
723
+ */
724
+ public registerDuplicateProposalCallback(
725
+ callback: (info: { slot: SlotNumber; proposer: EthAddress; type: 'checkpoint' | 'block' }) => void,
726
+ ): void {
727
+ this.duplicateProposalCallback = callback;
728
+ }
729
+
730
+ /**
731
+ * Registers a callback to be invoked when a duplicate attestation is detected.
732
+ * A validator signing attestations for different proposals at the same slot.
733
+ * This callback is triggered on the first duplicate (when count goes from 1 to 2).
734
+ */
735
+ public registerDuplicateAttestationCallback(callback: P2PDuplicateAttestationCallback): void {
736
+ this.duplicateAttestationCallback = callback;
666
737
  }
667
738
 
668
739
  /**
@@ -729,6 +800,9 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
729
800
  if (!validator || !validator.addMessage(msgId)) {
730
801
  this.instrumentation.incMessagePrevalidationStatus(false, topicType);
731
802
  this.node.services.pubsub.reportMessageValidationResult(msgId, source.toString(), TopicValidatorResult.Ignore);
803
+ if (topicType === TopicType.tx) {
804
+ this.logger.verbose(`Ignoring already-seen tx gossip message`, { msgId, source: source.toString() });
805
+ }
732
806
  return { result: false, topicType };
733
807
  }
734
808
 
@@ -793,9 +867,7 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
793
867
  if (msg.topic === this.topicStrings[TopicType.tx]) {
794
868
  await this.handleGossipedTx(p2pMessage.payload, msgId, source);
795
869
  } else if (msg.topic === this.topicStrings[TopicType.checkpoint_attestation]) {
796
- if (this.clientType === P2PClientType.Full) {
797
- await this.processCheckpointAttestationFromPeer(p2pMessage.payload, msgId, source);
798
- }
870
+ await this.processCheckpointAttestationFromPeer(p2pMessage.payload, msgId, source);
799
871
  } else if (msg.topic === this.topicStrings[TopicType.block_proposal]) {
800
872
  await this.processBlockFromPeer(p2pMessage.payload, msgId, source);
801
873
  } else if (msg.topic === this.topicStrings[TopicType.checkpoint_proposal]) {
@@ -851,51 +923,134 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
851
923
  return;
852
924
  }
853
925
 
854
- protected async validateReceivedMessage<T>(
855
- validationFunc: () => Promise<ReceivedMessageValidationResult<T>>,
926
+ protected async validateReceivedMessage<T, M = undefined>(
927
+ validationFunc: () => Promise<ReceivedMessageValidationResult<T, M>>,
856
928
  msgId: string,
857
929
  source: PeerId,
858
930
  topicType: TopicType,
859
- ): Promise<ReceivedMessageValidationResult<T>> {
860
- let resultAndObj: ReceivedMessageValidationResult<T> = { result: TopicValidatorResult.Reject };
931
+ ): Promise<ReceivedMessageValidationResult<T, M>> {
932
+ // Default to reject result with a penalty if validation function throws an error
933
+ let resultAndObj: ReceivedMessageValidationResult<T, M> = {
934
+ result: TopicValidatorResult.Reject,
935
+ severity: PeerErrorSeverity.MidToleranceError,
936
+ };
861
937
  const timer = new Timer();
862
938
  try {
863
939
  resultAndObj = await validationFunc();
864
940
  } catch (err) {
865
- this.peerManager.penalizePeer(source, PeerErrorSeverity.LowToleranceError);
866
- this.logger.error(`Error deserializing and validating gossipsub message`, err, {
867
- msgId,
868
- source: source.toString(),
869
- topicType,
870
- });
941
+ this.logger.error(`Error validating gossipsub message`, err, { msgId, source: source.toString(), topicType });
871
942
  }
872
943
 
873
944
  if (resultAndObj.result === TopicValidatorResult.Accept) {
945
+ this.logger.debug(`Message ${topicType} accepted by validator`, { msgId, source: source.toString(), topicType });
874
946
  this.instrumentation.recordMessageValidation(topicType, timer);
947
+ } else if (resultAndObj.result === TopicValidatorResult.Reject) {
948
+ this.logger.warn(`Message ${topicType} rejected by validator with severity ${resultAndObj.severity}`, {
949
+ msgId,
950
+ source: source.toString(),
951
+ topicType,
952
+ severity: resultAndObj.severity,
953
+ });
954
+ this.peerManager.penalizePeer(source, resultAndObj.severity);
955
+ } else {
956
+ this.logger.trace(`Message ${topicType} ignored by validator`, { msgId, source: source.toString(), topicType });
875
957
  }
876
958
 
877
959
  this.node.services.pubsub.reportMessageValidationResult(msgId, source.toString(), resultAndObj.result);
878
960
  return resultAndObj;
879
961
  }
880
962
 
963
+ private tryDeserialize<T>(deserializeFunc: () => T, msgId: string, source: PeerId): T | undefined {
964
+ try {
965
+ return deserializeFunc();
966
+ } catch (err) {
967
+ this.logger.warn(`Failed to deserialize gossipsub message from buffer`, {
968
+ err,
969
+ msgId,
970
+ source: source.toString(),
971
+ });
972
+ return undefined;
973
+ }
974
+ }
975
+
881
976
  protected async handleGossipedTx(payloadData: Buffer, msgId: string, source: PeerId) {
882
977
  const validationFunc: () => Promise<ReceivedMessageValidationResult<Tx>> = async () => {
883
- const tx = Tx.fromBuffer(payloadData);
884
- const isValid = await this.validatePropagatedTx(tx, source);
885
- const exists = isValid && (await this.mempools.txPool.hasTx(tx.getTxHash()));
978
+ const tx = this.tryDeserialize(() => Tx.fromBuffer(payloadData), msgId, source);
979
+ if (!tx) {
980
+ return { result: TopicValidatorResult.Reject, severity: PeerErrorSeverity.LowToleranceError };
981
+ }
982
+
983
+ const currentBlockNumber = await this.archiver.getBlockNumber();
984
+ const { ts: nextSlotTimestamp } = this.epochCache.getEpochAndSlotInNextL1Slot();
985
+
986
+ // Stage 1: fast validators (metadata, data, timestamps, double-spend, gas, phases, block header)
987
+ const firstStageValidators = await this.createFirstStageMessageValidators(currentBlockNumber, nextSlotTimestamp);
988
+ const firstStageOutcome = await this.runValidations(tx, firstStageValidators);
989
+ if (!firstStageOutcome.allPassed) {
990
+ const { name } = firstStageOutcome.failure;
991
+ let { severity } = firstStageOutcome.failure;
992
+
993
+ // Double spend validator has a special case handler. We perform more detailed examination
994
+ // as to how recently the nullifier was entered into the tree and if the transaction should
995
+ // have 'known' the nullifier existed. This determines the severity of the penalty applied to the peer.
996
+ if (name === 'doubleSpendValidator') {
997
+ const txBlockNumber = BlockNumber(currentBlockNumber + 1);
998
+ severity = await this.handleDoubleSpendFailure(tx, txBlockNumber);
999
+ }
1000
+
1001
+ this.logger.verbose(`Rejecting gossiped tx ${tx.getTxHash().toString()}: stage 1 validation failed`, {
1002
+ validator: name,
1003
+ severity,
1004
+ source: source.toString(),
1005
+ });
1006
+ return { result: TopicValidatorResult.Reject, severity };
1007
+ }
1008
+
1009
+ // Pool pre-check: see if the pool would accept this tx before doing expensive proof verification
1010
+ const canAdd = await this.mempools.txPool.canAddPendingTx(tx);
1011
+ if (canAdd === 'ignored') {
1012
+ this.logger.verbose(`Ignoring gossiped tx ${tx.getTxHash().toString()}: pool pre-check returned ignored`, {
1013
+ source: source.toString(),
1014
+ });
1015
+ return { result: TopicValidatorResult.Ignore, obj: tx };
1016
+ }
1017
+
1018
+ // Stage 2: expensive proof verification
1019
+ const secondStageValidators = this.createSecondStageMessageValidators();
1020
+ const secondStageOutcome = await this.runValidations(tx, secondStageValidators);
1021
+ if (!secondStageOutcome.allPassed) {
1022
+ const { severity, name } = secondStageOutcome.failure;
1023
+ this.logger.verbose(`Rejecting gossiped tx ${tx.getTxHash().toString()}: stage 2 validation failed`, {
1024
+ validator: name,
1025
+ severity,
1026
+ source: source.toString(),
1027
+ });
1028
+ return { result: TopicValidatorResult.Reject, severity };
1029
+ }
1030
+
1031
+ // Pool add: persist the tx
1032
+ const txHash = tx.getTxHash();
1033
+ const addResult = await this.mempools.txPool.addPendingTxs([tx], { source: 'gossip' });
1034
+
1035
+ const wasAccepted = addResult.accepted.some(h => h.equals(txHash));
1036
+ const wasIgnored = addResult.ignored.some(h => h.equals(txHash));
886
1037
 
887
- this.logger.trace(`Validate propagated tx`, {
888
- isValid,
889
- exists,
1038
+ this.logger.verbose(`Validate propagated tx ${txHash.toString()}`, {
1039
+ wasAccepted,
1040
+ wasIgnored,
890
1041
  [Attributes.P2P_ID]: source.toString(),
891
1042
  });
892
1043
 
893
- if (!isValid) {
894
- return { result: TopicValidatorResult.Reject };
895
- } else if (exists) {
1044
+ if (wasAccepted) {
1045
+ return { result: TopicValidatorResult.Accept, obj: tx };
1046
+ } else if (wasIgnored) {
896
1047
  return { result: TopicValidatorResult.Ignore, obj: tx };
897
1048
  } else {
898
- return { result: TopicValidatorResult.Accept, obj: tx };
1049
+ this.logger.warn(`Gossiped tx ${txHash.toString()} unexpectedly rejected by pool`, {
1050
+ source: source.toString(),
1051
+ txHash: txHash.toString(),
1052
+ });
1053
+ return { result: TopicValidatorResult.Reject, severity: PeerErrorSeverity.HighToleranceError };
899
1054
  }
900
1055
  };
901
1056
 
@@ -904,6 +1059,7 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
904
1059
  return;
905
1060
  }
906
1061
 
1062
+ // Tx was accepted into pool and will be propagated - just log and record metrics
907
1063
  const txHash = tx.getTxHash();
908
1064
  const txHashString = txHash.toString();
909
1065
  this.logger.verbose(`Received tx ${txHashString} from external peer ${source.toString()} via gossip`, {
@@ -911,13 +1067,7 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
911
1067
  txHash: txHashString,
912
1068
  });
913
1069
 
914
- if (this.config.dropTransactions && randomInt(1000) < this.config.dropTransactionsProbability * 1000) {
915
- this.logger.warn(`Intentionally dropping tx ${txHashString} (probability rule)`);
916
- return;
917
- }
918
-
919
1070
  this.instrumentation.incrementTxReceived(1);
920
- await this.mempools.txPool.addTxs([tx]);
921
1071
  }
922
1072
 
923
1073
  /**
@@ -929,47 +1079,17 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
929
1079
  msgId: string,
930
1080
  source: PeerId,
931
1081
  ): Promise<void> {
932
- const validationFunc: () => Promise<ReceivedMessageValidationResult<CheckpointAttestation>> = async () => {
933
- const attestation = CheckpointAttestation.fromBuffer(payloadData);
934
- const pool = this.mempools.attestationPool;
935
- const validationResult = await this.validateCheckpointAttestation(source, attestation);
936
- const isValid = validationResult.result === 'accept';
937
- const exists = isValid && (await pool.hasCheckpointAttestation(attestation));
938
-
939
- let canAdd = true;
940
- if (isValid && !exists) {
941
- const slot = attestation.payload.header.slotNumber;
942
- const { committee } = await this.epochCache.getCommittee(slot);
943
- const committeeSize = committee?.length ?? 0;
944
- canAdd = await pool.canAddCheckpointAttestation(attestation, committeeSize);
945
- }
946
-
947
- this.logger.trace(`Validate propagated checkpoint attestation`, {
948
- isValid,
949
- exists,
950
- canAdd,
951
- [Attributes.SLOT_NUMBER]: attestation.payload.header.slotNumber.toString(),
952
- [Attributes.P2P_ID]: source.toString(),
953
- });
954
-
955
- if (validationResult.result === 'reject') {
956
- return { result: TopicValidatorResult.Reject };
957
- } else if (validationResult.result === 'ignore' || exists) {
958
- return { result: TopicValidatorResult.Ignore, obj: attestation };
959
- } else if (!canAdd) {
960
- this.logger.warn(`Dropping checkpoint attestation due to per-(slot, proposalId) attestation cap`, {
961
- slot: attestation.payload.header.slotNumber.toString(),
962
- archive: attestation.archive.toString(),
963
- source: source.toString(),
964
- });
965
- return { result: TopicValidatorResult.Ignore, obj: attestation };
966
- } else {
967
- return { result: TopicValidatorResult.Accept, obj: attestation };
968
- }
969
- };
970
-
971
1082
  const { result, obj: attestation } = await this.validateReceivedMessage<CheckpointAttestation>(
972
- validationFunc,
1083
+ () => {
1084
+ const attestation = this.tryDeserialize(() => CheckpointAttestation.fromBuffer(payloadData), msgId, source);
1085
+ if (!attestation) {
1086
+ return Promise.resolve({
1087
+ result: TopicValidatorResult.Reject,
1088
+ severity: PeerErrorSeverity.LowToleranceError,
1089
+ });
1090
+ }
1091
+ return this.validateAndStoreCheckpointAttestation(source, attestation);
1092
+ },
973
1093
  msgId,
974
1094
  source,
975
1095
  TopicType.checkpoint_attestation,
@@ -979,8 +1099,8 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
979
1099
  return;
980
1100
  }
981
1101
 
982
- this.logger.debug(
983
- `Received checkpoint attestation for slot ${attestation.slotNumber} from external peer ${source.toString()}`,
1102
+ this.logger.verbose(
1103
+ `Received valid checkpoint attestation for slot ${attestation.slotNumber} from external peer ${source.toString()}`,
984
1104
  {
985
1105
  p2pMessageIdentifier: await attestation.p2pMessageLoggingIdentifier(),
986
1106
  slot: attestation.slotNumber,
@@ -988,60 +1108,168 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
988
1108
  source: source.toString(),
989
1109
  },
990
1110
  );
991
-
992
- await this.mempools.attestationPool.addCheckpointAttestations([attestation]);
993
1111
  }
994
1112
 
995
- private async processBlockFromPeer(payloadData: Buffer, msgId: string, source: PeerId): Promise<void> {
996
- const validationFunc: () => Promise<ReceivedMessageValidationResult<BlockProposal>> = async () => {
997
- const block = BlockProposal.fromBuffer(payloadData);
998
- const validationResult = await this.validateBlockProposal(source, block);
999
- const isValid = validationResult.result === 'accept';
1000
- const pool = this.mempools.attestationPool;
1001
-
1002
- const exists = isValid && (await pool.hasBlockProposal(block));
1003
- const canAdd = isValid && (await pool.canAddProposal(block));
1004
-
1005
- this.logger.trace(`Validate propagated block proposal`, {
1006
- isValid,
1007
- exists,
1008
- canAdd,
1009
- [Attributes.SLOT_NUMBER]: block.slotNumber.toString(),
1010
- [Attributes.P2P_ID]: source.toString(),
1113
+ /** Validates a checkpoint attestation and adds it to the pool. Penalizes the peer if validation fails. */
1114
+ @trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId, attestation) => ({
1115
+ [Attributes.SLOT_NUMBER]: attestation.payload.header.slotNumber.toString(),
1116
+ }))
1117
+ protected async validateAndStoreCheckpointAttestation(
1118
+ peerId: PeerId,
1119
+ attestation: CheckpointAttestation,
1120
+ ): Promise<ReceivedMessageValidationResult<CheckpointAttestation>> {
1121
+ const validationResult = await this.checkpointAttestationValidator.validate(attestation);
1122
+
1123
+ if (validationResult.result === 'reject') {
1124
+ this.logger.warn(`Penalizing peer ${peerId} for checkpoint attestation validation failure`);
1125
+ return { result: TopicValidatorResult.Reject, severity: validationResult.severity };
1126
+ }
1127
+
1128
+ if (validationResult.result === 'ignore') {
1129
+ return { result: TopicValidatorResult.Ignore, obj: attestation };
1130
+ }
1131
+
1132
+ // Try to add the attestation: this handles existence check, cap check, and adding in one call
1133
+ // count is the number of attestations by this signer for this slot (for duplicate detection)
1134
+ const slot = attestation.payload.header.slotNumber;
1135
+ const { added, alreadyExists, count } =
1136
+ await this.mempools.attestationPool.tryAddCheckpointAttestation(attestation);
1137
+
1138
+ this.logger.trace(`Validate propagated checkpoint attestation`, {
1139
+ added,
1140
+ alreadyExists,
1141
+ count,
1142
+ [Attributes.SLOT_NUMBER]: slot.toString(),
1143
+ [Attributes.P2P_ID]: peerId.toString(),
1144
+ });
1145
+
1146
+ // Exact same attestation received, no need to re-broadcast
1147
+ if (alreadyExists) {
1148
+ return { result: TopicValidatorResult.Ignore, obj: attestation };
1149
+ }
1150
+
1151
+ // Could not add (cap reached for signer), penalize and do not re-broadcast
1152
+ if (!added) {
1153
+ this.logger.warn(`Rejecting checkpoint attestation due to cap`, {
1154
+ slot: slot.toString(),
1155
+ archive: attestation.archive.toString(),
1156
+ source: peerId.toString(),
1157
+ attester: attestation.getSender()?.toString(),
1158
+ count,
1011
1159
  });
1160
+ return { result: TopicValidatorResult.Reject, severity: PeerErrorSeverity.HighToleranceError };
1161
+ }
1012
1162
 
1013
- if (validationResult.result === 'reject') {
1014
- return { result: TopicValidatorResult.Reject };
1015
- } else if (validationResult.result === 'ignore' || exists) {
1016
- return { result: TopicValidatorResult.Ignore, obj: block };
1017
- } else if (!canAdd) {
1018
- this.peerManager.penalizePeer(source, PeerErrorSeverity.MidToleranceError);
1019
- this.logger.warn(`Penalizing peer for block proposal exceeding per-slot cap`, {
1020
- slot: block.slotNumber.toString(),
1021
- archive: block.archive.toString(),
1022
- source: source.toString(),
1163
+ // Check if this is a duplicate attestation (signer attested to a different proposal at the same slot)
1164
+ // count is the number of attestations by this signer for this slot
1165
+ if (count === 2) {
1166
+ const attester = attestation.getSender();
1167
+ if (attester) {
1168
+ this.logger.warn(`Detected duplicate attestation (equivocation) at slot ${slot}`, {
1169
+ slot: slot.toString(),
1170
+ archive: attestation.archive.toString(),
1171
+ source: peerId.toString(),
1172
+ attester: attester.toString(),
1023
1173
  });
1024
- return { result: TopicValidatorResult.Reject };
1025
- } else {
1026
- return { result: TopicValidatorResult.Accept, obj: block };
1174
+ this.duplicateAttestationCallback?.({ slot, attester });
1027
1175
  }
1028
- };
1176
+ }
1177
+
1178
+ // Attestation was added successfully - accept it so other nodes can also detect the equivocation
1179
+ return { result: TopicValidatorResult.Accept, obj: attestation };
1180
+ }
1029
1181
 
1030
- const { result, obj: block } = await this.validateReceivedMessage<BlockProposal>(
1031
- validationFunc,
1182
+ protected async processBlockFromPeer(payloadData: Buffer, msgId: string, source: PeerId): Promise<void> {
1183
+ const {
1184
+ result,
1185
+ obj: block,
1186
+ metadata: { isEquivocated } = {},
1187
+ } = await this.validateReceivedMessage<BlockProposal, { isEquivocated: boolean }>(
1188
+ () => this.validateAndStoreBlockProposal(source, BlockProposal.fromBuffer(payloadData)),
1032
1189
  msgId,
1033
1190
  source,
1034
1191
  TopicType.block_proposal,
1035
1192
  );
1036
1193
 
1037
- if (!result || !block) {
1194
+ // If not accepted or equivocated, return
1195
+ if (result !== TopicValidatorResult.Accept || !block || isEquivocated) {
1038
1196
  return;
1039
1197
  }
1040
1198
 
1041
1199
  await this.processValidBlockProposal(block, source);
1042
1200
  }
1043
1201
 
1044
- // REVIEW: callback pattern https://github.com/AztecProtocol/aztec-packages/issues/7963
1202
+ /** Validates a block proposal. Triggers a penalization to the peer that sent it if invalid. Adds to the mempool if valid. */
1203
+ @trackSpan('Libp2pService.validateAndStoreBlockProposal', (_peerId, block) => ({
1204
+ [Attributes.BLOCK_NUMBER]: block.blockNumber.toString(),
1205
+ [Attributes.SLOT_NUMBER]: block.slotNumber.toString(),
1206
+ }))
1207
+ protected async validateAndStoreBlockProposal(
1208
+ peerId: PeerId,
1209
+ block: BlockProposal,
1210
+ ): Promise<ReceivedMessageValidationResult<BlockProposal, { isEquivocated: boolean }>> {
1211
+ const validationResult = await this.blockProposalValidator.validate(block);
1212
+
1213
+ if (validationResult.result === 'reject') {
1214
+ this.logger.warn(`Penalizing peer ${peerId} for block proposal validation failure`);
1215
+ return { result: TopicValidatorResult.Reject, severity: validationResult.severity };
1216
+ }
1217
+
1218
+ if (validationResult.result === 'ignore') {
1219
+ return { result: TopicValidatorResult.Ignore, obj: block };
1220
+ }
1221
+
1222
+ // Try to add the proposal: this handles existence check, cap check, and adding in one call
1223
+ const { added, alreadyExists, count } = await this.mempools.attestationPool.tryAddBlockProposal(block);
1224
+ const isEquivocated = count !== undefined && count > 1;
1225
+
1226
+ // Duplicate proposal received, no need to re-broadcast
1227
+ if (alreadyExists) {
1228
+ this.logger.debug(`Ignoring duplicate block proposal received`, {
1229
+ ...block.toBlockInfo(),
1230
+ indexWithinCheckpoint: block.indexWithinCheckpoint,
1231
+ proposer: block.getSender()?.toString(),
1232
+ source: peerId.toString(),
1233
+ });
1234
+ return { result: TopicValidatorResult.Ignore, obj: block, metadata: { isEquivocated } };
1235
+ }
1236
+
1237
+ // Too many blocks received for this slot and index, penalize peer and do not re-broadcast
1238
+ if (!added) {
1239
+ this.logger.warn(`Penalizing peer for block proposal exceeding per-position cap`, {
1240
+ ...block.toBlockInfo(),
1241
+ indexWithinCheckpoint: block.indexWithinCheckpoint,
1242
+ count,
1243
+ proposer: block.getSender()?.toString(),
1244
+ source: peerId.toString(),
1245
+ });
1246
+ return {
1247
+ result: TopicValidatorResult.Reject,
1248
+ metadata: { isEquivocated },
1249
+ severity: PeerErrorSeverity.HighToleranceError,
1250
+ };
1251
+ }
1252
+
1253
+ // If this was a duplicate proposal, do not process it, but do invoke the duplicate callback,
1254
+ // and do re-broadcast it so other nodes in the network know to slash the proposer
1255
+ if (isEquivocated) {
1256
+ const proposer = block.getSender();
1257
+ this.logger.warn(`Detected duplicate block proposal (equivocation) at slot ${block.slotNumber}`, {
1258
+ ...block.toBlockInfo(),
1259
+ source: peerId.toString(),
1260
+ proposer: proposer?.toString(),
1261
+ });
1262
+ // Invoke the duplicate callback on the first duplicate spotted only
1263
+ if (proposer && count === 2) {
1264
+ this.duplicateProposalCallback?.({ slot: block.slotNumber, proposer, type: 'block' });
1265
+ }
1266
+ return { result: TopicValidatorResult.Accept, obj: block, metadata: { isEquivocated } };
1267
+ }
1268
+
1269
+ // Otherwise, we're good to go!
1270
+ return { result: TopicValidatorResult.Accept, obj: block };
1271
+ }
1272
+
1045
1273
  // REFACTOR(palla): This method should be moved to the p2p_client or to a separate component,
1046
1274
  // should not be here as it does not deal with p2p networking.
1047
1275
  @trackSpan('Libp2pService.processValidBlockProposal', async block => ({
@@ -1049,7 +1277,7 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1049
1277
  [Attributes.BLOCK_ARCHIVE]: block.archive.toString(),
1050
1278
  [Attributes.P2P_ID]: await block.p2pMessageLoggingIdentifier().then(i => i.toString()),
1051
1279
  }))
1052
- private async processValidBlockProposal(block: BlockProposal, sender: PeerId) {
1280
+ protected async processValidBlockProposal(block: BlockProposal, sender: PeerId) {
1053
1281
  const slot = block.slotNumber;
1054
1282
  this.logger.verbose(`Received block proposal for slot ${slot} from external peer ${sender.toString()}.`, {
1055
1283
  p2pMessageIdentifier: await block.p2pMessageLoggingIdentifier(),
@@ -1057,30 +1285,14 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1057
1285
  ...block.toBlockInfo(),
1058
1286
  });
1059
1287
 
1060
- // Attempt to add proposal
1061
- try {
1062
- await this.mempools.attestationPool.addBlockProposal(block);
1063
- } catch (err: unknown) {
1064
- // Drop proposals if we hit per-slot cap in the attestation pool; rethrow unknown errors
1065
- if (err instanceof ProposalSlotCapExceededError) {
1066
- this.logger.warn(`Dropping block proposal due to per-slot proposal cap`, {
1067
- slot: String(slot),
1068
- archive: block.archive.toString(),
1069
- error: (err as Error).message,
1070
- });
1071
- return;
1072
- }
1073
- throw err;
1074
- }
1075
-
1076
- // Mark the txs in this proposal as non-evictable
1077
- await this.mempools.txPool.markTxsAsNonEvictable(block.txHashes);
1288
+ // Mark the txs in this proposal as protected
1289
+ await this.mempools.txPool.protectTxs(block.txHashes, block.blockHeader);
1078
1290
 
1079
1291
  // Call the block received callback to validate the proposal.
1080
1292
  // Note: Validators do NOT attest to individual blocks, only to checkpoint proposals.
1081
1293
  const isValid = await this.blockReceivedCallback(block, sender);
1082
1294
  if (!isValid) {
1083
- this.logger.warn(`Block proposal validation failed for block ${block.blockNumber}`, block.toBlockInfo());
1295
+ this.logger.info(`Block proposal validation failed for block ${block.blockNumber}`, block.toBlockInfo());
1084
1296
  }
1085
1297
  }
1086
1298
 
@@ -1088,67 +1300,149 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1088
1300
  * Handle a gossiped checkpoint proposal.
1089
1301
  * Validates and processes the checkpoint proposal, then triggers the callback for attestation.
1090
1302
  */
1091
- private async handleGossipedCheckpointProposal(payloadData: Buffer, msgId: string, source: PeerId): Promise<void> {
1092
- // TODO(palla/mbps): This pattern is repeated across multiple message handlers, consider abstracting it.
1093
- const validationFunc: () => Promise<ReceivedMessageValidationResult<CheckpointProposal>> = async () => {
1094
- const checkpoint = CheckpointProposal.fromBuffer(payloadData);
1095
- const validationResult = await this.validateCheckpointProposal(source, checkpoint);
1096
- const isValid = validationResult.result === 'accept';
1097
- const pool = this.mempools.attestationPool;
1098
-
1099
- const exists = isValid && (await pool.hasCheckpointProposal(checkpoint));
1100
- const canAdd = isValid && (await pool.canAddCheckpointProposal(checkpoint));
1101
-
1102
- this.logger.trace(`Validate propagated checkpoint proposal`, {
1103
- isValid,
1104
- exists,
1105
- canAdd,
1106
- [Attributes.SLOT_NUMBER]: checkpoint.slotNumber.toString(),
1107
- [Attributes.P2P_ID]: source.toString(),
1108
- });
1109
-
1110
- if (validationResult.result === 'reject') {
1111
- return { result: TopicValidatorResult.Reject };
1112
- } else if (validationResult.result === 'ignore' || exists) {
1113
- return { result: TopicValidatorResult.Ignore, obj: checkpoint };
1114
- } else if (!canAdd) {
1115
- this.peerManager.penalizePeer(source, PeerErrorSeverity.MidToleranceError);
1116
- this.logger.warn(`Penalizing peer for checkpoint proposal exceeding per-slot cap`, {
1117
- slot: checkpoint.slotNumber.toString(),
1118
- archive: checkpoint.archive.toString(),
1119
- source: source.toString(),
1120
- });
1121
- return { result: TopicValidatorResult.Reject };
1122
- } else {
1123
- return { result: TopicValidatorResult.Accept, obj: checkpoint };
1124
- }
1125
- };
1126
-
1127
- const { result, obj: checkpoint } = await this.validateReceivedMessage<CheckpointProposal>(
1128
- validationFunc,
1303
+ protected async handleGossipedCheckpointProposal(payloadData: Buffer, msgId: string, source: PeerId): Promise<void> {
1304
+ const {
1305
+ result,
1306
+ obj: checkpoint,
1307
+ metadata: { isEquivocated, processBlock } = {},
1308
+ } = await this.validateReceivedMessage<CheckpointProposal, { isEquivocated: boolean; processBlock: boolean }>(
1309
+ () => this.validateAndStoreCheckpointProposal(source, CheckpointProposal.fromBuffer(payloadData)),
1129
1310
  msgId,
1130
1311
  source,
1131
1312
  TopicType.checkpoint_proposal,
1132
1313
  );
1133
1314
 
1134
- if (result !== TopicValidatorResult.Accept || !checkpoint) {
1315
+ // If the checkpoint contained a valid last block, we process it even if the checkpoint itself is to be rejected
1316
+ // TODO(palla/mbps): Is this ok? Should we be considering a block from a checkpoint that was equivocated?
1317
+ if (processBlock && checkpoint?.getBlockProposal()) {
1318
+ await this.processValidBlockProposal(checkpoint.getBlockProposal()!, source);
1319
+ }
1320
+
1321
+ if (result !== TopicValidatorResult.Accept || !checkpoint || isEquivocated) {
1135
1322
  return;
1136
1323
  }
1137
1324
 
1138
- await this.processValidCheckpointProposal(checkpoint, source);
1325
+ await this.processValidCheckpointProposal(checkpoint.toCore(), source);
1326
+ }
1327
+
1328
+ /**
1329
+ * Validates a checkpoint proposal. Penalizes peer if validation fails. Adds the checkpoint and
1330
+ * its last block (if present) to the mempool if valid. Triggers equivocation detection on both.
1331
+ */
1332
+ @trackSpan('Libp2pService.validateAndStoreCheckpointProposal', (_peerId, checkpoint) => ({
1333
+ [Attributes.SLOT_NUMBER]: checkpoint.slotNumber.toString(),
1334
+ }))
1335
+ protected async validateAndStoreCheckpointProposal(
1336
+ peerId: PeerId,
1337
+ checkpoint: CheckpointProposal,
1338
+ ): Promise<ReceivedMessageValidationResult<CheckpointProposal, { isEquivocated: boolean; processBlock: boolean }>> {
1339
+ const validationResult = await this.checkpointProposalValidator.validate(checkpoint);
1340
+
1341
+ if (validationResult.result === 'reject') {
1342
+ this.logger.warn(`Penalizing peer ${peerId} for checkpoint proposal validation failure`);
1343
+ return { result: TopicValidatorResult.Reject, severity: validationResult.severity };
1344
+ }
1345
+
1346
+ if (validationResult.result === 'ignore') {
1347
+ return { result: TopicValidatorResult.Ignore, obj: checkpoint };
1348
+ }
1349
+
1350
+ // Extract and try to add the block proposal first if present
1351
+ const blockProposal = checkpoint.getBlockProposal();
1352
+ let processBlock = false;
1353
+ if (blockProposal) {
1354
+ this.logger.debug(`Validating block proposal from propagated checkpoint`, {
1355
+ [Attributes.SLOT_NUMBER]: checkpoint.slotNumber.toString(),
1356
+ [Attributes.P2P_ID]: peerId.toString(),
1357
+ });
1358
+ const blockProposalResult = await this.validateAndStoreBlockProposal(peerId, blockProposal);
1359
+ const { obj, metadata: { isEquivocated } = {} } = blockProposalResult;
1360
+ if (blockProposalResult.result === TopicValidatorResult.Reject || !obj || isEquivocated) {
1361
+ this.logger.debug(`Rejecting checkpoint due to invalid last block proposal`, {
1362
+ [Attributes.SLOT_NUMBER]: checkpoint.slotNumber.toString(),
1363
+ [Attributes.P2P_ID]: peerId.toString(),
1364
+ isEquivocated,
1365
+ result: blockProposalResult.result,
1366
+ });
1367
+ return {
1368
+ result: TopicValidatorResult.Reject,
1369
+ severity:
1370
+ 'severity' in blockProposalResult ? blockProposalResult.severity : PeerErrorSeverity.MidToleranceError,
1371
+ };
1372
+ } else if (blockProposalResult.result === TopicValidatorResult.Accept && obj && !isEquivocated) {
1373
+ processBlock = true;
1374
+ }
1375
+ }
1376
+
1377
+ // Try to add the checkpoint proposal core: this handles existence check, cap check, and adding in one call
1378
+ const checkpointCore = checkpoint.toCore();
1379
+ const tryAddResult = await this.mempools.attestationPool.tryAddCheckpointProposal(checkpointCore);
1380
+ const { added, alreadyExists, count } = tryAddResult;
1381
+ const isEquivocated = count !== undefined && count > 1;
1382
+
1383
+ // Duplicate proposal received, do not re-broadcast
1384
+ if (alreadyExists) {
1385
+ this.logger.debug(`Ignoring duplicate checkpoint proposal received`, {
1386
+ ...checkpoint.toCheckpointInfo(),
1387
+ source: peerId.toString(),
1388
+ });
1389
+ return {
1390
+ result: TopicValidatorResult.Ignore,
1391
+ obj: checkpoint,
1392
+ metadata: { isEquivocated, processBlock },
1393
+ };
1394
+ }
1395
+
1396
+ // Too many checkpoint proposals received for this slot, penalize peer and do not re-broadcast
1397
+ // Note: We still return the checkpoint obj so the lastBlock can be processed if valid
1398
+ if (!added) {
1399
+ this.logger.warn(`Penalizing peer for checkpoint proposal exceeding per-slot cap`, {
1400
+ ...checkpoint.toCheckpointInfo(),
1401
+ count,
1402
+ source: peerId.toString(),
1403
+ });
1404
+ return {
1405
+ result: TopicValidatorResult.Reject,
1406
+ obj: checkpoint,
1407
+ metadata: { isEquivocated, processBlock },
1408
+ severity: PeerErrorSeverity.HighToleranceError,
1409
+ };
1410
+ }
1411
+
1412
+ // If this was a duplicate proposal, do not process it, but do invoke the duplicate callback,
1413
+ // and do re-broadcast it so other nodes in the network know to slash the proposer
1414
+ if (isEquivocated) {
1415
+ const proposer = checkpoint.getSender();
1416
+ this.logger.warn(`Detected duplicate checkpoint proposal (equivocation) at slot ${checkpoint.slotNumber}`, {
1417
+ ...checkpoint.toCheckpointInfo(),
1418
+ source: peerId.toString(),
1419
+ proposer: proposer?.toString(),
1420
+ });
1421
+ // Invoke the duplicate callback on the first duplicate spotted only
1422
+ if (proposer && count === 2) {
1423
+ this.duplicateProposalCallback?.({ slot: checkpoint.slotNumber, proposer, type: 'checkpoint' });
1424
+ }
1425
+ return {
1426
+ result: TopicValidatorResult.Accept,
1427
+ obj: checkpoint,
1428
+ metadata: { isEquivocated, processBlock },
1429
+ };
1430
+ }
1431
+
1432
+ // Otherwise, we're good to go!
1433
+ return { result: TopicValidatorResult.Accept, obj: checkpoint, metadata: { processBlock, isEquivocated } };
1139
1434
  }
1140
1435
 
1141
1436
  /**
1142
1437
  * Process a validated checkpoint proposal.
1143
- * Extracts and processes the last block proposal (if present) first, then processes the checkpoint.
1144
- * The block callback is invoked before the checkpoint callback.
1438
+ * Note: The proposal was already added to the pool by tryAddCheckpointProposal in handleGossipedCheckpointProposal.
1145
1439
  */
1146
1440
  @trackSpan('Libp2pService.processValidCheckpointProposal', async checkpoint => ({
1147
1441
  [Attributes.SLOT_NUMBER]: checkpoint.slotNumber,
1148
1442
  [Attributes.BLOCK_ARCHIVE]: checkpoint.archive.toString(),
1149
1443
  [Attributes.P2P_ID]: await checkpoint.p2pMessageLoggingIdentifier().then(i => i.toString()),
1150
1444
  }))
1151
- private async processValidCheckpointProposal(checkpoint: CheckpointProposal, sender: PeerId) {
1445
+ protected async processValidCheckpointProposal(checkpoint: CheckpointProposalCore, sender: PeerId) {
1152
1446
  const slot = checkpoint.slotNumber;
1153
1447
  this.logger.verbose(`Received checkpoint proposal for slot ${slot} from external peer ${sender.toString()}.`, {
1154
1448
  p2pMessageIdentifier: await checkpoint.p2pMessageLoggingIdentifier(),
@@ -1157,37 +1451,14 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1157
1451
  source: sender.toString(),
1158
1452
  });
1159
1453
 
1160
- // Extract block proposal before adding to pool (pool stores them separately)
1161
- const blockProposal = checkpoint.getBlockProposal();
1162
-
1163
- // Add proposal to the pool (this extracts and stores block proposal separately)
1164
- await this.mempools.attestationPool.addCheckpointProposal(checkpoint);
1165
-
1166
- // Mark txs as non-evictable if present (from the last block)
1167
- if (checkpoint.txHashes.length > 0) {
1168
- await this.mempools.txPool.markTxsAsNonEvictable(checkpoint.txHashes);
1169
- }
1170
-
1171
- // If there was a last block proposal, invoke the block callback first for validation.
1172
- // Note: The block proposal is already stored in the pool by addCheckpointProposal.
1173
- if (blockProposal) {
1174
- const isValid = await this.blockReceivedCallback(blockProposal, sender);
1175
- if (!isValid) {
1176
- this.logger.warn(`Block proposal from checkpoint failed validation`, {
1177
- slot: slot.toString(),
1178
- archive: checkpoint.archive.toString(),
1179
- blockNumber: blockProposal.blockNumber.toString(),
1180
- });
1181
- return;
1182
- }
1183
- }
1454
+ await this.allNodesCheckpointReceivedCallback(checkpoint, sender);
1184
1455
 
1185
1456
  // Call the checkpoint received callback with the core version (without lastBlock)
1186
1457
  // to validate and potentially generate attestations
1187
- const attestations = await this.checkpointReceivedCallback(checkpoint.toCore(), sender);
1458
+ const attestations = await this.validatorCheckpointReceivedCallback(checkpoint, sender);
1188
1459
  if (attestations && attestations.length > 0) {
1189
1460
  // If the callback returned attestations, add them to the pool and propagate them
1190
- await this.mempools.attestationPool.addCheckpointAttestations(attestations);
1461
+ await this.mempools.attestationPool.addOwnCheckpointAttestations(attestations);
1191
1462
  for (const attestation of attestations) {
1192
1463
  await this.propagate(attestation);
1193
1464
  }
@@ -1216,7 +1487,7 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1216
1487
  @trackSpan('Libp2pService.validateRequestedBlockTxs', request => ({
1217
1488
  [Attributes.BLOCK_ARCHIVE]: request.archiveRoot.toString(),
1218
1489
  }))
1219
- private async validateRequestedBlockTxs(
1490
+ protected async validateRequestedBlockTxs(
1220
1491
  request: BlockTxsRequest,
1221
1492
  response: BlockTxsResponse,
1222
1493
  peerId: PeerId,
@@ -1346,7 +1617,7 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1346
1617
  @trackSpan('Libp2pService.validateRequestedBlock', (requestedBlockNumber, _responseBlock) => ({
1347
1618
  [Attributes.BLOCK_NUMBER]: requestedBlockNumber.toString(),
1348
1619
  }))
1349
- private async validateRequestedBlock(
1620
+ protected async validateRequestedBlock(
1350
1621
  requestedBlockNumber: Fr,
1351
1622
  responseBlock: L2Block,
1352
1623
  peerId: PeerId,
@@ -1379,7 +1650,12 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1379
1650
  }
1380
1651
  }
1381
1652
 
1382
- private async validateRequestedTx(tx: Tx, peerId: PeerId, txValidator: TxValidator, requested?: Set<`0x${string}`>) {
1653
+ protected async validateRequestedTx(
1654
+ tx: Tx,
1655
+ peerId: PeerId,
1656
+ txValidator: TxValidator,
1657
+ requested?: Set<`0x${string}`>,
1658
+ ) {
1383
1659
  const penalize = (severity: PeerErrorSeverity) => this.peerManager.penalizePeer(peerId, severity);
1384
1660
  if (requested && !requested.has(tx.getTxHash().toString())) {
1385
1661
  penalize(PeerErrorSeverity.MidToleranceError);
@@ -1393,44 +1669,13 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1393
1669
  }
1394
1670
  }
1395
1671
 
1396
- private createRequestedTxValidator(): TxValidator {
1397
- return createTxReqRespValidator(this.proofVerifier, {
1672
+ protected createRequestedTxValidator(): TxValidator {
1673
+ return createTxValidatorForReqResponseReceivedTxs(this.proofVerifier, {
1398
1674
  l1ChainId: this.config.l1ChainId,
1399
1675
  rollupVersion: this.config.rollupVersion,
1400
1676
  });
1401
1677
  }
1402
1678
 
1403
- @trackSpan('Libp2pService.validatePropagatedTx', tx => ({
1404
- [Attributes.TX_HASH]: tx.getTxHash().toString(),
1405
- }))
1406
- private async validatePropagatedTx(tx: Tx, peerId: PeerId): Promise<boolean> {
1407
- const currentBlockNumber = await this.archiver.getBlockNumber();
1408
-
1409
- // We accept transactions if they are not expired by the next slot (checked based on the IncludeByTimestamp field)
1410
- const { ts: nextSlotTimestamp } = this.epochCache.getEpochAndSlotInNextL1Slot();
1411
- const messageValidators = await this.createMessageValidators(currentBlockNumber, nextSlotTimestamp);
1412
-
1413
- for (const validator of messageValidators) {
1414
- const outcome = await this.runValidations(tx, validator);
1415
-
1416
- if (outcome.allPassed) {
1417
- continue;
1418
- }
1419
- const { name } = outcome.failure;
1420
- let { severity } = outcome.failure;
1421
-
1422
- // Double spend validator has a special case handler
1423
- if (name === 'doubleSpendValidator') {
1424
- const txBlockNumber = BlockNumber(currentBlockNumber + 1); // tx is expected to be in the next block
1425
- severity = await this.handleDoubleSpendFailure(tx, txBlockNumber);
1426
- }
1427
-
1428
- this.peerManager.penalizePeer(peerId, severity);
1429
- return false;
1430
- }
1431
- return true;
1432
- }
1433
-
1434
1679
  private async getGasFees(blockNumber: BlockNumber): Promise<GasFees> {
1435
1680
  if (blockNumber === this.feesCache?.blockNumber) {
1436
1681
  return this.feesCache.gasFees;
@@ -1458,60 +1703,62 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1458
1703
  };
1459
1704
  }
1460
1705
 
1461
- public async validate(txs: Tx[]): Promise<void> {
1462
- const currentBlockNumber = await this.archiver.getBlockNumber();
1463
-
1464
- // We accept transactions if they are not expired by the next slot (checked based on the IncludeByTimestamp field)
1465
- const { ts: nextSlotTimestamp } = this.epochCache.getEpochAndSlotInNextL1Slot();
1466
- const messageValidators = await this.createMessageValidators(currentBlockNumber, nextSlotTimestamp);
1706
+ public async validateTxsReceivedInBlockProposal(txs: Tx[]): Promise<void> {
1707
+ const validator = createTxValidatorForBlockProposalReceivedTxs(
1708
+ this.proofVerifier,
1709
+ { l1ChainId: this.config.l1ChainId, rollupVersion: this.config.rollupVersion },
1710
+ this.logger.getBindings(),
1711
+ );
1467
1712
 
1468
- await Promise.all(
1713
+ const results = await Promise.all(
1469
1714
  txs.map(async tx => {
1470
- for (const validator of messageValidators) {
1471
- const outcome = await this.runValidations(tx, validator);
1472
- if (!outcome.allPassed) {
1473
- throw new Error('Invalid tx detected', { cause: { outcome } });
1474
- }
1475
- }
1715
+ const result = await validator.validateTx(tx);
1716
+ return result.result !== 'invalid';
1476
1717
  }),
1477
1718
  );
1719
+ if (results.some(value => value === false)) {
1720
+ throw new Error('Invalid tx detected');
1721
+ }
1478
1722
  }
1479
1723
 
1480
- /**
1481
- * Create message validators for the given block number and timestamp.
1482
- *
1483
- * Each validator is a pair of a validator and a severity.
1484
- * If a validator fails, the peer is penalized with the severity of the validator.
1485
- *
1486
- * @param currentBlockNumber - The current synced block number.
1487
- * @param nextSlotTimestamp - The timestamp of the next slot (used to validate txs are not expired).
1488
- * @returns The message validators.
1489
- */
1490
- private async createMessageValidators(
1724
+ /** Creates the first stage (fast) validators for gossiped transactions. */
1725
+ protected async createFirstStageMessageValidators(
1491
1726
  currentBlockNumber: BlockNumber,
1492
1727
  nextSlotTimestamp: UInt64,
1493
- ): Promise<Record<string, MessageValidator>[]> {
1728
+ ): Promise<Record<string, TransactionValidator>> {
1494
1729
  const gasFees = await this.getGasFees(currentBlockNumber);
1495
- const allowedInSetup = this.config.txPublicSetupAllowList ?? (await getDefaultAllowedSetupFunctions());
1496
-
1497
- const blockNumberInWhichTheTxIsConsideredToBeIncluded = BlockNumber(currentBlockNumber + 1);
1498
-
1499
- return createTxMessageValidators(
1730
+ const allowedInSetup = [
1731
+ ...(await getDefaultAllowedSetupFunctions()),
1732
+ ...(this.config.txPublicSetupAllowListExtend ?? []),
1733
+ ];
1734
+ const blockNumber = BlockNumber(currentBlockNumber + 1);
1735
+ const l1Constants = await this.archiver.getL1Constants();
1736
+
1737
+ return createFirstStageTxValidationsForGossipedTransactions(
1500
1738
  nextSlotTimestamp,
1501
- blockNumberInWhichTheTxIsConsideredToBeIncluded,
1739
+ blockNumber,
1502
1740
  this.worldStateSynchronizer,
1503
1741
  gasFees,
1504
1742
  this.config.l1ChainId,
1505
1743
  this.config.rollupVersion,
1506
1744
  protocolContractsHash,
1507
1745
  this.archiver,
1508
- this.proofVerifier,
1509
1746
  !this.config.disableTransactions,
1510
1747
  allowedInSetup,
1511
1748
  this.logger.getBindings(),
1749
+ {
1750
+ rollupManaLimit: l1Constants.rollupManaLimit,
1751
+ maxBlockL2Gas: this.config.validateMaxL2BlockGas,
1752
+ maxBlockDAGas: this.config.validateMaxDABlockGas,
1753
+ },
1512
1754
  );
1513
1755
  }
1514
1756
 
1757
+ /** Creates the second stage (expensive proof verification) validators for gossiped transactions. */
1758
+ protected createSecondStageMessageValidators(): Record<string, TransactionValidator> {
1759
+ return createSecondStageTxValidationsForGossipedTransactions(this.proofVerifier, this.logger.getBindings());
1760
+ }
1761
+
1515
1762
  /**
1516
1763
  * Run validations on a tx.
1517
1764
  * @param tx - The tx to validate.
@@ -1520,7 +1767,7 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1520
1767
  */
1521
1768
  private async runValidations(
1522
1769
  tx: Tx,
1523
- messageValidators: Record<string, MessageValidator>,
1770
+ messageValidators: Record<string, TransactionValidator>,
1524
1771
  ): Promise<ValidationOutcome> {
1525
1772
  const validationPromises = Object.entries(messageValidators).map(async ([name, { validator, severity }]) => {
1526
1773
  const { result } = await validator.validateTx(tx);
@@ -1529,8 +1776,10 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1529
1776
 
1530
1777
  // A promise that resolves when all validations have been run
1531
1778
  const allValidations = await Promise.all(validationPromises);
1532
- const failed = allValidations.find(x => !x.isValid);
1533
- if (failed) {
1779
+ const failures = allValidations.filter(x => !x.isValid);
1780
+ if (failures.length > 0) {
1781
+ // Pick the most severe failure (lowest tolerance = harshest penalty)
1782
+ const failed = maxBy(failures, f => PeerErrorSeverityByHarshness.indexOf(f.severity))!;
1534
1783
  return {
1535
1784
  allPassed: false,
1536
1785
  failure: {
@@ -1583,74 +1832,6 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1583
1832
  return PeerErrorSeverity.HighToleranceError;
1584
1833
  }
1585
1834
 
1586
- /**
1587
- * Validate a checkpoint attestation.
1588
- *
1589
- * @param attestation - The checkpoint attestation to validate.
1590
- * @returns True if the checkpoint attestation is valid, false otherwise.
1591
- */
1592
- @trackSpan('Libp2pService.validateCheckpointAttestation', async (_, attestation) => ({
1593
- [Attributes.SLOT_NUMBER]: attestation.payload.header.slotNumber,
1594
- [Attributes.BLOCK_ARCHIVE]: attestation.archive.toString(),
1595
- [Attributes.P2P_ID]: await attestation.p2pMessageLoggingIdentifier().then(i => i.toString()),
1596
- }))
1597
- public async validateCheckpointAttestation(
1598
- peerId: PeerId,
1599
- attestation: CheckpointAttestation,
1600
- ): Promise<P2PValidationResult> {
1601
- const result = await this.checkpointAttestationValidator.validate(attestation);
1602
-
1603
- if (result.result === 'reject') {
1604
- this.logger.debug(`Penalizing peer ${peerId} for checkpoint attestation validation failure`);
1605
- this.peerManager.penalizePeer(peerId, result.severity);
1606
- }
1607
-
1608
- return result;
1609
- }
1610
-
1611
- /**
1612
- * Validate a block proposal.
1613
- *
1614
- * @param block - The block proposal to validate.
1615
- * @returns True if the block proposal is valid, false otherwise.
1616
- */
1617
- @trackSpan('Libp2pService.validateBlockProposal', (_peerId, block) => ({
1618
- [Attributes.SLOT_NUMBER]: block.slotNumber.toString(),
1619
- }))
1620
- public async validateBlockProposal(peerId: PeerId, block: BlockProposal): Promise<P2PValidationResult> {
1621
- const result = await this.blockProposalValidator.validate(block);
1622
-
1623
- if (result.result === 'reject') {
1624
- this.logger.debug(`Penalizing peer ${peerId} for block proposal validation failure`);
1625
- this.peerManager.penalizePeer(peerId, result.severity);
1626
- }
1627
-
1628
- return result;
1629
- }
1630
-
1631
- /**
1632
- * Validate a checkpoint proposal.
1633
- *
1634
- * @param checkpoint - The checkpoint proposal to validate.
1635
- * @returns True if the checkpoint proposal is valid, false otherwise.
1636
- */
1637
- @trackSpan('Libp2pService.validateCheckpointProposal', (_peerId, checkpoint) => ({
1638
- [Attributes.SLOT_NUMBER]: checkpoint.slotNumber.toString(),
1639
- }))
1640
- public async validateCheckpointProposal(
1641
- peerId: PeerId,
1642
- checkpoint: CheckpointProposal,
1643
- ): Promise<P2PValidationResult> {
1644
- const result = await this.checkpointProposalValidator.validate(checkpoint);
1645
-
1646
- if (result.result === 'reject') {
1647
- this.logger.debug(`Penalizing peer ${peerId} for checkpoint proposal validation failure`);
1648
- this.peerManager.penalizePeer(peerId, result.severity);
1649
- }
1650
-
1651
- return result;
1652
- }
1653
-
1654
1835
  public getPeerScore(peerId: PeerId): number {
1655
1836
  return this.node.services.pubsub.score.score(peerId.toString());
1656
1837
  }