@aztec/p2p 0.0.1-commit.0b941701 → 0.0.1-commit.134ed76

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 (408) hide show
  1. package/dest/bootstrap/bootstrap.d.ts +4 -3
  2. package/dest/bootstrap/bootstrap.d.ts.map +1 -1
  3. package/dest/bootstrap/bootstrap.js +4 -4
  4. package/dest/client/factory.d.ts +5 -5
  5. package/dest/client/factory.d.ts.map +1 -1
  6. package/dest/client/factory.js +47 -13
  7. package/dest/client/interface.d.ts +33 -15
  8. package/dest/client/interface.d.ts.map +1 -1
  9. package/dest/client/p2p_client.d.ts +35 -36
  10. package/dest/client/p2p_client.d.ts.map +1 -1
  11. package/dest/client/p2p_client.js +115 -139
  12. package/dest/client/test/tx_proposal_collector/proposal_tx_collector_worker.d.ts +2 -0
  13. package/dest/client/test/tx_proposal_collector/proposal_tx_collector_worker.d.ts.map +1 -0
  14. package/dest/client/test/tx_proposal_collector/proposal_tx_collector_worker.js +305 -0
  15. package/dest/client/test/tx_proposal_collector/proposal_tx_collector_worker_protocol.d.ts +73 -0
  16. package/dest/client/test/tx_proposal_collector/proposal_tx_collector_worker_protocol.d.ts.map +1 -0
  17. package/dest/client/test/tx_proposal_collector/proposal_tx_collector_worker_protocol.js +8 -0
  18. package/dest/config.d.ts +24 -3
  19. package/dest/config.d.ts.map +1 -1
  20. package/dest/config.js +16 -2
  21. package/dest/index.d.ts +2 -1
  22. package/dest/index.d.ts.map +1 -1
  23. package/dest/index.js +1 -0
  24. package/dest/mem_pools/attestation_pool/attestation_pool.d.ts +102 -88
  25. package/dest/mem_pools/attestation_pool/attestation_pool.d.ts.map +1 -1
  26. package/dest/mem_pools/attestation_pool/attestation_pool.js +436 -3
  27. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.d.ts +2 -2
  28. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.d.ts.map +1 -1
  29. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.js +353 -87
  30. package/dest/mem_pools/attestation_pool/index.d.ts +2 -3
  31. package/dest/mem_pools/attestation_pool/index.d.ts.map +1 -1
  32. package/dest/mem_pools/attestation_pool/index.js +1 -2
  33. package/dest/mem_pools/index.d.ts +3 -2
  34. package/dest/mem_pools/index.d.ts.map +1 -1
  35. package/dest/mem_pools/index.js +1 -1
  36. package/dest/mem_pools/instrumentation.d.ts +1 -1
  37. package/dest/mem_pools/instrumentation.d.ts.map +1 -1
  38. package/dest/mem_pools/instrumentation.js +2 -2
  39. package/dest/mem_pools/interface.d.ts +5 -5
  40. package/dest/mem_pools/interface.d.ts.map +1 -1
  41. package/dest/mem_pools/tx_pool_v2/archive/index.d.ts +2 -0
  42. package/dest/mem_pools/tx_pool_v2/archive/index.d.ts.map +1 -0
  43. package/dest/mem_pools/tx_pool_v2/archive/index.js +1 -0
  44. package/dest/mem_pools/tx_pool_v2/archive/tx_archive.d.ts +43 -0
  45. package/dest/mem_pools/tx_pool_v2/archive/tx_archive.d.ts.map +1 -0
  46. package/dest/mem_pools/tx_pool_v2/archive/tx_archive.js +103 -0
  47. package/dest/mem_pools/tx_pool_v2/deleted_pool.d.ts +87 -0
  48. package/dest/mem_pools/tx_pool_v2/deleted_pool.d.ts.map +1 -0
  49. package/dest/mem_pools/tx_pool_v2/deleted_pool.js +180 -0
  50. package/dest/mem_pools/tx_pool_v2/eviction/eviction_manager.d.ts +47 -0
  51. package/dest/mem_pools/tx_pool_v2/eviction/eviction_manager.d.ts.map +1 -0
  52. package/dest/mem_pools/tx_pool_v2/eviction/eviction_manager.js +119 -0
  53. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.d.ts +17 -0
  54. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.d.ts.map +1 -0
  55. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.js +90 -0
  56. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.d.ts +19 -0
  57. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.d.ts.map +1 -0
  58. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.js +89 -0
  59. package/dest/mem_pools/tx_pool_v2/eviction/index.d.ts +10 -0
  60. package/dest/mem_pools/tx_pool_v2/eviction/index.d.ts.map +1 -0
  61. package/dest/mem_pools/tx_pool_v2/eviction/index.js +11 -0
  62. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.d.ts +131 -0
  63. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.d.ts.map +1 -0
  64. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.js +17 -0
  65. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.d.ts +15 -0
  66. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.d.ts.map +1 -0
  67. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.js +63 -0
  68. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.d.ts +17 -0
  69. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.d.ts.map +1 -0
  70. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.js +91 -0
  71. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.d.ts +16 -0
  72. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.d.ts.map +1 -0
  73. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.js +70 -0
  74. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.d.ts +20 -0
  75. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.d.ts.map +1 -0
  76. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.js +63 -0
  77. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.d.ts +15 -0
  78. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.d.ts.map +1 -0
  79. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.js +19 -0
  80. package/dest/mem_pools/tx_pool_v2/index.d.ts +6 -0
  81. package/dest/mem_pools/tx_pool_v2/index.d.ts.map +1 -0
  82. package/dest/mem_pools/tx_pool_v2/index.js +5 -0
  83. package/dest/mem_pools/tx_pool_v2/interfaces.d.ts +197 -0
  84. package/dest/mem_pools/tx_pool_v2/interfaces.d.ts.map +1 -0
  85. package/dest/mem_pools/tx_pool_v2/interfaces.js +6 -0
  86. package/dest/mem_pools/tx_pool_v2/tx_metadata.d.ts +93 -0
  87. package/dest/mem_pools/tx_pool_v2/tx_metadata.d.ts.map +1 -0
  88. package/dest/mem_pools/tx_pool_v2/tx_metadata.js +127 -0
  89. package/dest/mem_pools/tx_pool_v2/tx_pool_bench_metrics.d.ts +26 -0
  90. package/dest/mem_pools/tx_pool_v2/tx_pool_bench_metrics.d.ts.map +1 -0
  91. package/dest/mem_pools/tx_pool_v2/tx_pool_bench_metrics.js +70 -0
  92. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.d.ts +99 -0
  93. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.d.ts.map +1 -0
  94. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.js +332 -0
  95. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.d.ts +55 -0
  96. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.d.ts.map +1 -0
  97. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.js +156 -0
  98. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.d.ts +69 -0
  99. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.d.ts.map +1 -0
  100. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.js +751 -0
  101. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.d.ts +3 -3
  102. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.d.ts.map +1 -1
  103. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.js +7 -2
  104. package/dest/msg_validators/proposal_validator/proposal_validator.js +5 -5
  105. package/dest/msg_validators/tx_validator/aggregate_tx_validator.d.ts +3 -3
  106. package/dest/msg_validators/tx_validator/aggregate_tx_validator.d.ts.map +1 -1
  107. package/dest/msg_validators/tx_validator/archive_cache.d.ts +3 -3
  108. package/dest/msg_validators/tx_validator/archive_cache.d.ts.map +1 -1
  109. package/dest/msg_validators/tx_validator/archive_cache.js +1 -1
  110. package/dest/msg_validators/tx_validator/block_header_validator.d.ts +20 -6
  111. package/dest/msg_validators/tx_validator/block_header_validator.d.ts.map +1 -1
  112. package/dest/msg_validators/tx_validator/block_header_validator.js +5 -4
  113. package/dest/msg_validators/tx_validator/data_validator.d.ts +3 -1
  114. package/dest/msg_validators/tx_validator/data_validator.d.ts.map +1 -1
  115. package/dest/msg_validators/tx_validator/data_validator.js +4 -1
  116. package/dest/msg_validators/tx_validator/double_spend_validator.d.ts +15 -4
  117. package/dest/msg_validators/tx_validator/double_spend_validator.d.ts.map +1 -1
  118. package/dest/msg_validators/tx_validator/double_spend_validator.js +7 -6
  119. package/dest/msg_validators/tx_validator/factory.d.ts +8 -3
  120. package/dest/msg_validators/tx_validator/factory.d.ts.map +1 -1
  121. package/dest/msg_validators/tx_validator/factory.js +21 -11
  122. package/dest/msg_validators/tx_validator/gas_validator.d.ts +3 -2
  123. package/dest/msg_validators/tx_validator/gas_validator.d.ts.map +1 -1
  124. package/dest/msg_validators/tx_validator/gas_validator.js +3 -2
  125. package/dest/msg_validators/tx_validator/metadata_validator.d.ts +3 -2
  126. package/dest/msg_validators/tx_validator/metadata_validator.d.ts.map +1 -1
  127. package/dest/msg_validators/tx_validator/metadata_validator.js +2 -2
  128. package/dest/msg_validators/tx_validator/phases_validator.d.ts +3 -2
  129. package/dest/msg_validators/tx_validator/phases_validator.d.ts.map +1 -1
  130. package/dest/msg_validators/tx_validator/phases_validator.js +3 -3
  131. package/dest/msg_validators/tx_validator/size_validator.d.ts +3 -1
  132. package/dest/msg_validators/tx_validator/size_validator.d.ts.map +1 -1
  133. package/dest/msg_validators/tx_validator/size_validator.js +4 -1
  134. package/dest/msg_validators/tx_validator/timestamp_validator.d.ts +22 -5
  135. package/dest/msg_validators/tx_validator/timestamp_validator.d.ts.map +1 -1
  136. package/dest/msg_validators/tx_validator/timestamp_validator.js +4 -4
  137. package/dest/msg_validators/tx_validator/tx_permitted_validator.d.ts +3 -2
  138. package/dest/msg_validators/tx_validator/tx_permitted_validator.d.ts.map +1 -1
  139. package/dest/msg_validators/tx_validator/tx_permitted_validator.js +2 -2
  140. package/dest/msg_validators/tx_validator/tx_proof_validator.d.ts +3 -2
  141. package/dest/msg_validators/tx_validator/tx_proof_validator.d.ts.map +1 -1
  142. package/dest/msg_validators/tx_validator/tx_proof_validator.js +2 -2
  143. package/dest/services/data_store.d.ts +1 -1
  144. package/dest/services/data_store.d.ts.map +1 -1
  145. package/dest/services/data_store.js +10 -6
  146. package/dest/services/discv5/discV5_service.js +1 -1
  147. package/dest/services/dummy_service.d.ts +22 -2
  148. package/dest/services/dummy_service.d.ts.map +1 -1
  149. package/dest/services/dummy_service.js +45 -0
  150. package/dest/services/encoding.d.ts +2 -2
  151. package/dest/services/encoding.d.ts.map +1 -1
  152. package/dest/services/encoding.js +2 -2
  153. package/dest/services/gossipsub/index.d.ts +3 -0
  154. package/dest/services/gossipsub/index.d.ts.map +1 -0
  155. package/dest/services/gossipsub/index.js +2 -0
  156. package/dest/services/gossipsub/scoring.d.ts +21 -3
  157. package/dest/services/gossipsub/scoring.d.ts.map +1 -1
  158. package/dest/services/gossipsub/scoring.js +24 -7
  159. package/dest/services/gossipsub/topic_score_params.d.ts +161 -0
  160. package/dest/services/gossipsub/topic_score_params.d.ts.map +1 -0
  161. package/dest/services/gossipsub/topic_score_params.js +324 -0
  162. package/dest/services/index.d.ts +2 -1
  163. package/dest/services/index.d.ts.map +1 -1
  164. package/dest/services/index.js +1 -0
  165. package/dest/services/libp2p/instrumentation.d.ts +1 -1
  166. package/dest/services/libp2p/instrumentation.d.ts.map +1 -1
  167. package/dest/services/libp2p/instrumentation.js +14 -3
  168. package/dest/services/libp2p/libp2p_service.d.ts +90 -35
  169. package/dest/services/libp2p/libp2p_service.d.ts.map +1 -1
  170. package/dest/services/libp2p/libp2p_service.js +403 -299
  171. package/dest/services/peer-manager/metrics.d.ts +2 -2
  172. package/dest/services/peer-manager/metrics.d.ts.map +1 -1
  173. package/dest/services/peer-manager/metrics.js +20 -5
  174. package/dest/services/peer-manager/peer_scoring.d.ts +1 -1
  175. package/dest/services/peer-manager/peer_scoring.d.ts.map +1 -1
  176. package/dest/services/peer-manager/peer_scoring.js +33 -4
  177. package/dest/services/reqresp/batch-tx-requester/batch_tx_requester.d.ts +47 -0
  178. package/dest/services/reqresp/batch-tx-requester/batch_tx_requester.d.ts.map +1 -0
  179. package/dest/services/reqresp/batch-tx-requester/batch_tx_requester.js +566 -0
  180. package/dest/services/reqresp/batch-tx-requester/config.d.ts +17 -0
  181. package/dest/services/reqresp/batch-tx-requester/config.d.ts.map +1 -0
  182. package/dest/services/reqresp/batch-tx-requester/config.js +27 -0
  183. package/dest/services/reqresp/batch-tx-requester/interface.d.ts +50 -0
  184. package/dest/services/reqresp/batch-tx-requester/interface.d.ts.map +1 -0
  185. package/dest/services/reqresp/batch-tx-requester/interface.js +1 -0
  186. package/dest/services/reqresp/batch-tx-requester/missing_txs.d.ts +37 -0
  187. package/dest/services/reqresp/batch-tx-requester/missing_txs.d.ts.map +1 -0
  188. package/dest/services/reqresp/batch-tx-requester/missing_txs.js +151 -0
  189. package/dest/services/reqresp/batch-tx-requester/peer_collection.d.ts +54 -0
  190. package/dest/services/reqresp/batch-tx-requester/peer_collection.d.ts.map +1 -0
  191. package/dest/services/reqresp/batch-tx-requester/peer_collection.js +139 -0
  192. package/dest/services/reqresp/batch-tx-requester/tx_validator.d.ts +20 -0
  193. package/dest/services/reqresp/batch-tx-requester/tx_validator.d.ts.map +1 -0
  194. package/dest/services/reqresp/batch-tx-requester/tx_validator.js +21 -0
  195. package/dest/services/reqresp/connection-sampler/batch_connection_sampler.d.ts +22 -3
  196. package/dest/services/reqresp/connection-sampler/batch_connection_sampler.d.ts.map +1 -1
  197. package/dest/services/reqresp/connection-sampler/batch_connection_sampler.js +63 -4
  198. package/dest/services/reqresp/connection-sampler/connection_sampler.d.ts +2 -1
  199. package/dest/services/reqresp/connection-sampler/connection_sampler.d.ts.map +1 -1
  200. package/dest/services/reqresp/connection-sampler/connection_sampler.js +12 -0
  201. package/dest/services/reqresp/interface.d.ts +12 -1
  202. package/dest/services/reqresp/interface.d.ts.map +1 -1
  203. package/dest/services/reqresp/interface.js +15 -1
  204. package/dest/services/reqresp/metrics.d.ts +6 -5
  205. package/dest/services/reqresp/metrics.d.ts.map +1 -1
  206. package/dest/services/reqresp/metrics.js +17 -5
  207. package/dest/services/reqresp/protocols/block_txs/bitvector.d.ts +5 -1
  208. package/dest/services/reqresp/protocols/block_txs/bitvector.d.ts.map +1 -1
  209. package/dest/services/reqresp/protocols/block_txs/bitvector.js +5 -0
  210. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.d.ts +7 -5
  211. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.d.ts.map +1 -1
  212. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.js +27 -9
  213. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.d.ts +29 -6
  214. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.d.ts.map +1 -1
  215. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.js +59 -13
  216. package/dest/services/reqresp/protocols/tx.d.ts +7 -1
  217. package/dest/services/reqresp/protocols/tx.d.ts.map +1 -1
  218. package/dest/services/reqresp/protocols/tx.js +20 -0
  219. package/dest/services/reqresp/reqresp.d.ts +6 -1
  220. package/dest/services/reqresp/reqresp.d.ts.map +1 -1
  221. package/dest/services/reqresp/reqresp.js +69 -26
  222. package/dest/services/service.d.ts +38 -1
  223. package/dest/services/service.d.ts.map +1 -1
  224. package/dest/services/tx_collection/config.d.ts +10 -1
  225. package/dest/services/tx_collection/config.d.ts.map +1 -1
  226. package/dest/services/tx_collection/config.js +25 -1
  227. package/dest/services/tx_collection/fast_tx_collection.d.ts +7 -4
  228. package/dest/services/tx_collection/fast_tx_collection.d.ts.map +1 -1
  229. package/dest/services/tx_collection/fast_tx_collection.js +34 -13
  230. package/dest/services/tx_collection/file_store_tx_collection.d.ts +44 -0
  231. package/dest/services/tx_collection/file_store_tx_collection.d.ts.map +1 -0
  232. package/dest/services/tx_collection/file_store_tx_collection.js +118 -0
  233. package/dest/services/tx_collection/file_store_tx_source.d.ts +27 -0
  234. package/dest/services/tx_collection/file_store_tx_source.d.ts.map +1 -0
  235. package/dest/services/tx_collection/file_store_tx_source.js +57 -0
  236. package/dest/services/tx_collection/index.d.ts +3 -1
  237. package/dest/services/tx_collection/index.d.ts.map +1 -1
  238. package/dest/services/tx_collection/index.js +2 -0
  239. package/dest/services/tx_collection/instrumentation.d.ts +1 -1
  240. package/dest/services/tx_collection/instrumentation.d.ts.map +1 -1
  241. package/dest/services/tx_collection/instrumentation.js +9 -2
  242. package/dest/services/tx_collection/proposal_tx_collector.d.ts +48 -0
  243. package/dest/services/tx_collection/proposal_tx_collector.d.ts.map +1 -0
  244. package/dest/services/tx_collection/proposal_tx_collector.js +49 -0
  245. package/dest/services/tx_collection/slow_tx_collection.d.ts +3 -1
  246. package/dest/services/tx_collection/slow_tx_collection.d.ts.map +1 -1
  247. package/dest/services/tx_collection/slow_tx_collection.js +48 -19
  248. package/dest/services/tx_collection/tx_collection.d.ts +19 -9
  249. package/dest/services/tx_collection/tx_collection.d.ts.map +1 -1
  250. package/dest/services/tx_collection/tx_collection.js +62 -6
  251. package/dest/services/tx_collection/tx_collection_sink.d.ts +15 -6
  252. package/dest/services/tx_collection/tx_collection_sink.d.ts.map +1 -1
  253. package/dest/services/tx_collection/tx_collection_sink.js +13 -7
  254. package/dest/services/tx_file_store/config.d.ts +16 -0
  255. package/dest/services/tx_file_store/config.d.ts.map +1 -0
  256. package/dest/services/tx_file_store/config.js +22 -0
  257. package/dest/services/tx_file_store/index.d.ts +4 -0
  258. package/dest/services/tx_file_store/index.d.ts.map +1 -0
  259. package/dest/services/tx_file_store/index.js +3 -0
  260. package/dest/services/tx_file_store/instrumentation.d.ts +15 -0
  261. package/dest/services/tx_file_store/instrumentation.d.ts.map +1 -0
  262. package/dest/services/tx_file_store/instrumentation.js +29 -0
  263. package/dest/services/tx_file_store/tx_file_store.d.ts +47 -0
  264. package/dest/services/tx_file_store/tx_file_store.d.ts.map +1 -0
  265. package/dest/services/tx_file_store/tx_file_store.js +149 -0
  266. package/dest/services/tx_provider.d.ts +3 -3
  267. package/dest/services/tx_provider.d.ts.map +1 -1
  268. package/dest/services/tx_provider.js +5 -4
  269. package/dest/services/tx_provider_instrumentation.d.ts +1 -1
  270. package/dest/services/tx_provider_instrumentation.d.ts.map +1 -1
  271. package/dest/services/tx_provider_instrumentation.js +5 -5
  272. package/dest/test-helpers/index.d.ts +3 -1
  273. package/dest/test-helpers/index.d.ts.map +1 -1
  274. package/dest/test-helpers/index.js +2 -0
  275. package/dest/test-helpers/make-test-p2p-clients.d.ts +3 -3
  276. package/dest/test-helpers/make-test-p2p-clients.d.ts.map +1 -1
  277. package/dest/test-helpers/mock-pubsub.d.ts +27 -1
  278. package/dest/test-helpers/mock-pubsub.d.ts.map +1 -1
  279. package/dest/test-helpers/mock-pubsub.js +97 -2
  280. package/dest/test-helpers/reqresp-nodes.d.ts +1 -1
  281. package/dest/test-helpers/reqresp-nodes.d.ts.map +1 -1
  282. package/dest/test-helpers/reqresp-nodes.js +2 -1
  283. package/dest/test-helpers/test_tx_provider.d.ts +40 -0
  284. package/dest/test-helpers/test_tx_provider.d.ts.map +1 -0
  285. package/dest/test-helpers/test_tx_provider.js +41 -0
  286. package/dest/test-helpers/testbench-utils.d.ts +158 -0
  287. package/dest/test-helpers/testbench-utils.d.ts.map +1 -0
  288. package/dest/test-helpers/testbench-utils.js +360 -0
  289. package/dest/testbench/p2p_client_testbench_worker.d.ts +28 -2
  290. package/dest/testbench/p2p_client_testbench_worker.d.ts.map +1 -1
  291. package/dest/testbench/p2p_client_testbench_worker.js +213 -132
  292. package/dest/testbench/worker_client_manager.d.ts +51 -6
  293. package/dest/testbench/worker_client_manager.d.ts.map +1 -1
  294. package/dest/testbench/worker_client_manager.js +226 -44
  295. package/package.json +14 -14
  296. package/src/bootstrap/bootstrap.ts +7 -4
  297. package/src/client/factory.ts +78 -22
  298. package/src/client/interface.ts +39 -14
  299. package/src/client/p2p_client.ts +151 -162
  300. package/src/client/test/tx_proposal_collector/README.md +227 -0
  301. package/src/client/test/tx_proposal_collector/proposal_tx_collector_worker.ts +336 -0
  302. package/src/client/test/tx_proposal_collector/proposal_tx_collector_worker_protocol.ts +43 -0
  303. package/src/config.ts +38 -2
  304. package/src/index.ts +1 -0
  305. package/src/mem_pools/attestation_pool/attestation_pool.ts +488 -91
  306. package/src/mem_pools/attestation_pool/attestation_pool_test_suite.ts +442 -102
  307. package/src/mem_pools/attestation_pool/index.ts +9 -2
  308. package/src/mem_pools/index.ts +4 -1
  309. package/src/mem_pools/instrumentation.ts +2 -1
  310. package/src/mem_pools/interface.ts +4 -4
  311. package/src/mem_pools/tx_pool_v2/README.md +259 -0
  312. package/src/mem_pools/tx_pool_v2/archive/index.ts +1 -0
  313. package/src/mem_pools/tx_pool_v2/archive/tx_archive.ts +120 -0
  314. package/src/mem_pools/tx_pool_v2/deleted_pool.ts +234 -0
  315. package/src/mem_pools/tx_pool_v2/eviction/eviction_manager.ts +147 -0
  316. package/src/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.ts +118 -0
  317. package/src/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.ts +111 -0
  318. package/src/mem_pools/tx_pool_v2/eviction/index.ts +23 -0
  319. package/src/mem_pools/tx_pool_v2/eviction/interfaces.ts +164 -0
  320. package/src/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.ts +74 -0
  321. package/src/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.ts +101 -0
  322. package/src/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.ts +86 -0
  323. package/src/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.ts +72 -0
  324. package/src/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.ts +31 -0
  325. package/src/mem_pools/tx_pool_v2/index.ts +12 -0
  326. package/src/mem_pools/tx_pool_v2/interfaces.ts +227 -0
  327. package/src/mem_pools/tx_pool_v2/tx_metadata.ts +207 -0
  328. package/src/mem_pools/tx_pool_v2/tx_pool_bench_metrics.ts +77 -0
  329. package/src/mem_pools/tx_pool_v2/tx_pool_indices.ts +417 -0
  330. package/src/mem_pools/tx_pool_v2/tx_pool_v2.ts +212 -0
  331. package/src/mem_pools/tx_pool_v2/tx_pool_v2_impl.ts +895 -0
  332. package/src/msg_validators/attestation_validator/fisherman_attestation_validator.ts +10 -4
  333. package/src/msg_validators/proposal_validator/proposal_validator.ts +5 -5
  334. package/src/msg_validators/tx_validator/aggregate_tx_validator.ts +2 -2
  335. package/src/msg_validators/tx_validator/archive_cache.ts +3 -3
  336. package/src/msg_validators/tx_validator/block_header_validator.ts +22 -11
  337. package/src/msg_validators/tx_validator/data_validator.ts +6 -2
  338. package/src/msg_validators/tx_validator/double_spend_validator.ts +15 -9
  339. package/src/msg_validators/tx_validator/factory.ts +64 -23
  340. package/src/msg_validators/tx_validator/gas_validator.ts +9 -3
  341. package/src/msg_validators/tx_validator/metadata_validator.ts +6 -3
  342. package/src/msg_validators/tx_validator/phases_validator.ts +5 -3
  343. package/src/msg_validators/tx_validator/size_validator.ts +6 -2
  344. package/src/msg_validators/tx_validator/timestamp_validator.ts +25 -17
  345. package/src/msg_validators/tx_validator/tx_permitted_validator.ts +8 -3
  346. package/src/msg_validators/tx_validator/tx_proof_validator.ts +8 -3
  347. package/src/services/data_store.ts +10 -7
  348. package/src/services/discv5/discV5_service.ts +1 -1
  349. package/src/services/dummy_service.ts +57 -0
  350. package/src/services/encoding.ts +2 -2
  351. package/src/services/gossipsub/README.md +626 -0
  352. package/src/services/gossipsub/index.ts +2 -0
  353. package/src/services/gossipsub/scoring.ts +29 -5
  354. package/src/services/gossipsub/topic_score_params.ts +451 -0
  355. package/src/services/index.ts +1 -0
  356. package/src/services/libp2p/instrumentation.ts +15 -2
  357. package/src/services/libp2p/libp2p_service.ts +428 -319
  358. package/src/services/peer-manager/metrics.ts +21 -4
  359. package/src/services/peer-manager/peer_scoring.ts +29 -1
  360. package/src/services/reqresp/batch-tx-requester/README.md +305 -0
  361. package/src/services/reqresp/batch-tx-requester/batch_tx_requester.ts +706 -0
  362. package/src/services/reqresp/batch-tx-requester/config.ts +40 -0
  363. package/src/services/reqresp/batch-tx-requester/interface.ts +57 -0
  364. package/src/services/reqresp/batch-tx-requester/missing_txs.ts +209 -0
  365. package/src/services/reqresp/batch-tx-requester/peer_collection.ts +205 -0
  366. package/src/services/reqresp/batch-tx-requester/tx_validator.ts +37 -0
  367. package/src/services/reqresp/connection-sampler/batch_connection_sampler.ts +65 -4
  368. package/src/services/reqresp/connection-sampler/connection_sampler.ts +16 -0
  369. package/src/services/reqresp/interface.ts +29 -1
  370. package/src/services/reqresp/metrics.ts +34 -9
  371. package/src/services/reqresp/protocols/block_txs/bitvector.ts +7 -0
  372. package/src/services/reqresp/protocols/block_txs/block_txs_handler.ts +35 -12
  373. package/src/services/reqresp/protocols/block_txs/block_txs_reqresp.ts +74 -9
  374. package/src/services/reqresp/protocols/tx.ts +22 -0
  375. package/src/services/reqresp/reqresp.ts +79 -22
  376. package/src/services/service.ts +44 -0
  377. package/src/services/tx_collection/config.ts +41 -1
  378. package/src/services/tx_collection/fast_tx_collection.ts +44 -19
  379. package/src/services/tx_collection/file_store_tx_collection.ts +152 -0
  380. package/src/services/tx_collection/file_store_tx_source.ts +70 -0
  381. package/src/services/tx_collection/index.ts +6 -0
  382. package/src/services/tx_collection/instrumentation.ts +11 -2
  383. package/src/services/tx_collection/proposal_tx_collector.ts +112 -0
  384. package/src/services/tx_collection/slow_tx_collection.ts +55 -26
  385. package/src/services/tx_collection/tx_collection.ts +82 -16
  386. package/src/services/tx_collection/tx_collection_sink.ts +17 -7
  387. package/src/services/tx_file_store/config.ts +37 -0
  388. package/src/services/tx_file_store/index.ts +3 -0
  389. package/src/services/tx_file_store/instrumentation.ts +36 -0
  390. package/src/services/tx_file_store/tx_file_store.ts +173 -0
  391. package/src/services/tx_provider.ts +8 -7
  392. package/src/services/tx_provider_instrumentation.ts +11 -5
  393. package/src/test-helpers/index.ts +2 -0
  394. package/src/test-helpers/make-test-p2p-clients.ts +3 -3
  395. package/src/test-helpers/mock-pubsub.ts +133 -3
  396. package/src/test-helpers/reqresp-nodes.ts +2 -1
  397. package/src/test-helpers/test_tx_provider.ts +64 -0
  398. package/src/test-helpers/testbench-utils.ts +422 -0
  399. package/src/testbench/p2p_client_testbench_worker.ts +322 -123
  400. package/src/testbench/worker_client_manager.ts +304 -47
  401. package/dest/mem_pools/attestation_pool/kv_attestation_pool.d.ts +0 -40
  402. package/dest/mem_pools/attestation_pool/kv_attestation_pool.d.ts.map +0 -1
  403. package/dest/mem_pools/attestation_pool/kv_attestation_pool.js +0 -218
  404. package/dest/mem_pools/attestation_pool/memory_attestation_pool.d.ts +0 -31
  405. package/dest/mem_pools/attestation_pool/memory_attestation_pool.d.ts.map +0 -1
  406. package/dest/mem_pools/attestation_pool/memory_attestation_pool.js +0 -180
  407. package/src/mem_pools/attestation_pool/kv_attestation_pool.ts +0 -320
  408. package/src/mem_pools/attestation_pool/memory_attestation_pool.ts +0 -264
@@ -1,12 +1,10 @@
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';
4
3
  import { Fr } from '@aztec/foundation/curves/bn254';
5
4
  import { type Logger, createLibp2pComponentLogger, createLogger } from '@aztec/foundation/log';
6
5
  import { RunningPromise } from '@aztec/foundation/running-promise';
7
6
  import { Timer } from '@aztec/foundation/timer';
8
7
  import type { AztecAsyncKVStore } from '@aztec/kv-store';
9
- import { getVKTreeRoot } from '@aztec/noir-protocol-circuits-types/vk-tree';
10
8
  import { protocolContractsHash } from '@aztec/protocol-contracts';
11
9
  import type { EthAddress, L2Block, L2BlockSource } from '@aztec/stdlib/block';
12
10
  import type { ContractDataSource } from '@aztec/stdlib/contract';
@@ -46,7 +44,7 @@ import {
46
44
  type GossipsubMessage,
47
45
  gossipsub,
48
46
  } from '@chainsafe/libp2p-gossipsub';
49
- import { createPeerScoreParams, createTopicScoreParams } from '@chainsafe/libp2p-gossipsub/score';
47
+ import { createPeerScoreParams } from '@chainsafe/libp2p-gossipsub/score';
50
48
  import { SignaturePolicy } from '@chainsafe/libp2p-gossipsub/types';
51
49
  import { noise } from '@chainsafe/libp2p-noise';
52
50
  import { yamux } from '@chainsafe/libp2p-yamux';
@@ -60,62 +58,62 @@ import { ENR } from '@nethermindeth/enr';
60
58
  import { createLibp2p } from 'libp2p';
61
59
 
62
60
  import type { P2PConfig } from '../../config.js';
63
- import { ProposalSlotCapExceededError } from '../../errors/attestation-pool.error.js';
64
61
  import type { MemPools } from '../../mem_pools/interface.js';
65
62
  import {
66
63
  BlockProposalValidator,
67
64
  CheckpointAttestationValidator,
68
65
  CheckpointProposalValidator,
66
+ DoubleSpendTxValidator,
69
67
  FishermanAttestationValidator,
70
- SizeTxValidator,
68
+ getDefaultAllowedSetupFunctions,
71
69
  } from '../../msg_validators/index.js';
72
70
  import { MessageSeenValidator } from '../../msg_validators/msg_seen_validator/msg_seen_validator.js';
73
- import { getDefaultAllowedSetupFunctions } from '../../msg_validators/tx_validator/allowed_public_setup.js';
74
- import { type MessageValidator, createTxMessageValidators } from '../../msg_validators/tx_validator/factory.js';
75
71
  import {
76
- AggregateTxValidator,
77
- DataTxValidator,
78
- DoubleSpendTxValidator,
79
- MetadataTxValidator,
80
- TxProofValidator,
81
- } from '../../msg_validators/tx_validator/index.js';
72
+ type MessageValidator,
73
+ createTxMessageValidators,
74
+ createTxReqRespValidator,
75
+ } from '../../msg_validators/tx_validator/factory.js';
82
76
  import { GossipSubEvent } from '../../types/index.js';
83
77
  import { type PubSubLibp2p, convertToMultiaddr } from '../../util.js';
84
78
  import { getVersions } from '../../versioning.js';
85
79
  import { AztecDatastore } from '../data_store.js';
86
80
  import { DiscV5Service } from '../discv5/discV5_service.js';
87
81
  import { SnappyTransform, fastMsgIdFn, getMsgIdFn, msgIdToStrFn } from '../encoding.js';
88
- import { gossipScoreThresholds } from '../gossipsub/scoring.js';
82
+ import { APP_SPECIFIC_WEIGHT, gossipScoreThresholds } from '../gossipsub/scoring.js';
83
+ import { createAllTopicScoreParams } from '../gossipsub/topic_score_params.js';
89
84
  import type { PeerManagerInterface } from '../peer-manager/interface.js';
90
85
  import { PeerManager } from '../peer-manager/peer_manager.js';
91
86
  import { PeerScoring } from '../peer-manager/peer_scoring.js';
87
+ import type { BatchTxRequesterLibP2PService } from '../reqresp/batch-tx-requester/interface.js';
92
88
  import type { P2PReqRespConfig } from '../reqresp/config.js';
93
89
  import {
94
90
  DEFAULT_SUB_PROTOCOL_VALIDATORS,
95
91
  type ReqRespInterface,
92
+ type ReqRespResponse,
96
93
  ReqRespSubProtocol,
97
94
  type ReqRespSubProtocolHandler,
98
95
  type ReqRespSubProtocolHandlers,
99
96
  type ReqRespSubProtocolValidators,
100
97
  type SubProtocolMap,
101
98
  ValidationError,
102
- } from '../reqresp/interface.js';
103
- import { reqRespBlockTxsHandler } from '../reqresp/protocols/block_txs/block_txs_handler.js';
104
- import { reqGoodbyeHandler } from '../reqresp/protocols/goodbye.js';
99
+ } from '../reqresp/index.js';
105
100
  import {
106
101
  AuthRequest,
107
102
  BlockTxsRequest,
108
103
  BlockTxsResponse,
109
104
  StatusMessage,
110
105
  pingHandler,
106
+ reqGoodbyeHandler,
111
107
  reqRespBlockHandler,
108
+ reqRespBlockTxsHandler,
112
109
  reqRespStatusHandler,
113
110
  reqRespTxHandler,
114
- } from '../reqresp/protocols/index.js';
111
+ } from '../reqresp/index.js';
115
112
  import { ReqResp } from '../reqresp/reqresp.js';
116
113
  import type {
117
114
  P2PBlockReceivedCallback,
118
115
  P2PCheckpointReceivedCallback,
116
+ P2PDuplicateAttestationCallback,
119
117
  P2PService,
120
118
  PeerDiscoveryService,
121
119
  } from '../service.js';
@@ -130,9 +128,9 @@ interface ValidationResult {
130
128
  type ValidationOutcome = { allPassed: true } | { allPassed: false; failure: ValidationResult };
131
129
 
132
130
  // REFACTOR: Unify with the type above
133
- type ReceivedMessageValidationResult<T> =
134
- | { obj: T; result: Exclude<TopicValidatorResult, TopicValidatorResult.Reject> }
135
- | { obj?: undefined; result: TopicValidatorResult.Reject };
131
+ type ReceivedMessageValidationResult<T, M = undefined> =
132
+ | { obj: T; result: Exclude<TopicValidatorResult, TopicValidatorResult.Reject>; metadata?: M }
133
+ | { obj?: T; result: TopicValidatorResult.Reject; metadata?: M };
136
134
 
137
135
  /**
138
136
  * Lib P2P implementation of the P2PService interface.
@@ -151,6 +149,16 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
151
149
 
152
150
  private feesCache: { blockNumber: BlockNumber; gasFees: GasFees } | undefined;
153
151
 
152
+ /** Callback invoked when a duplicate proposal is detected (triggers slashing). */
153
+ private duplicateProposalCallback?: (info: {
154
+ slot: SlotNumber;
155
+ proposer: EthAddress;
156
+ type: 'checkpoint' | 'block';
157
+ }) => void;
158
+
159
+ /** Callback invoked when a duplicate attestation is detected (triggers slashing). */
160
+ private duplicateAttestationCallback?: P2PDuplicateAttestationCallback;
161
+
154
162
  /**
155
163
  * Callback for when a block is received from a peer.
156
164
  * @param block - The block received from the peer.
@@ -179,9 +187,9 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
179
187
  protected node: PubSubLibp2p,
180
188
  private peerDiscoveryService: PeerDiscoveryService,
181
189
  private reqresp: ReqRespInterface,
182
- private peerManager: PeerManagerInterface,
190
+ protected peerManager: PeerManagerInterface,
183
191
  protected mempools: MemPools,
184
- private archiver: L2BlockSource & ContractDataSource,
192
+ protected archiver: L2BlockSource & ContractDataSource,
185
193
  private epochCache: EpochCacheInterface,
186
194
  private proofVerifier: ClientProtocolCircuitVerifier,
187
195
  private worldStateSynchronizer: WorldStateSynchronizer,
@@ -286,14 +294,14 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
286
294
 
287
295
  const datastore = new AztecDatastore(peerStore);
288
296
 
289
- const otelMetricsAdapter = new OtelMetricsAdapter(telemetry);
297
+ const otelMetricsAdapter = new OtelMetricsAdapter(telemetry, logger.getBindings());
290
298
 
291
299
  const peerDiscoveryService = new DiscV5Service(
292
300
  peerId,
293
301
  config,
294
302
  packageVersion,
295
303
  telemetry,
296
- createLogger(`${logger.module}:discv5_service`),
304
+ createLogger(`${logger.module}:discv5_service`, logger.getBindings()),
297
305
  );
298
306
 
299
307
  // Seed libp2p's bootstrap discovery with private and trusted peers
@@ -307,11 +315,6 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
307
315
  const versions = getVersions(config);
308
316
  const protocolVersion = compressComponentVersions(versions);
309
317
 
310
- const txTopic = createTopicString(TopicType.tx, protocolVersion);
311
- const blockProposalTopic = createTopicString(TopicType.block_proposal, protocolVersion);
312
- const checkpointProposalTopic = createTopicString(TopicType.checkpoint_proposal, protocolVersion);
313
- const checkpointAttestationTopic = createTopicString(TopicType.checkpoint_attestation, protocolVersion);
314
-
315
318
  const preferredPeersEnrs: ENR[] = config.preferredPeers.map(enr => ENR.decodeTxt(enr));
316
319
  const directPeers = (
317
320
  await Promise.all(
@@ -331,6 +334,15 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
331
334
 
332
335
  const announceTcpMultiaddr = config.p2pIp ? [convertToMultiaddr(config.p2pIp, p2pPort, 'tcp')] : [];
333
336
 
337
+ // Create dynamic topic score params based on network configuration
338
+ const l1Constants = epochCache.getL1Constants();
339
+ const topicScoreParams = createAllTopicScoreParams(protocolVersion, {
340
+ slotDurationMs: l1Constants.slotDuration * 1000,
341
+ heartbeatIntervalMs: config.gossipsubInterval,
342
+ targetCommitteeSize: l1Constants.targetCommitteeSize,
343
+ blockDurationMs: config.blockDurationMs,
344
+ });
345
+
334
346
  const node = await createLibp2p({
335
347
  start: false,
336
348
  peerId,
@@ -426,35 +438,14 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
426
438
  scoreParams: createPeerScoreParams({
427
439
  // IPColocation factor can be disabled for local testing - default to -5
428
440
  IPColocationFactorWeight: config.debugDisableColocationPenalty ? 0 : -5.0,
429
- topics: {
430
- [txTopic]: createTopicScoreParams({
431
- topicWeight: 1,
432
- invalidMessageDeliveriesWeight: -20,
433
- invalidMessageDeliveriesDecay: 0.5,
434
- }),
435
- [blockProposalTopic]: createTopicScoreParams({
436
- topicWeight: 1,
437
- invalidMessageDeliveriesWeight: -20,
438
- invalidMessageDeliveriesDecay: 0.5,
439
- }),
440
- [checkpointProposalTopic]: createTopicScoreParams({
441
- topicWeight: 1,
442
- invalidMessageDeliveriesWeight: -20,
443
- invalidMessageDeliveriesDecay: 0.5,
444
- }),
445
- [checkpointAttestationTopic]: createTopicScoreParams({
446
- topicWeight: 1,
447
- invalidMessageDeliveriesWeight: -20,
448
- invalidMessageDeliveriesDecay: 0.5,
449
- }),
450
- },
441
+ topics: topicScoreParams,
451
442
  }),
452
443
  }) as (components: GossipSubComponents) => GossipSub,
453
444
  components: (components: { connectionManager: ConnectionManager }) => ({
454
445
  connectionManager: components.connectionManager,
455
446
  }),
456
447
  },
457
- logger: createLibp2pComponentLogger(logger.module),
448
+ logger: createLibp2pComponentLogger(logger.module, logger.getBindings()),
458
449
  });
459
450
 
460
451
  const peerScoring = new PeerScoring(config, telemetry);
@@ -473,8 +464,12 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
473
464
  epochCache,
474
465
  );
475
466
 
476
- // Update gossipsub score params
477
- node.services.pubsub.score.params.appSpecificWeight = 10;
467
+ // Configure application-specific scoring for gossipsub.
468
+ // The weight scales app score to align with gossipsub thresholds:
469
+ // - Disconnect (-50) × 10 = -500 = gossipThreshold (stops receiving gossip)
470
+ // - Ban (-100) × 10 = -1000 = publishThreshold (cannot publish)
471
+ // Note: positive topic scores can offset penalties, so alignment is best-effort.
472
+ node.services.pubsub.score.params.appSpecificWeight = APP_SPECIFIC_WEIGHT;
478
473
  node.services.pubsub.score.params.appSpecificScore = (peerId: string) =>
479
474
  peerManager.shouldDisableP2PGossip(peerId) ? -Infinity : peerManager.getPeerScore(peerId);
480
475
 
@@ -526,7 +521,11 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
526
521
  };
527
522
 
528
523
  if (!this.config.disableTransactions) {
529
- const blockTxsHandler = reqRespBlockTxsHandler(this.mempools.attestationPool, this.mempools.txPool);
524
+ const blockTxsHandler = reqRespBlockTxsHandler(
525
+ this.mempools.attestationPool,
526
+ this.archiver,
527
+ this.mempools.txPool,
528
+ );
530
529
  requestResponseHandlers[ReqRespSubProtocol.BLOCK_TXS] = blockTxsHandler.bind(this);
531
530
  }
532
531
 
@@ -642,6 +641,15 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
642
641
  return this.reqresp.sendBatchRequest(protocol, requests, pinnedPeerId);
643
642
  }
644
643
 
644
+ public sendRequestToPeer(
645
+ peerId: PeerId,
646
+ subProtocol: ReqRespSubProtocol,
647
+ payload: Buffer,
648
+ dialTimeout?: number,
649
+ ): Promise<ReqRespResponse> {
650
+ return this.reqresp.sendRequestToPeer(peerId, subProtocol, payload, dialTimeout);
651
+ }
652
+
645
653
  /**
646
654
  * Get the ENR of the node
647
655
  * @returns The ENR of the node
@@ -658,6 +666,25 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
658
666
  this.checkpointReceivedCallback = callback;
659
667
  }
660
668
 
669
+ /**
670
+ * Registers a callback to be invoked when a duplicate proposal is detected.
671
+ * This callback is triggered on the first duplicate (when count goes from 1 to 2).
672
+ */
673
+ public registerDuplicateProposalCallback(
674
+ callback: (info: { slot: SlotNumber; proposer: EthAddress; type: 'checkpoint' | 'block' }) => void,
675
+ ): void {
676
+ this.duplicateProposalCallback = callback;
677
+ }
678
+
679
+ /**
680
+ * Registers a callback to be invoked when a duplicate attestation is detected.
681
+ * A validator signing attestations for different proposals at the same slot.
682
+ * This callback is triggered on the first duplicate (when count goes from 1 to 2).
683
+ */
684
+ public registerDuplicateAttestationCallback(callback: P2PDuplicateAttestationCallback): void {
685
+ this.duplicateAttestationCallback = callback;
686
+ }
687
+
661
688
  /**
662
689
  * Subscribes to a topic.
663
690
  * @param topic - The topic to subscribe to.
@@ -844,13 +871,13 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
844
871
  return;
845
872
  }
846
873
 
847
- protected async validateReceivedMessage<T>(
848
- validationFunc: () => Promise<ReceivedMessageValidationResult<T>>,
874
+ protected async validateReceivedMessage<T, M = undefined>(
875
+ validationFunc: () => Promise<ReceivedMessageValidationResult<T, M>>,
849
876
  msgId: string,
850
877
  source: PeerId,
851
878
  topicType: TopicType,
852
- ): Promise<ReceivedMessageValidationResult<T>> {
853
- let resultAndObj: ReceivedMessageValidationResult<T> = { result: TopicValidatorResult.Reject };
879
+ ): Promise<ReceivedMessageValidationResult<T, M>> {
880
+ let resultAndObj: ReceivedMessageValidationResult<T, M> = { result: TopicValidatorResult.Reject };
854
881
  const timer = new Timer();
855
882
  try {
856
883
  resultAndObj = await validationFunc();
@@ -875,20 +902,33 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
875
902
  const validationFunc: () => Promise<ReceivedMessageValidationResult<Tx>> = async () => {
876
903
  const tx = Tx.fromBuffer(payloadData);
877
904
  const isValid = await this.validatePropagatedTx(tx, source);
878
- const exists = isValid && (await this.mempools.txPool.hasTx(tx.getTxHash()));
905
+ if (!isValid) {
906
+ this.logger.trace(`Rejecting invalid propagated tx`, {
907
+ [Attributes.P2P_ID]: source.toString(),
908
+ });
909
+ return { result: TopicValidatorResult.Reject };
910
+ }
911
+
912
+ // Propagate only on pool acceptance
913
+ const txHash = tx.getTxHash();
914
+ const addResult = await this.mempools.txPool.addPendingTxs([tx], { source: 'gossip' });
915
+
916
+ const wasAccepted = addResult.accepted.some(h => h.equals(txHash));
917
+ const wasIgnored = addResult.ignored.some(h => h.equals(txHash));
879
918
 
880
919
  this.logger.trace(`Validate propagated tx`, {
881
920
  isValid,
882
- exists,
921
+ wasAccepted,
922
+ wasIgnored,
883
923
  [Attributes.P2P_ID]: source.toString(),
884
924
  });
885
925
 
886
- if (!isValid) {
887
- return { result: TopicValidatorResult.Reject };
888
- } else if (exists) {
926
+ if (wasAccepted) {
927
+ return { result: TopicValidatorResult.Accept, obj: tx };
928
+ } else if (wasIgnored) {
889
929
  return { result: TopicValidatorResult.Ignore, obj: tx };
890
930
  } else {
891
- return { result: TopicValidatorResult.Accept, obj: tx };
931
+ return { result: TopicValidatorResult.Reject };
892
932
  }
893
933
  };
894
934
 
@@ -897,6 +937,7 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
897
937
  return;
898
938
  }
899
939
 
940
+ // Tx was accepted into pool and will be propagated - just log and record metrics
900
941
  const txHash = tx.getTxHash();
901
942
  const txHashString = txHash.toString();
902
943
  this.logger.verbose(`Received tx ${txHashString} from external peer ${source.toString()} via gossip`, {
@@ -904,13 +945,7 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
904
945
  txHash: txHashString,
905
946
  });
906
947
 
907
- if (this.config.dropTransactions && randomInt(1000) < this.config.dropTransactionsProbability * 1000) {
908
- this.logger.warn(`Intentionally dropping tx ${txHashString} (probability rule)`);
909
- return;
910
- }
911
-
912
948
  this.instrumentation.incrementTxReceived(1);
913
- await this.mempools.txPool.addTxs([tx]);
914
949
  }
915
950
 
916
951
  /**
@@ -922,47 +957,8 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
922
957
  msgId: string,
923
958
  source: PeerId,
924
959
  ): Promise<void> {
925
- const validationFunc: () => Promise<ReceivedMessageValidationResult<CheckpointAttestation>> = async () => {
926
- const attestation = CheckpointAttestation.fromBuffer(payloadData);
927
- const pool = this.mempools.attestationPool;
928
- const validationResult = await this.validateCheckpointAttestation(source, attestation);
929
- const isValid = validationResult.result === 'accept';
930
- const exists = isValid && (await pool.hasCheckpointAttestation(attestation));
931
-
932
- let canAdd = true;
933
- if (isValid && !exists) {
934
- const slot = attestation.payload.header.slotNumber;
935
- const { committee } = await this.epochCache.getCommittee(slot);
936
- const committeeSize = committee?.length ?? 0;
937
- canAdd = await pool.canAddCheckpointAttestation(attestation, committeeSize);
938
- }
939
-
940
- this.logger.trace(`Validate propagated checkpoint attestation`, {
941
- isValid,
942
- exists,
943
- canAdd,
944
- [Attributes.SLOT_NUMBER]: attestation.payload.header.slotNumber.toString(),
945
- [Attributes.P2P_ID]: source.toString(),
946
- });
947
-
948
- if (validationResult.result === 'reject') {
949
- return { result: TopicValidatorResult.Reject };
950
- } else if (validationResult.result === 'ignore' || exists) {
951
- return { result: TopicValidatorResult.Ignore, obj: attestation };
952
- } else if (!canAdd) {
953
- this.logger.warn(`Dropping checkpoint attestation due to per-(slot, proposalId) attestation cap`, {
954
- slot: attestation.payload.header.slotNumber.toString(),
955
- archive: attestation.archive.toString(),
956
- source: source.toString(),
957
- });
958
- return { result: TopicValidatorResult.Ignore, obj: attestation };
959
- } else {
960
- return { result: TopicValidatorResult.Accept, obj: attestation };
961
- }
962
- };
963
-
964
960
  const { result, obj: attestation } = await this.validateReceivedMessage<CheckpointAttestation>(
965
- validationFunc,
961
+ () => this.validateAndStoreCheckpointAttestation(source, CheckpointAttestation.fromBuffer(payloadData)),
966
962
  msgId,
967
963
  source,
968
964
  TopicType.checkpoint_attestation,
@@ -972,8 +968,8 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
972
968
  return;
973
969
  }
974
970
 
975
- this.logger.debug(
976
- `Received checkpoint attestation for slot ${attestation.slotNumber} from external peer ${source.toString()}`,
971
+ this.logger.verbose(
972
+ `Received valid checkpoint attestation for slot ${attestation.slotNumber} from external peer ${source.toString()}`,
977
973
  {
978
974
  p2pMessageIdentifier: await attestation.p2pMessageLoggingIdentifier(),
979
975
  slot: attestation.slotNumber,
@@ -981,60 +977,167 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
981
977
  source: source.toString(),
982
978
  },
983
979
  );
984
-
985
- await this.mempools.attestationPool.addCheckpointAttestations([attestation]);
986
980
  }
987
981
 
988
- private async processBlockFromPeer(payloadData: Buffer, msgId: string, source: PeerId): Promise<void> {
989
- const validationFunc: () => Promise<ReceivedMessageValidationResult<BlockProposal>> = async () => {
990
- const block = BlockProposal.fromBuffer(payloadData);
991
- const validationResult = await this.validateBlockProposal(source, block);
992
- const isValid = validationResult.result === 'accept';
993
- const pool = this.mempools.attestationPool;
982
+ /** Validates a checkpoint attestation and adds it to the pool. Penalizes the peer if validation fails. */
983
+ @trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId, attestation) => ({
984
+ [Attributes.SLOT_NUMBER]: attestation.payload.header.slotNumber.toString(),
985
+ }))
986
+ protected async validateAndStoreCheckpointAttestation(
987
+ peerId: PeerId,
988
+ attestation: CheckpointAttestation,
989
+ ): Promise<ReceivedMessageValidationResult<CheckpointAttestation>> {
990
+ const validationResult = await this.checkpointAttestationValidator.validate(attestation);
994
991
 
995
- const exists = isValid && (await pool.hasBlockProposal(block));
996
- const canAdd = isValid && (await pool.canAddProposal(block));
992
+ if (validationResult.result === 'reject') {
993
+ this.logger.warn(`Penalizing peer ${peerId} for checkpoint attestation validation failure`);
994
+ this.peerManager.penalizePeer(peerId, validationResult.severity);
995
+ return { result: TopicValidatorResult.Reject };
996
+ }
997
997
 
998
- this.logger.trace(`Validate propagated block proposal`, {
999
- isValid,
1000
- exists,
1001
- canAdd,
1002
- [Attributes.SLOT_NUMBER]: block.slotNumber.toString(),
1003
- [Attributes.P2P_ID]: source.toString(),
998
+ if (validationResult.result === 'ignore') {
999
+ return { result: TopicValidatorResult.Ignore, obj: attestation };
1000
+ }
1001
+
1002
+ // Try to add the attestation: this handles existence check, cap check, and adding in one call
1003
+ // count is the number of attestations by this signer for this slot (for duplicate detection)
1004
+ const slot = attestation.payload.header.slotNumber;
1005
+ const { added, alreadyExists, count } =
1006
+ await this.mempools.attestationPool.tryAddCheckpointAttestation(attestation);
1007
+
1008
+ this.logger.trace(`Validate propagated checkpoint attestation`, {
1009
+ added,
1010
+ alreadyExists,
1011
+ count,
1012
+ [Attributes.SLOT_NUMBER]: slot.toString(),
1013
+ [Attributes.P2P_ID]: peerId.toString(),
1014
+ });
1015
+
1016
+ // Exact same attestation received, no need to re-broadcast
1017
+ if (alreadyExists) {
1018
+ return { result: TopicValidatorResult.Ignore, obj: attestation };
1019
+ }
1020
+
1021
+ // Could not add (cap reached for signer), no need to re-broadcast
1022
+ if (!added) {
1023
+ this.logger.warn(`Dropping checkpoint attestation due to cap`, {
1024
+ slot: slot.toString(),
1025
+ archive: attestation.archive.toString(),
1026
+ source: peerId.toString(),
1027
+ attester: attestation.getSender()?.toString(),
1028
+ count,
1004
1029
  });
1030
+ return { result: TopicValidatorResult.Ignore, obj: attestation };
1031
+ }
1005
1032
 
1006
- if (validationResult.result === 'reject') {
1007
- return { result: TopicValidatorResult.Reject };
1008
- } else if (validationResult.result === 'ignore' || exists) {
1009
- return { result: TopicValidatorResult.Ignore, obj: block };
1010
- } else if (!canAdd) {
1011
- this.peerManager.penalizePeer(source, PeerErrorSeverity.MidToleranceError);
1012
- this.logger.warn(`Penalizing peer for block proposal exceeding per-slot cap`, {
1013
- slot: block.slotNumber.toString(),
1014
- archive: block.archive.toString(),
1015
- source: source.toString(),
1033
+ // Check if this is a duplicate attestation (signer attested to a different proposal at the same slot)
1034
+ // count is the number of attestations by this signer for this slot
1035
+ if (count === 2) {
1036
+ const attester = attestation.getSender();
1037
+ if (attester) {
1038
+ this.logger.warn(`Detected duplicate attestation (equivocation) at slot ${slot}`, {
1039
+ slot: slot.toString(),
1040
+ archive: attestation.archive.toString(),
1041
+ source: peerId.toString(),
1042
+ attester: attester.toString(),
1016
1043
  });
1017
- return { result: TopicValidatorResult.Reject };
1018
- } else {
1019
- return { result: TopicValidatorResult.Accept, obj: block };
1044
+ this.duplicateAttestationCallback?.({ slot, attester });
1020
1045
  }
1021
- };
1046
+ }
1047
+
1048
+ // Attestation was added successfully - accept it so other nodes can also detect the equivocation
1049
+ return { result: TopicValidatorResult.Accept, obj: attestation };
1050
+ }
1022
1051
 
1023
- const { result, obj: block } = await this.validateReceivedMessage<BlockProposal>(
1024
- validationFunc,
1052
+ protected async processBlockFromPeer(payloadData: Buffer, msgId: string, source: PeerId): Promise<void> {
1053
+ const {
1054
+ result,
1055
+ obj: block,
1056
+ metadata: { isEquivocated } = {},
1057
+ } = await this.validateReceivedMessage<BlockProposal, { isEquivocated: boolean }>(
1058
+ () => this.validateAndStoreBlockProposal(source, BlockProposal.fromBuffer(payloadData)),
1025
1059
  msgId,
1026
1060
  source,
1027
1061
  TopicType.block_proposal,
1028
1062
  );
1029
1063
 
1030
- if (!result || !block) {
1064
+ // If not accepted or equivocated, return
1065
+ if (result !== TopicValidatorResult.Accept || !block || isEquivocated) {
1031
1066
  return;
1032
1067
  }
1033
1068
 
1034
1069
  await this.processValidBlockProposal(block, source);
1035
1070
  }
1036
1071
 
1037
- // REVIEW: callback pattern https://github.com/AztecProtocol/aztec-packages/issues/7963
1072
+ /** Validates a block proposal. Triggers a penalization to the peer that sent it if invalid. Adds to the mempool if valid. */
1073
+ @trackSpan('Libp2pService.validateAndStoreBlockProposal', (_peerId, block) => ({
1074
+ [Attributes.BLOCK_NUMBER]: block.blockNumber.toString(),
1075
+ [Attributes.SLOT_NUMBER]: block.slotNumber.toString(),
1076
+ }))
1077
+ protected async validateAndStoreBlockProposal(
1078
+ peerId: PeerId,
1079
+ block: BlockProposal,
1080
+ ): Promise<ReceivedMessageValidationResult<BlockProposal, { isEquivocated: boolean }>> {
1081
+ const validationResult = await this.blockProposalValidator.validate(block);
1082
+
1083
+ if (validationResult.result === 'reject') {
1084
+ this.logger.warn(`Penalizing peer ${peerId} for block proposal validation failure`);
1085
+ this.peerManager.penalizePeer(peerId, validationResult.severity);
1086
+ return { result: TopicValidatorResult.Reject };
1087
+ }
1088
+
1089
+ if (validationResult.result === 'ignore') {
1090
+ return { result: TopicValidatorResult.Ignore, obj: block };
1091
+ }
1092
+
1093
+ // Try to add the proposal: this handles existence check, cap check, and adding in one call
1094
+ const { added, alreadyExists, count } = await this.mempools.attestationPool.tryAddBlockProposal(block);
1095
+ const isEquivocated = count !== undefined && count > 1;
1096
+
1097
+ // Duplicate proposal received, no need to re-broadcast
1098
+ if (alreadyExists) {
1099
+ this.logger.debug(`Ignoring duplicate block proposal received`, {
1100
+ ...block.toBlockInfo(),
1101
+ indexWithinCheckpoint: block.indexWithinCheckpoint,
1102
+ proposer: block.getSender()?.toString(),
1103
+ source: peerId.toString(),
1104
+ });
1105
+ return { result: TopicValidatorResult.Ignore, obj: block, metadata: { isEquivocated } };
1106
+ }
1107
+
1108
+ // Too many blocks received for this slot and index, penalize peer and do not re-broadcast
1109
+ if (!added) {
1110
+ this.peerManager.penalizePeer(peerId, PeerErrorSeverity.HighToleranceError);
1111
+ this.logger.warn(`Penalizing peer for block proposal exceeding per-position cap`, {
1112
+ ...block.toBlockInfo(),
1113
+ indexWithinCheckpoint: block.indexWithinCheckpoint,
1114
+ count,
1115
+ proposer: block.getSender()?.toString(),
1116
+ source: peerId.toString(),
1117
+ });
1118
+ return { result: TopicValidatorResult.Reject, metadata: { isEquivocated } };
1119
+ }
1120
+
1121
+ // If this was a duplicate proposal, do not process it, but do invoke the duplicate callback,
1122
+ // and do re-broadcast it so other nodes in the network know to slash the proposer
1123
+ if (isEquivocated) {
1124
+ const proposer = block.getSender();
1125
+ this.logger.warn(`Detected duplicate block proposal (equivocation) at slot ${block.slotNumber}`, {
1126
+ ...block.toBlockInfo(),
1127
+ source: peerId.toString(),
1128
+ proposer: proposer?.toString(),
1129
+ });
1130
+ // Invoke the duplicate callback on the first duplicate spotted only
1131
+ if (proposer && count === 2) {
1132
+ this.duplicateProposalCallback?.({ slot: block.slotNumber, proposer, type: 'block' });
1133
+ }
1134
+ return { result: TopicValidatorResult.Accept, obj: block, metadata: { isEquivocated } };
1135
+ }
1136
+
1137
+ // Otherwise, we're good to go!
1138
+ return { result: TopicValidatorResult.Accept, obj: block };
1139
+ }
1140
+
1038
1141
  // REFACTOR(palla): This method should be moved to the p2p_client or to a separate component,
1039
1142
  // should not be here as it does not deal with p2p networking.
1040
1143
  @trackSpan('Libp2pService.processValidBlockProposal', async block => ({
@@ -1042,7 +1145,7 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1042
1145
  [Attributes.BLOCK_ARCHIVE]: block.archive.toString(),
1043
1146
  [Attributes.P2P_ID]: await block.p2pMessageLoggingIdentifier().then(i => i.toString()),
1044
1147
  }))
1045
- private async processValidBlockProposal(block: BlockProposal, sender: PeerId) {
1148
+ protected async processValidBlockProposal(block: BlockProposal, sender: PeerId) {
1046
1149
  const slot = block.slotNumber;
1047
1150
  this.logger.verbose(`Received block proposal for slot ${slot} from external peer ${sender.toString()}.`, {
1048
1151
  p2pMessageIdentifier: await block.p2pMessageLoggingIdentifier(),
@@ -1050,24 +1153,8 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1050
1153
  ...block.toBlockInfo(),
1051
1154
  });
1052
1155
 
1053
- // Attempt to add proposal
1054
- try {
1055
- await this.mempools.attestationPool.addBlockProposal(block);
1056
- } catch (err: unknown) {
1057
- // Drop proposals if we hit per-slot cap in the attestation pool; rethrow unknown errors
1058
- if (err instanceof ProposalSlotCapExceededError) {
1059
- this.logger.warn(`Dropping block proposal due to per-slot proposal cap`, {
1060
- slot: String(slot),
1061
- archive: block.archive.toString(),
1062
- error: (err as Error).message,
1063
- });
1064
- return;
1065
- }
1066
- throw err;
1067
- }
1068
-
1069
- // Mark the txs in this proposal as non-evictable
1070
- await this.mempools.txPool.markTxsAsNonEvictable(block.txHashes);
1156
+ // Mark the txs in this proposal as protected
1157
+ await this.mempools.txPool.protectTxs(block.txHashes, block.blockHeader);
1071
1158
 
1072
1159
  // Call the block received callback to validate the proposal.
1073
1160
  // Note: Validators do NOT attest to individual blocks, only to checkpoint proposals.
@@ -1081,67 +1168,145 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1081
1168
  * Handle a gossiped checkpoint proposal.
1082
1169
  * Validates and processes the checkpoint proposal, then triggers the callback for attestation.
1083
1170
  */
1084
- private async handleGossipedCheckpointProposal(payloadData: Buffer, msgId: string, source: PeerId): Promise<void> {
1085
- // TODO(palla/mbps): This pattern is repeated across multiple message handlers, consider abstracting it.
1086
- const validationFunc: () => Promise<ReceivedMessageValidationResult<CheckpointProposal>> = async () => {
1087
- const checkpoint = CheckpointProposal.fromBuffer(payloadData);
1088
- const validationResult = await this.validateCheckpointProposal(source, checkpoint);
1089
- const isValid = validationResult.result === 'accept';
1090
- const pool = this.mempools.attestationPool;
1091
-
1092
- const exists = isValid && (await pool.hasCheckpointProposal(checkpoint));
1093
- const canAdd = isValid && (await pool.canAddCheckpointProposal(checkpoint));
1094
-
1095
- this.logger.trace(`Validate propagated checkpoint proposal`, {
1096
- isValid,
1097
- exists,
1098
- canAdd,
1171
+ protected async handleGossipedCheckpointProposal(payloadData: Buffer, msgId: string, source: PeerId): Promise<void> {
1172
+ const {
1173
+ result,
1174
+ obj: checkpoint,
1175
+ metadata: { isEquivocated, processBlock } = {},
1176
+ } = await this.validateReceivedMessage<CheckpointProposal, { isEquivocated: boolean; processBlock: boolean }>(
1177
+ () => this.validateAndStoreCheckpointProposal(source, CheckpointProposal.fromBuffer(payloadData)),
1178
+ msgId,
1179
+ source,
1180
+ TopicType.checkpoint_proposal,
1181
+ );
1182
+
1183
+ // If the checkpoint contained a valid last block, we process it even if the checkpoint itself is to be rejected
1184
+ // TODO(palla/mbps): Is this ok? Should we be considering a block from a checkpoint that was equivocated?
1185
+ if (processBlock && checkpoint?.getBlockProposal()) {
1186
+ await this.processValidBlockProposal(checkpoint.getBlockProposal()!, source);
1187
+ }
1188
+
1189
+ if (result !== TopicValidatorResult.Accept || !checkpoint || isEquivocated) {
1190
+ return;
1191
+ }
1192
+
1193
+ await this.processValidCheckpointProposal(checkpoint.toCore(), source);
1194
+ }
1195
+
1196
+ /**
1197
+ * Validates a checkpoint proposal. Penalizes peer if validation fails. Adds the checkpoint and
1198
+ * its last block (if present) to the mempool if valid. Triggers equivocation detection on both.
1199
+ */
1200
+ @trackSpan('Libp2pService.validateAndStoreCheckpointProposal', (_peerId, checkpoint) => ({
1201
+ [Attributes.SLOT_NUMBER]: checkpoint.slotNumber.toString(),
1202
+ }))
1203
+ protected async validateAndStoreCheckpointProposal(
1204
+ peerId: PeerId,
1205
+ checkpoint: CheckpointProposal,
1206
+ ): Promise<ReceivedMessageValidationResult<CheckpointProposal, { isEquivocated: boolean; processBlock: boolean }>> {
1207
+ const validationResult = await this.checkpointProposalValidator.validate(checkpoint);
1208
+
1209
+ if (validationResult.result === 'reject') {
1210
+ this.logger.warn(`Penalizing peer ${peerId} for checkpoint proposal validation failure`);
1211
+ this.peerManager.penalizePeer(peerId, validationResult.severity);
1212
+ return { result: TopicValidatorResult.Reject };
1213
+ }
1214
+
1215
+ if (validationResult.result === 'ignore') {
1216
+ return { result: TopicValidatorResult.Ignore, obj: checkpoint };
1217
+ }
1218
+
1219
+ // Extract and try to add the block proposal first if present
1220
+ const blockProposal = checkpoint.getBlockProposal();
1221
+ let processBlock = false;
1222
+ if (blockProposal) {
1223
+ this.logger.debug(`Validating block proposal from propagated checkpoint`, {
1099
1224
  [Attributes.SLOT_NUMBER]: checkpoint.slotNumber.toString(),
1100
- [Attributes.P2P_ID]: source.toString(),
1225
+ [Attributes.P2P_ID]: peerId.toString(),
1101
1226
  });
1102
-
1103
- if (validationResult.result === 'reject') {
1104
- return { result: TopicValidatorResult.Reject };
1105
- } else if (validationResult.result === 'ignore' || exists) {
1106
- return { result: TopicValidatorResult.Ignore, obj: checkpoint };
1107
- } else if (!canAdd) {
1108
- this.peerManager.penalizePeer(source, PeerErrorSeverity.MidToleranceError);
1109
- this.logger.warn(`Penalizing peer for checkpoint proposal exceeding per-slot cap`, {
1110
- slot: checkpoint.slotNumber.toString(),
1111
- archive: checkpoint.archive.toString(),
1112
- source: source.toString(),
1227
+ const {
1228
+ result,
1229
+ obj,
1230
+ metadata: { isEquivocated } = {},
1231
+ } = await this.validateAndStoreBlockProposal(peerId, blockProposal);
1232
+ if (result === TopicValidatorResult.Reject || !obj || isEquivocated) {
1233
+ this.logger.debug(`Rejecting checkpoint due to invalid last block proposal`, {
1234
+ [Attributes.SLOT_NUMBER]: checkpoint.slotNumber.toString(),
1235
+ [Attributes.P2P_ID]: peerId.toString(),
1236
+ isEquivocated,
1237
+ result,
1113
1238
  });
1114
1239
  return { result: TopicValidatorResult.Reject };
1115
- } else {
1116
- return { result: TopicValidatorResult.Accept, obj: checkpoint };
1240
+ } else if (result === TopicValidatorResult.Accept && obj && !isEquivocated) {
1241
+ processBlock = true;
1117
1242
  }
1118
- };
1243
+ }
1119
1244
 
1120
- const { result, obj: checkpoint } = await this.validateReceivedMessage<CheckpointProposal>(
1121
- validationFunc,
1122
- msgId,
1123
- source,
1124
- TopicType.checkpoint_proposal,
1125
- );
1245
+ // Try to add the checkpoint proposal core: this handles existence check, cap check, and adding in one call
1246
+ const checkpointCore = checkpoint.toCore();
1247
+ const tryAddResult = await this.mempools.attestationPool.tryAddCheckpointProposal(checkpointCore);
1248
+ const { added, alreadyExists, count } = tryAddResult;
1249
+ const isEquivocated = count !== undefined && count > 1;
1250
+
1251
+ // Duplicate proposal received, do not re-broadcast
1252
+ if (alreadyExists) {
1253
+ this.logger.debug(`Ignoring duplicate checkpoint proposal received`, {
1254
+ ...checkpoint.toCheckpointInfo(),
1255
+ source: peerId.toString(),
1256
+ });
1257
+ return {
1258
+ result: TopicValidatorResult.Ignore,
1259
+ obj: checkpoint,
1260
+ metadata: { isEquivocated, processBlock },
1261
+ };
1262
+ }
1126
1263
 
1127
- if (result !== TopicValidatorResult.Accept || !checkpoint) {
1128
- return;
1264
+ // Too many checkpoint proposals received for this slot, penalize peer and do not re-broadcast
1265
+ // Note: We still return the checkpoint obj so the lastBlock can be processed if valid
1266
+ if (!added) {
1267
+ this.peerManager.penalizePeer(peerId, PeerErrorSeverity.HighToleranceError);
1268
+ this.logger.warn(`Penalizing peer for checkpoint proposal exceeding per-slot cap`, {
1269
+ ...checkpoint.toCheckpointInfo(),
1270
+ count,
1271
+ source: peerId.toString(),
1272
+ });
1273
+ return { result: TopicValidatorResult.Reject, obj: checkpoint, metadata: { isEquivocated, processBlock } };
1129
1274
  }
1130
1275
 
1131
- await this.processValidCheckpointProposal(checkpoint, source);
1276
+ // If this was a duplicate proposal, do not process it, but do invoke the duplicate callback,
1277
+ // and do re-broadcast it so other nodes in the network know to slash the proposer
1278
+ if (isEquivocated) {
1279
+ const proposer = checkpoint.getSender();
1280
+ this.logger.warn(`Detected duplicate checkpoint proposal (equivocation) at slot ${checkpoint.slotNumber}`, {
1281
+ ...checkpoint.toCheckpointInfo(),
1282
+ source: peerId.toString(),
1283
+ proposer: proposer?.toString(),
1284
+ });
1285
+ // Invoke the duplicate callback on the first duplicate spotted only
1286
+ if (proposer && count === 2) {
1287
+ this.duplicateProposalCallback?.({ slot: checkpoint.slotNumber, proposer, type: 'checkpoint' });
1288
+ }
1289
+ return {
1290
+ result: TopicValidatorResult.Accept,
1291
+ obj: checkpoint,
1292
+ metadata: { isEquivocated, processBlock },
1293
+ };
1294
+ }
1295
+
1296
+ // Otherwise, we're good to go!
1297
+ return { result: TopicValidatorResult.Accept, obj: checkpoint, metadata: { processBlock, isEquivocated } };
1132
1298
  }
1133
1299
 
1134
1300
  /**
1135
1301
  * Process a validated checkpoint proposal.
1136
- * Extracts and processes the last block proposal (if present) first, then processes the checkpoint.
1137
- * The block callback is invoked before the checkpoint callback.
1302
+ * Note: The proposal was already added to the pool by tryAddCheckpointProposal in handleGossipedCheckpointProposal.
1138
1303
  */
1139
1304
  @trackSpan('Libp2pService.processValidCheckpointProposal', async checkpoint => ({
1140
1305
  [Attributes.SLOT_NUMBER]: checkpoint.slotNumber,
1141
1306
  [Attributes.BLOCK_ARCHIVE]: checkpoint.archive.toString(),
1142
1307
  [Attributes.P2P_ID]: await checkpoint.p2pMessageLoggingIdentifier().then(i => i.toString()),
1143
1308
  }))
1144
- private async processValidCheckpointProposal(checkpoint: CheckpointProposal, sender: PeerId) {
1309
+ protected async processValidCheckpointProposal(checkpoint: CheckpointProposalCore, sender: PeerId) {
1145
1310
  const slot = checkpoint.slotNumber;
1146
1311
  this.logger.verbose(`Received checkpoint proposal for slot ${slot} from external peer ${sender.toString()}.`, {
1147
1312
  p2pMessageIdentifier: await checkpoint.p2pMessageLoggingIdentifier(),
@@ -1150,37 +1315,12 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1150
1315
  source: sender.toString(),
1151
1316
  });
1152
1317
 
1153
- // Extract block proposal before adding to pool (pool stores them separately)
1154
- const blockProposal = checkpoint.getBlockProposal();
1155
-
1156
- // Add proposal to the pool (this extracts and stores block proposal separately)
1157
- await this.mempools.attestationPool.addCheckpointProposal(checkpoint);
1158
-
1159
- // Mark txs as non-evictable if present (from the last block)
1160
- if (checkpoint.txHashes.length > 0) {
1161
- await this.mempools.txPool.markTxsAsNonEvictable(checkpoint.txHashes);
1162
- }
1163
-
1164
- // If there was a last block proposal, invoke the block callback first for validation.
1165
- // Note: The block proposal is already stored in the pool by addCheckpointProposal.
1166
- if (blockProposal) {
1167
- const isValid = await this.blockReceivedCallback(blockProposal, sender);
1168
- if (!isValid) {
1169
- this.logger.warn(`Block proposal from checkpoint failed validation`, {
1170
- slot: slot.toString(),
1171
- archive: checkpoint.archive.toString(),
1172
- blockNumber: blockProposal.blockNumber.toString(),
1173
- });
1174
- return;
1175
- }
1176
- }
1177
-
1178
1318
  // Call the checkpoint received callback with the core version (without lastBlock)
1179
1319
  // to validate and potentially generate attestations
1180
- const attestations = await this.checkpointReceivedCallback(checkpoint.toCore(), sender);
1320
+ const attestations = await this.checkpointReceivedCallback(checkpoint, sender);
1181
1321
  if (attestations && attestations.length > 0) {
1182
1322
  // If the callback returned attestations, add them to the pool and propagate them
1183
- await this.mempools.attestationPool.addCheckpointAttestations(attestations);
1323
+ await this.mempools.attestationPool.addOwnCheckpointAttestations(attestations);
1184
1324
  for (const attestation of attestations) {
1185
1325
  await this.propagate(attestation);
1186
1326
  }
@@ -1207,9 +1347,9 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1207
1347
  * @returns True if the requested block transactions are valid, false otherwise.
1208
1348
  */
1209
1349
  @trackSpan('Libp2pService.validateRequestedBlockTxs', request => ({
1210
- [Attributes.BLOCK_HASH]: request.blockHash.toString(),
1350
+ [Attributes.BLOCK_ARCHIVE]: request.archiveRoot.toString(),
1211
1351
  }))
1212
- private async validateRequestedBlockTxs(
1352
+ protected async validateRequestedBlockTxs(
1213
1353
  request: BlockTxsRequest,
1214
1354
  response: BlockTxsResponse,
1215
1355
  peerId: PeerId,
@@ -1217,10 +1357,10 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1217
1357
  const requestedTxValidator = this.createRequestedTxValidator();
1218
1358
 
1219
1359
  try {
1220
- if (!response.blockHash.equals(request.blockHash)) {
1360
+ if (!response.archiveRoot.equals(request.archiveRoot)) {
1221
1361
  this.peerManager.penalizePeer(peerId, PeerErrorSeverity.MidToleranceError);
1222
1362
  throw new ValidationError(
1223
- `Received block txs for unexpected block: expected ${request.blockHash.toString()}, got ${response.blockHash.toString()}`,
1363
+ `Received block txs for unexpected archive root: expected ${request.archiveRoot.toString()}, got ${response.archiveRoot.toString()}`,
1224
1364
  );
1225
1365
  }
1226
1366
 
@@ -1250,7 +1390,7 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1250
1390
  }
1251
1391
 
1252
1392
  // Given proposal (should have locally), ensure returned txs are valid subset and match request indices
1253
- const proposal = await this.mempools.attestationPool.getBlockProposal(request.blockHash.toString());
1393
+ const proposal = await this.mempools.attestationPool.getBlockProposal(request.archiveRoot.toString());
1254
1394
  if (proposal) {
1255
1395
  // Build intersected indices
1256
1396
  const intersectIdx = request.txIndices.getTrueIndices().filter(i => response.txIndices.isSet(i));
@@ -1270,7 +1410,7 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1270
1410
  } else {
1271
1411
  // No local proposal, cannot check the membership/order of the returned txs
1272
1412
  this.logger.warn(
1273
- `Block proposal not found for block hash ${request.blockHash.toString()}; cannot validate membership/order of returned txs`,
1413
+ `Block proposal not found for archive root ${request.archiveRoot.toString()}; cannot validate membership/order of returned txs`,
1274
1414
  );
1275
1415
  return false;
1276
1416
  }
@@ -1309,7 +1449,7 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1309
1449
  const requested = new Set(requestedTxHash.map(h => h.toString()));
1310
1450
  const requestedTxValidator = this.createRequestedTxValidator();
1311
1451
 
1312
- //TODO: (mralj) - this is somewhat naive implementation, if single tx is invlid we consider the whole response invalid.
1452
+ //TODO: (mralj) - this is somewhat naive implementation, if single tx is invalid we consider the whole response invalid.
1313
1453
  // I think we should still extract the valid txs and return them, so that we can still use the response.
1314
1454
  try {
1315
1455
  await Promise.all(responseTx.map(tx => this.validateRequestedTx(tx, peerId, requestedTxValidator, requested)));
@@ -1339,7 +1479,7 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1339
1479
  @trackSpan('Libp2pService.validateRequestedBlock', (requestedBlockNumber, _responseBlock) => ({
1340
1480
  [Attributes.BLOCK_NUMBER]: requestedBlockNumber.toString(),
1341
1481
  }))
1342
- private async validateRequestedBlock(
1482
+ protected async validateRequestedBlock(
1343
1483
  requestedBlockNumber: Fr,
1344
1484
  responseBlock: L2Block,
1345
1485
  peerId: PeerId,
@@ -1372,28 +1512,13 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1372
1512
  }
1373
1513
  }
1374
1514
 
1375
- private createRequestedTxValidator(): TxValidator {
1376
- return new AggregateTxValidator(
1377
- new DataTxValidator(),
1378
- new SizeTxValidator(),
1379
- new MetadataTxValidator({
1380
- l1ChainId: new Fr(this.config.l1ChainId),
1381
- rollupVersion: new Fr(this.config.rollupVersion),
1382
- protocolContractsHash,
1383
- vkTreeRoot: getVKTreeRoot(),
1384
- }),
1385
- new TxProofValidator(this.proofVerifier),
1386
- );
1387
- }
1388
-
1389
- private async validateRequestedTx(tx: Tx, peerId: PeerId, txValidator: TxValidator, requested?: Set<`0x${string}`>) {
1515
+ protected async validateRequestedTx(
1516
+ tx: Tx,
1517
+ peerId: PeerId,
1518
+ txValidator: TxValidator,
1519
+ requested?: Set<`0x${string}`>,
1520
+ ) {
1390
1521
  const penalize = (severity: PeerErrorSeverity) => this.peerManager.penalizePeer(peerId, severity);
1391
-
1392
- if (!(await tx.validateTxHash())) {
1393
- penalize(PeerErrorSeverity.MidToleranceError);
1394
- throw new ValidationError(`Received tx with invalid hash ${tx.getTxHash().toString()}.`);
1395
- }
1396
-
1397
1522
  if (requested && !requested.has(tx.getTxHash().toString())) {
1398
1523
  penalize(PeerErrorSeverity.MidToleranceError);
1399
1524
  throw new ValidationError(`Received tx with hash ${tx.getTxHash().toString()} that was not requested.`);
@@ -1406,10 +1531,17 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1406
1531
  }
1407
1532
  }
1408
1533
 
1534
+ protected createRequestedTxValidator(): TxValidator {
1535
+ return createTxReqRespValidator(this.proofVerifier, {
1536
+ l1ChainId: this.config.l1ChainId,
1537
+ rollupVersion: this.config.rollupVersion,
1538
+ });
1539
+ }
1540
+
1409
1541
  @trackSpan('Libp2pService.validatePropagatedTx', tx => ({
1410
1542
  [Attributes.TX_HASH]: tx.getTxHash().toString(),
1411
1543
  }))
1412
- private async validatePropagatedTx(tx: Tx, peerId: PeerId): Promise<boolean> {
1544
+ protected async validatePropagatedTx(tx: Tx, peerId: PeerId): Promise<boolean> {
1413
1545
  const currentBlockNumber = await this.archiver.getBlockNumber();
1414
1546
 
1415
1547
  // We accept transactions if they are not expired by the next slot (checked based on the IncludeByTimestamp field)
@@ -1448,6 +1580,22 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1448
1580
  return gasFees;
1449
1581
  }
1450
1582
 
1583
+ /**
1584
+ * Get the BatchTxRequesterLibP2PService dependencies for creating BatchTxRequester instances
1585
+ */
1586
+ public getBatchTxRequesterService(): BatchTxRequesterLibP2PService {
1587
+ return {
1588
+ reqResp: this.reqresp,
1589
+ connectionSampler: this.reqresp.getConnectionSampler(),
1590
+ txValidatorConfig: {
1591
+ l1ChainId: this.config.l1ChainId,
1592
+ rollupVersion: this.config.rollupVersion,
1593
+ proofVerifier: this.proofVerifier,
1594
+ },
1595
+ peerScoring: this.peerManager,
1596
+ };
1597
+ }
1598
+
1451
1599
  public async validate(txs: Tx[]): Promise<void> {
1452
1600
  const currentBlockNumber = await this.archiver.getBlockNumber();
1453
1601
 
@@ -1498,6 +1646,7 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1498
1646
  this.proofVerifier,
1499
1647
  !this.config.disableTransactions,
1500
1648
  allowedInSetup,
1649
+ this.logger.getBindings(),
1501
1650
  );
1502
1651
  }
1503
1652
 
@@ -1551,15 +1700,18 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1551
1700
  return PeerErrorSeverity.HighToleranceError;
1552
1701
  }
1553
1702
 
1554
- const snapshotValidator = new DoubleSpendTxValidator({
1555
- nullifiersExist: async (nullifiers: Buffer[]) => {
1556
- const merkleTree = this.worldStateSynchronizer.getSnapshot(
1557
- BlockNumber(blockNumber - this.config.doubleSpendSeverePeerPenaltyWindow),
1558
- );
1559
- const indices = await merkleTree.findLeafIndices(MerkleTreeId.NULLIFIER_TREE, nullifiers);
1560
- return indices.map(index => index !== undefined);
1703
+ const snapshotValidator = new DoubleSpendTxValidator(
1704
+ {
1705
+ nullifiersExist: async (nullifiers: Buffer[]) => {
1706
+ const merkleTree = this.worldStateSynchronizer.getSnapshot(
1707
+ BlockNumber(blockNumber - this.config.doubleSpendSeverePeerPenaltyWindow),
1708
+ );
1709
+ const indices = await merkleTree.findLeafIndices(MerkleTreeId.NULLIFIER_TREE, nullifiers);
1710
+ return indices.map(index => index !== undefined);
1711
+ },
1561
1712
  },
1562
- });
1713
+ this.logger.getBindings(),
1714
+ );
1563
1715
 
1564
1716
  const validSnapshot = await snapshotValidator.validateTx(tx);
1565
1717
  if (validSnapshot.result !== 'valid') {
@@ -1587,50 +1739,7 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1587
1739
  const result = await this.checkpointAttestationValidator.validate(attestation);
1588
1740
 
1589
1741
  if (result.result === 'reject') {
1590
- this.logger.debug(`Penalizing peer ${peerId} for checkpoint attestation validation failure`);
1591
- this.peerManager.penalizePeer(peerId, result.severity);
1592
- }
1593
-
1594
- return result;
1595
- }
1596
-
1597
- /**
1598
- * Validate a block proposal.
1599
- *
1600
- * @param block - The block proposal to validate.
1601
- * @returns True if the block proposal is valid, false otherwise.
1602
- */
1603
- @trackSpan('Libp2pService.validateBlockProposal', (_peerId, block) => ({
1604
- [Attributes.SLOT_NUMBER]: block.slotNumber.toString(),
1605
- }))
1606
- public async validateBlockProposal(peerId: PeerId, block: BlockProposal): Promise<P2PValidationResult> {
1607
- const result = await this.blockProposalValidator.validate(block);
1608
-
1609
- if (result.result === 'reject') {
1610
- this.logger.debug(`Penalizing peer ${peerId} for block proposal validation failure`);
1611
- this.peerManager.penalizePeer(peerId, result.severity);
1612
- }
1613
-
1614
- return result;
1615
- }
1616
-
1617
- /**
1618
- * Validate a checkpoint proposal.
1619
- *
1620
- * @param checkpoint - The checkpoint proposal to validate.
1621
- * @returns True if the checkpoint proposal is valid, false otherwise.
1622
- */
1623
- @trackSpan('Libp2pService.validateCheckpointProposal', (_peerId, checkpoint) => ({
1624
- [Attributes.SLOT_NUMBER]: checkpoint.slotNumber.toString(),
1625
- }))
1626
- public async validateCheckpointProposal(
1627
- peerId: PeerId,
1628
- checkpoint: CheckpointProposal,
1629
- ): Promise<P2PValidationResult> {
1630
- const result = await this.checkpointProposalValidator.validate(checkpoint);
1631
-
1632
- if (result.result === 'reject') {
1633
- this.logger.debug(`Penalizing peer ${peerId} for checkpoint proposal validation failure`);
1742
+ this.logger.warn(`Penalizing peer ${peerId} for checkpoint attestation validation failure`);
1634
1743
  this.peerManager.penalizePeer(peerId, result.severity);
1635
1744
  }
1636
1745