@aztec-labs/p2p 6.0.0-nightly.20260829

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 (607) hide show
  1. package/README.md +134 -0
  2. package/dest/bootstrap/bootstrap.d.ts +39 -0
  3. package/dest/bootstrap/bootstrap.d.ts.map +1 -0
  4. package/dest/bootstrap/bootstrap.js +152 -0
  5. package/dest/client/factory.d.ts +32 -0
  6. package/dest/client/factory.d.ts.map +1 -0
  7. package/dest/client/factory.js +125 -0
  8. package/dest/client/index.d.ts +4 -0
  9. package/dest/client/index.d.ts.map +1 -0
  10. package/dest/client/index.js +3 -0
  11. package/dest/client/interface.d.ts +223 -0
  12. package/dest/client/interface.d.ts.map +1 -0
  13. package/dest/client/interface.js +9 -0
  14. package/dest/client/p2p_client.d.ts +202 -0
  15. package/dest/client/p2p_client.d.ts.map +1 -0
  16. package/dest/client/p2p_client.js +1051 -0
  17. package/dest/config.d.ts +295 -0
  18. package/dest/config.d.ts.map +1 -0
  19. package/dest/config.js +458 -0
  20. package/dest/enr/generate-enr.d.ts +17 -0
  21. package/dest/enr/generate-enr.d.ts.map +1 -0
  22. package/dest/enr/generate-enr.js +52 -0
  23. package/dest/enr/index.d.ts +2 -0
  24. package/dest/enr/index.d.ts.map +1 -0
  25. package/dest/enr/index.js +1 -0
  26. package/dest/errors/attestation-pool.error.d.ts +7 -0
  27. package/dest/errors/attestation-pool.error.d.ts.map +1 -0
  28. package/dest/errors/attestation-pool.error.js +12 -0
  29. package/dest/errors/p2p-service.error.d.ts +9 -0
  30. package/dest/errors/p2p-service.error.d.ts.map +1 -0
  31. package/dest/errors/p2p-service.error.js +10 -0
  32. package/dest/errors/reqresp.error.d.ts +21 -0
  33. package/dest/errors/reqresp.error.d.ts.map +1 -0
  34. package/dest/errors/reqresp.error.js +23 -0
  35. package/dest/errors/tx-pool.error.d.ts +8 -0
  36. package/dest/errors/tx-pool.error.d.ts.map +1 -0
  37. package/dest/errors/tx-pool.error.js +9 -0
  38. package/dest/index.d.ts +11 -0
  39. package/dest/index.d.ts.map +1 -0
  40. package/dest/index.js +9 -0
  41. package/dest/mem_pools/attestation_pool/attestation_pool.d.ts +194 -0
  42. package/dest/mem_pools/attestation_pool/attestation_pool.d.ts.map +1 -0
  43. package/dest/mem_pools/attestation_pool/attestation_pool.js +521 -0
  44. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.d.ts +3 -0
  45. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.d.ts.map +1 -0
  46. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.js +745 -0
  47. package/dest/mem_pools/attestation_pool/index.d.ts +2 -0
  48. package/dest/mem_pools/attestation_pool/index.d.ts.map +1 -0
  49. package/dest/mem_pools/attestation_pool/index.js +1 -0
  50. package/dest/mem_pools/attestation_pool/mocks.d.ts +242 -0
  51. package/dest/mem_pools/attestation_pool/mocks.d.ts.map +1 -0
  52. package/dest/mem_pools/attestation_pool/mocks.js +33 -0
  53. package/dest/mem_pools/index.d.ts +4 -0
  54. package/dest/mem_pools/index.d.ts.map +1 -0
  55. package/dest/mem_pools/index.js +1 -0
  56. package/dest/mem_pools/instrumentation.d.ts +41 -0
  57. package/dest/mem_pools/instrumentation.d.ts.map +1 -0
  58. package/dest/mem_pools/instrumentation.js +120 -0
  59. package/dest/mem_pools/interface.d.ts +10 -0
  60. package/dest/mem_pools/interface.d.ts.map +1 -0
  61. package/dest/mem_pools/interface.js +3 -0
  62. package/dest/mem_pools/tx_pool_v2/archive/index.d.ts +2 -0
  63. package/dest/mem_pools/tx_pool_v2/archive/index.d.ts.map +1 -0
  64. package/dest/mem_pools/tx_pool_v2/archive/index.js +1 -0
  65. package/dest/mem_pools/tx_pool_v2/archive/tx_archive.d.ts +48 -0
  66. package/dest/mem_pools/tx_pool_v2/archive/tx_archive.d.ts.map +1 -0
  67. package/dest/mem_pools/tx_pool_v2/archive/tx_archive.js +112 -0
  68. package/dest/mem_pools/tx_pool_v2/deleted_pool.d.ts +104 -0
  69. package/dest/mem_pools/tx_pool_v2/deleted_pool.d.ts.map +1 -0
  70. package/dest/mem_pools/tx_pool_v2/deleted_pool.js +251 -0
  71. package/dest/mem_pools/tx_pool_v2/eviction/eviction_manager.d.ts +47 -0
  72. package/dest/mem_pools/tx_pool_v2/eviction/eviction_manager.d.ts.map +1 -0
  73. package/dest/mem_pools/tx_pool_v2/eviction/eviction_manager.js +128 -0
  74. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.d.ts +17 -0
  75. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.d.ts.map +1 -0
  76. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.js +94 -0
  77. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.d.ts +19 -0
  78. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.d.ts.map +1 -0
  79. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.js +99 -0
  80. package/dest/mem_pools/tx_pool_v2/eviction/index.d.ts +11 -0
  81. package/dest/mem_pools/tx_pool_v2/eviction/index.d.ts.map +1 -0
  82. package/dest/mem_pools/tx_pool_v2/eviction/index.js +12 -0
  83. package/dest/mem_pools/tx_pool_v2/eviction/insufficient_fee_per_gas_eviction_rule.d.ts +16 -0
  84. package/dest/mem_pools/tx_pool_v2/eviction/insufficient_fee_per_gas_eviction_rule.d.ts.map +1 -0
  85. package/dest/mem_pools/tx_pool_v2/eviction/insufficient_fee_per_gas_eviction_rule.js +64 -0
  86. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.d.ts +180 -0
  87. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.d.ts.map +1 -0
  88. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.js +25 -0
  89. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.d.ts +15 -0
  90. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.d.ts.map +1 -0
  91. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.js +64 -0
  92. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.d.ts +17 -0
  93. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.d.ts.map +1 -0
  94. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.js +92 -0
  95. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.d.ts +16 -0
  96. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.d.ts.map +1 -0
  97. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.js +79 -0
  98. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.d.ts +20 -0
  99. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.d.ts.map +1 -0
  100. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.js +75 -0
  101. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.d.ts +15 -0
  102. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.d.ts.map +1 -0
  103. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.js +19 -0
  104. package/dest/mem_pools/tx_pool_v2/index.d.ts +6 -0
  105. package/dest/mem_pools/tx_pool_v2/index.d.ts.map +1 -0
  106. package/dest/mem_pools/tx_pool_v2/index.js +5 -0
  107. package/dest/mem_pools/tx_pool_v2/instrumentation.d.ts +25 -0
  108. package/dest/mem_pools/tx_pool_v2/instrumentation.d.ts.map +1 -0
  109. package/dest/mem_pools/tx_pool_v2/instrumentation.js +67 -0
  110. package/dest/mem_pools/tx_pool_v2/interfaces.d.ts +243 -0
  111. package/dest/mem_pools/tx_pool_v2/interfaces.d.ts.map +1 -0
  112. package/dest/mem_pools/tx_pool_v2/interfaces.js +11 -0
  113. package/dest/mem_pools/tx_pool_v2/tx_metadata.d.ts +137 -0
  114. package/dest/mem_pools/tx_pool_v2/tx_metadata.d.ts.map +1 -0
  115. package/dest/mem_pools/tx_pool_v2/tx_metadata.js +223 -0
  116. package/dest/mem_pools/tx_pool_v2/tx_pool_bench_metrics.d.ts +26 -0
  117. package/dest/mem_pools/tx_pool_v2/tx_pool_bench_metrics.d.ts.map +1 -0
  118. package/dest/mem_pools/tx_pool_v2/tx_pool_bench_metrics.js +70 -0
  119. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.d.ts +122 -0
  120. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.d.ts.map +1 -0
  121. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.js +368 -0
  122. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.d.ts +75 -0
  123. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.d.ts.map +1 -0
  124. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.js +218 -0
  125. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.d.ts +122 -0
  126. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.d.ts.map +1 -0
  127. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.js +1039 -0
  128. package/dest/msg_validators/attestation_validator/attestation_validator.d.ts +17 -0
  129. package/dest/msg_validators/attestation_validator/attestation_validator.d.ts.map +1 -0
  130. package/dest/msg_validators/attestation_validator/attestation_validator.js +111 -0
  131. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.d.ts +24 -0
  132. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.d.ts.map +1 -0
  133. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.js +75 -0
  134. package/dest/msg_validators/attestation_validator/index.d.ts +3 -0
  135. package/dest/msg_validators/attestation_validator/index.d.ts.map +1 -0
  136. package/dest/msg_validators/attestation_validator/index.js +2 -0
  137. package/dest/msg_validators/index.d.ts +4 -0
  138. package/dest/msg_validators/index.d.ts.map +1 -0
  139. package/dest/msg_validators/index.js +3 -0
  140. package/dest/msg_validators/msg_seen_validator/msg_seen_validator.d.ts +10 -0
  141. package/dest/msg_validators/msg_seen_validator/msg_seen_validator.d.ts.map +1 -0
  142. package/dest/msg_validators/msg_seen_validator/msg_seen_validator.js +36 -0
  143. package/dest/msg_validators/proposal_validator/block_proposal_validator.d.ts +16 -0
  144. package/dest/msg_validators/proposal_validator/block_proposal_validator.d.ts.map +1 -0
  145. package/dest/msg_validators/proposal_validator/block_proposal_validator.js +14 -0
  146. package/dest/msg_validators/proposal_validator/checkpoint_proposal_validator.d.ts +16 -0
  147. package/dest/msg_validators/proposal_validator/checkpoint_proposal_validator.d.ts.map +1 -0
  148. package/dest/msg_validators/proposal_validator/checkpoint_proposal_validator.js +26 -0
  149. package/dest/msg_validators/proposal_validator/index.d.ts +4 -0
  150. package/dest/msg_validators/proposal_validator/index.d.ts.map +1 -0
  151. package/dest/msg_validators/proposal_validator/index.js +3 -0
  152. package/dest/msg_validators/proposal_validator/proposal_validator.d.ts +40 -0
  153. package/dest/msg_validators/proposal_validator/proposal_validator.d.ts.map +1 -0
  154. package/dest/msg_validators/proposal_validator/proposal_validator.js +186 -0
  155. package/dest/msg_validators/tx_validator/aggregate_tx_validator.d.ts +7 -0
  156. package/dest/msg_validators/tx_validator/aggregate_tx_validator.d.ts.map +1 -0
  157. package/dest/msg_validators/tx_validator/aggregate_tx_validator.js +25 -0
  158. package/dest/msg_validators/tx_validator/allowed_public_setup.d.ts +4 -0
  159. package/dest/msg_validators/tx_validator/allowed_public_setup.d.ts.map +1 -0
  160. package/dest/msg_validators/tx_validator/allowed_public_setup.js +31 -0
  161. package/dest/msg_validators/tx_validator/allowed_setup_helpers.d.ts +17 -0
  162. package/dest/msg_validators/tx_validator/allowed_setup_helpers.d.ts.map +1 -0
  163. package/dest/msg_validators/tx_validator/allowed_setup_helpers.js +24 -0
  164. package/dest/msg_validators/tx_validator/archive_cache.d.ts +14 -0
  165. package/dest/msg_validators/tx_validator/archive_cache.d.ts.map +1 -0
  166. package/dest/msg_validators/tx_validator/archive_cache.js +22 -0
  167. package/dest/msg_validators/tx_validator/block_header_validator.d.ts +25 -0
  168. package/dest/msg_validators/tx_validator/block_header_validator.d.ts.map +1 -0
  169. package/dest/msg_validators/tx_validator/block_header_validator.js +27 -0
  170. package/dest/msg_validators/tx_validator/cached_tx_validator.d.ts +15 -0
  171. package/dest/msg_validators/tx_validator/cached_tx_validator.d.ts.map +1 -0
  172. package/dest/msg_validators/tx_validator/cached_tx_validator.js +19 -0
  173. package/dest/msg_validators/tx_validator/contract_instance_validator.d.ts +9 -0
  174. package/dest/msg_validators/tx_validator/contract_instance_validator.d.ts.map +1 -0
  175. package/dest/msg_validators/tx_validator/contract_instance_validator.js +48 -0
  176. package/dest/msg_validators/tx_validator/data_validator.d.ts +9 -0
  177. package/dest/msg_validators/tx_validator/data_validator.d.ts.map +1 -0
  178. package/dest/msg_validators/tx_validator/data_validator.js +114 -0
  179. package/dest/msg_validators/tx_validator/double_spend_validator.d.ts +21 -0
  180. package/dest/msg_validators/tx_validator/double_spend_validator.d.ts.map +1 -0
  181. package/dest/msg_validators/tx_validator/double_spend_validator.js +36 -0
  182. package/dest/msg_validators/tx_validator/factory.d.ts +148 -0
  183. package/dest/msg_validators/tx_validator/factory.d.ts.map +1 -0
  184. package/dest/msg_validators/tx_validator/factory.js +302 -0
  185. package/dest/msg_validators/tx_validator/fee_payer_balance.d.ts +10 -0
  186. package/dest/msg_validators/tx_validator/fee_payer_balance.d.ts.map +1 -0
  187. package/dest/msg_validators/tx_validator/fee_payer_balance.js +24 -0
  188. package/dest/msg_validators/tx_validator/gas_limits_validator.d.ts +73 -0
  189. package/dest/msg_validators/tx_validator/gas_limits_validator.d.ts.map +1 -0
  190. package/dest/msg_validators/tx_validator/gas_limits_validator.js +107 -0
  191. package/dest/msg_validators/tx_validator/gas_validator.d.ts +65 -0
  192. package/dest/msg_validators/tx_validator/gas_validator.d.ts.map +1 -0
  193. package/dest/msg_validators/tx_validator/gas_validator.js +107 -0
  194. package/dest/msg_validators/tx_validator/index.d.ts +20 -0
  195. package/dest/msg_validators/tx_validator/index.d.ts.map +1 -0
  196. package/dest/msg_validators/tx_validator/index.js +19 -0
  197. package/dest/msg_validators/tx_validator/metadata_validator.d.ts +15 -0
  198. package/dest/msg_validators/tx_validator/metadata_validator.d.ts.map +1 -0
  199. package/dest/msg_validators/tx_validator/metadata_validator.js +63 -0
  200. package/dest/msg_validators/tx_validator/nullifier_cache.d.ts +14 -0
  201. package/dest/msg_validators/tx_validator/nullifier_cache.d.ts.map +1 -0
  202. package/dest/msg_validators/tx_validator/nullifier_cache.js +24 -0
  203. package/dest/msg_validators/tx_validator/phases_validator.d.ts +35 -0
  204. package/dest/msg_validators/tx_validator/phases_validator.d.ts.map +1 -0
  205. package/dest/msg_validators/tx_validator/phases_validator.js +141 -0
  206. package/dest/msg_validators/tx_validator/size_validator.d.ts +8 -0
  207. package/dest/msg_validators/tx_validator/size_validator.d.ts.map +1 -0
  208. package/dest/msg_validators/tx_validator/size_validator.js +23 -0
  209. package/dest/msg_validators/tx_validator/test_utils.d.ts +17 -0
  210. package/dest/msg_validators/tx_validator/test_utils.d.ts.map +1 -0
  211. package/dest/msg_validators/tx_validator/test_utils.js +22 -0
  212. package/dest/msg_validators/tx_validator/timestamp_validator.d.ts +30 -0
  213. package/dest/msg_validators/tx_validator/timestamp_validator.d.ts.map +1 -0
  214. package/dest/msg_validators/tx_validator/timestamp_validator.js +32 -0
  215. package/dest/msg_validators/tx_validator/tx_permitted_validator.d.ts +9 -0
  216. package/dest/msg_validators/tx_validator/tx_permitted_validator.d.ts.map +1 -0
  217. package/dest/msg_validators/tx_validator/tx_permitted_validator.js +24 -0
  218. package/dest/msg_validators/tx_validator/tx_proof_validator.d.ts +11 -0
  219. package/dest/msg_validators/tx_validator/tx_proof_validator.d.ts.map +1 -0
  220. package/dest/msg_validators/tx_validator/tx_proof_validator.js +28 -0
  221. package/dest/msg_validators/tx_validator/tx_validation_cache.d.ts +48 -0
  222. package/dest/msg_validators/tx_validator/tx_validation_cache.d.ts.map +1 -0
  223. package/dest/msg_validators/tx_validator/tx_validation_cache.js +68 -0
  224. package/dest/services/data_store.d.ts +27 -0
  225. package/dest/services/data_store.d.ts.map +1 -0
  226. package/dest/services/data_store.js +192 -0
  227. package/dest/services/discv5/discV5_service.d.ts +54 -0
  228. package/dest/services/discv5/discV5_service.d.ts.map +1 -0
  229. package/dest/services/discv5/discV5_service.js +337 -0
  230. package/dest/services/discv5/persisted_enr_store.d.ts +38 -0
  231. package/dest/services/discv5/persisted_enr_store.d.ts.map +1 -0
  232. package/dest/services/discv5/persisted_enr_store.js +145 -0
  233. package/dest/services/dummy_service.d.ts +150 -0
  234. package/dest/services/dummy_service.d.ts.map +1 -0
  235. package/dest/services/dummy_service.js +228 -0
  236. package/dest/services/encoding.d.ts +67 -0
  237. package/dest/services/encoding.d.ts.map +1 -0
  238. package/dest/services/encoding.js +152 -0
  239. package/dest/services/gossipsub/index.d.ts +3 -0
  240. package/dest/services/gossipsub/index.d.ts.map +1 -0
  241. package/dest/services/gossipsub/index.js +2 -0
  242. package/dest/services/gossipsub/scoring.d.ts +25 -0
  243. package/dest/services/gossipsub/scoring.d.ts.map +1 -0
  244. package/dest/services/gossipsub/scoring.js +27 -0
  245. package/dest/services/gossipsub/topic_score_params.d.ts +167 -0
  246. package/dest/services/gossipsub/topic_score_params.d.ts.map +1 -0
  247. package/dest/services/gossipsub/topic_score_params.js +336 -0
  248. package/dest/services/index.d.ts +8 -0
  249. package/dest/services/index.d.ts.map +1 -0
  250. package/dest/services/index.js +7 -0
  251. package/dest/services/libp2p/instrumentation.d.ts +25 -0
  252. package/dest/services/libp2p/instrumentation.d.ts.map +1 -0
  253. package/dest/services/libp2p/instrumentation.js +143 -0
  254. package/dest/services/libp2p/libp2p_service.d.ts +250 -0
  255. package/dest/services/libp2p/libp2p_service.d.ts.map +1 -0
  256. package/dest/services/libp2p/libp2p_service.js +1983 -0
  257. package/dest/services/peer-manager/interface.d.ts +23 -0
  258. package/dest/services/peer-manager/interface.d.ts.map +1 -0
  259. package/dest/services/peer-manager/interface.js +1 -0
  260. package/dest/services/peer-manager/metrics.d.ts +23 -0
  261. package/dest/services/peer-manager/metrics.d.ts.map +1 -0
  262. package/dest/services/peer-manager/metrics.js +71 -0
  263. package/dest/services/peer-manager/peer_manager.d.ts +202 -0
  264. package/dest/services/peer-manager/peer_manager.d.ts.map +1 -0
  265. package/dest/services/peer-manager/peer_manager.js +1015 -0
  266. package/dest/services/peer-manager/peer_scoring.d.ts +65 -0
  267. package/dest/services/peer-manager/peer_scoring.d.ts.map +1 -0
  268. package/dest/services/peer-manager/peer_scoring.js +239 -0
  269. package/dest/services/reqresp/batch-tx-requester/batch_tx_requester.d.ts +44 -0
  270. package/dest/services/reqresp/batch-tx-requester/batch_tx_requester.d.ts.map +1 -0
  271. package/dest/services/reqresp/batch-tx-requester/batch_tx_requester.js +534 -0
  272. package/dest/services/reqresp/batch-tx-requester/config.d.ts +17 -0
  273. package/dest/services/reqresp/batch-tx-requester/config.d.ts.map +1 -0
  274. package/dest/services/reqresp/batch-tx-requester/config.js +27 -0
  275. package/dest/services/reqresp/batch-tx-requester/interface.d.ts +50 -0
  276. package/dest/services/reqresp/batch-tx-requester/interface.d.ts.map +1 -0
  277. package/dest/services/reqresp/batch-tx-requester/interface.js +1 -0
  278. package/dest/services/reqresp/batch-tx-requester/missing_txs.d.ts +35 -0
  279. package/dest/services/reqresp/batch-tx-requester/missing_txs.d.ts.map +1 -0
  280. package/dest/services/reqresp/batch-tx-requester/missing_txs.js +136 -0
  281. package/dest/services/reqresp/batch-tx-requester/peer_collection.d.ts +62 -0
  282. package/dest/services/reqresp/batch-tx-requester/peer_collection.d.ts.map +1 -0
  283. package/dest/services/reqresp/batch-tx-requester/peer_collection.js +176 -0
  284. package/dest/services/reqresp/batch-tx-requester/tx_validator.d.ts +11 -0
  285. package/dest/services/reqresp/batch-tx-requester/tx_validator.d.ts.map +1 -0
  286. package/dest/services/reqresp/batch-tx-requester/tx_validator.js +7 -0
  287. package/dest/services/reqresp/config.d.ts +30 -0
  288. package/dest/services/reqresp/config.d.ts.map +1 -0
  289. package/dest/services/reqresp/config.js +45 -0
  290. package/dest/services/reqresp/connection-sampler/connection_sampler.d.ts +76 -0
  291. package/dest/services/reqresp/connection-sampler/connection_sampler.d.ts.map +1 -0
  292. package/dest/services/reqresp/connection-sampler/connection_sampler.js +251 -0
  293. package/dest/services/reqresp/constants.d.ts +12 -0
  294. package/dest/services/reqresp/constants.d.ts.map +1 -0
  295. package/dest/services/reqresp/constants.js +7 -0
  296. package/dest/services/reqresp/index.d.ts +7 -0
  297. package/dest/services/reqresp/index.d.ts.map +1 -0
  298. package/dest/services/reqresp/index.js +5 -0
  299. package/dest/services/reqresp/interface.d.ts +174 -0
  300. package/dest/services/reqresp/interface.d.ts.map +1 -0
  301. package/dest/services/reqresp/interface.js +107 -0
  302. package/dest/services/reqresp/metrics.d.ts +16 -0
  303. package/dest/services/reqresp/metrics.d.ts.map +1 -0
  304. package/dest/services/reqresp/metrics.js +50 -0
  305. package/dest/services/reqresp/protocols/auth.d.ts +43 -0
  306. package/dest/services/reqresp/protocols/auth.d.ts.map +1 -0
  307. package/dest/services/reqresp/protocols/auth.js +71 -0
  308. package/dest/services/reqresp/protocols/block_txs/bitvector.d.ts +35 -0
  309. package/dest/services/reqresp/protocols/block_txs/bitvector.d.ts.map +1 -0
  310. package/dest/services/reqresp/protocols/block_txs/bitvector.js +88 -0
  311. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.d.ts +13 -0
  312. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.d.ts.map +1 -0
  313. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.js +60 -0
  314. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.d.ts +75 -0
  315. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.d.ts.map +1 -0
  316. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.js +139 -0
  317. package/dest/services/reqresp/protocols/block_txs/index.d.ts +4 -0
  318. package/dest/services/reqresp/protocols/block_txs/index.d.ts.map +1 -0
  319. package/dest/services/reqresp/protocols/block_txs/index.js +3 -0
  320. package/dest/services/reqresp/protocols/goodbye.d.ts +49 -0
  321. package/dest/services/reqresp/protocols/goodbye.d.ts.map +1 -0
  322. package/dest/services/reqresp/protocols/goodbye.js +87 -0
  323. package/dest/services/reqresp/protocols/index.d.ts +10 -0
  324. package/dest/services/reqresp/protocols/index.d.ts.map +1 -0
  325. package/dest/services/reqresp/protocols/index.js +8 -0
  326. package/dest/services/reqresp/protocols/ping.d.ts +7 -0
  327. package/dest/services/reqresp/protocols/ping.d.ts.map +1 -0
  328. package/dest/services/reqresp/protocols/ping.js +7 -0
  329. package/dest/services/reqresp/protocols/status.d.ts +42 -0
  330. package/dest/services/reqresp/protocols/status.d.ts.map +1 -0
  331. package/dest/services/reqresp/protocols/status.js +78 -0
  332. package/dest/services/reqresp/protocols/tx.d.ts +29 -0
  333. package/dest/services/reqresp/protocols/tx.d.ts.map +1 -0
  334. package/dest/services/reqresp/protocols/tx.js +66 -0
  335. package/dest/services/reqresp/rate-limiter/index.d.ts +2 -0
  336. package/dest/services/reqresp/rate-limiter/index.d.ts.map +1 -0
  337. package/dest/services/reqresp/rate-limiter/index.js +1 -0
  338. package/dest/services/reqresp/rate-limiter/rate_limiter.d.ts +105 -0
  339. package/dest/services/reqresp/rate-limiter/rate_limiter.d.ts.map +1 -0
  340. package/dest/services/reqresp/rate-limiter/rate_limiter.js +194 -0
  341. package/dest/services/reqresp/rate-limiter/rate_limits.d.ts +3 -0
  342. package/dest/services/reqresp/rate-limiter/rate_limits.d.ts.map +1 -0
  343. package/dest/services/reqresp/rate-limiter/rate_limits.js +64 -0
  344. package/dest/services/reqresp/reqresp.d.ts +107 -0
  345. package/dest/services/reqresp/reqresp.d.ts.map +1 -0
  346. package/dest/services/reqresp/reqresp.js +887 -0
  347. package/dest/services/reqresp/status.d.ts +37 -0
  348. package/dest/services/reqresp/status.d.ts.map +1 -0
  349. package/dest/services/reqresp/status.js +58 -0
  350. package/dest/services/service.d.ts +168 -0
  351. package/dest/services/service.d.ts.map +1 -0
  352. package/dest/services/service.js +5 -0
  353. package/dest/services/tx_collection/config.d.ts +25 -0
  354. package/dest/services/tx_collection/config.d.ts.map +1 -0
  355. package/dest/services/tx_collection/config.js +59 -0
  356. package/dest/services/tx_collection/file_store_tx_collection.d.ts +37 -0
  357. package/dest/services/tx_collection/file_store_tx_collection.d.ts.map +1 -0
  358. package/dest/services/tx_collection/file_store_tx_collection.js +127 -0
  359. package/dest/services/tx_collection/file_store_tx_source.d.ts +38 -0
  360. package/dest/services/tx_collection/file_store_tx_source.d.ts.map +1 -0
  361. package/dest/services/tx_collection/file_store_tx_source.js +100 -0
  362. package/dest/services/tx_collection/index.d.ts +4 -0
  363. package/dest/services/tx_collection/index.d.ts.map +1 -0
  364. package/dest/services/tx_collection/index.js +3 -0
  365. package/dest/services/tx_collection/instrumentation.d.ts +10 -0
  366. package/dest/services/tx_collection/instrumentation.d.ts.map +1 -0
  367. package/dest/services/tx_collection/instrumentation.js +30 -0
  368. package/dest/services/tx_collection/request_tracker.d.ts +53 -0
  369. package/dest/services/tx_collection/request_tracker.d.ts.map +1 -0
  370. package/dest/services/tx_collection/request_tracker.js +84 -0
  371. package/dest/services/tx_collection/tx_collection.d.ts +104 -0
  372. package/dest/services/tx_collection/tx_collection.d.ts.map +1 -0
  373. package/dest/services/tx_collection/tx_collection.js +356 -0
  374. package/dest/services/tx_collection/tx_collection_sink.d.ts +40 -0
  375. package/dest/services/tx_collection/tx_collection_sink.d.ts.map +1 -0
  376. package/dest/services/tx_collection/tx_collection_sink.js +108 -0
  377. package/dest/services/tx_collection/tx_source.d.ts +24 -0
  378. package/dest/services/tx_collection/tx_source.d.ts.map +1 -0
  379. package/dest/services/tx_collection/tx_source.js +56 -0
  380. package/dest/services/tx_file_store/config.d.ts +16 -0
  381. package/dest/services/tx_file_store/config.d.ts.map +1 -0
  382. package/dest/services/tx_file_store/config.js +22 -0
  383. package/dest/services/tx_file_store/index.d.ts +4 -0
  384. package/dest/services/tx_file_store/index.d.ts.map +1 -0
  385. package/dest/services/tx_file_store/index.js +3 -0
  386. package/dest/services/tx_file_store/instrumentation.d.ts +15 -0
  387. package/dest/services/tx_file_store/instrumentation.d.ts.map +1 -0
  388. package/dest/services/tx_file_store/instrumentation.js +29 -0
  389. package/dest/services/tx_file_store/tx_file_store.d.ts +46 -0
  390. package/dest/services/tx_file_store/tx_file_store.d.ts.map +1 -0
  391. package/dest/services/tx_file_store/tx_file_store.js +142 -0
  392. package/dest/services/tx_provider.d.ts +53 -0
  393. package/dest/services/tx_provider.d.ts.map +1 -0
  394. package/dest/services/tx_provider.js +223 -0
  395. package/dest/services/tx_provider_instrumentation.d.ts +16 -0
  396. package/dest/services/tx_provider_instrumentation.d.ts.map +1 -0
  397. package/dest/services/tx_provider_instrumentation.js +34 -0
  398. package/dest/test-helpers/generate-peer-id-private-keys.d.ts +7 -0
  399. package/dest/test-helpers/generate-peer-id-private-keys.d.ts.map +1 -0
  400. package/dest/test-helpers/generate-peer-id-private-keys.js +13 -0
  401. package/dest/test-helpers/get-ports.d.ts +7 -0
  402. package/dest/test-helpers/get-ports.d.ts.map +1 -0
  403. package/dest/test-helpers/get-ports.js +8 -0
  404. package/dest/test-helpers/index.d.ts +9 -0
  405. package/dest/test-helpers/index.d.ts.map +1 -0
  406. package/dest/test-helpers/index.js +8 -0
  407. package/dest/test-helpers/make-enrs.d.ts +16 -0
  408. package/dest/test-helpers/make-enrs.d.ts.map +1 -0
  409. package/dest/test-helpers/make-enrs.js +31 -0
  410. package/dest/test-helpers/make-test-p2p-clients.d.ts +63 -0
  411. package/dest/test-helpers/make-test-p2p-clients.d.ts.map +1 -0
  412. package/dest/test-helpers/make-test-p2p-clients.js +140 -0
  413. package/dest/test-helpers/mock-pubsub.d.ts +109 -0
  414. package/dest/test-helpers/mock-pubsub.d.ts.map +1 -0
  415. package/dest/test-helpers/mock-pubsub.js +244 -0
  416. package/dest/test-helpers/mock-tx-helpers.d.ts +12 -0
  417. package/dest/test-helpers/mock-tx-helpers.d.ts.map +1 -0
  418. package/dest/test-helpers/mock-tx-helpers.js +19 -0
  419. package/dest/test-helpers/reqresp-nodes.d.ts +68 -0
  420. package/dest/test-helpers/reqresp-nodes.d.ts.map +1 -0
  421. package/dest/test-helpers/reqresp-nodes.js +240 -0
  422. package/dest/test-helpers/test_tx_provider.d.ts +42 -0
  423. package/dest/test-helpers/test_tx_provider.d.ts.map +1 -0
  424. package/dest/test-helpers/test_tx_provider.js +44 -0
  425. package/dest/test-helpers/testbench-utils.d.ts +164 -0
  426. package/dest/test-helpers/testbench-utils.d.ts.map +1 -0
  427. package/dest/test-helpers/testbench-utils.js +401 -0
  428. package/dest/testbench/p2p_client_testbench_worker.d.ts +26 -0
  429. package/dest/testbench/p2p_client_testbench_worker.d.ts.map +1 -0
  430. package/dest/testbench/p2p_client_testbench_worker.js +364 -0
  431. package/dest/testbench/parse_log_file.d.ts +2 -0
  432. package/dest/testbench/parse_log_file.d.ts.map +1 -0
  433. package/dest/testbench/parse_log_file.js +131 -0
  434. package/dest/testbench/testbench.d.ts +2 -0
  435. package/dest/testbench/testbench.d.ts.map +1 -0
  436. package/dest/testbench/testbench.js +62 -0
  437. package/dest/testbench/worker_client_manager.d.ts +102 -0
  438. package/dest/testbench/worker_client_manager.d.ts.map +1 -0
  439. package/dest/testbench/worker_client_manager.js +492 -0
  440. package/dest/types/index.d.ts +34 -0
  441. package/dest/types/index.d.ts.map +1 -0
  442. package/dest/types/index.js +30 -0
  443. package/dest/util.d.ts +66 -0
  444. package/dest/util.d.ts.map +1 -0
  445. package/dest/util.js +167 -0
  446. package/dest/versioning.d.ts +9 -0
  447. package/dest/versioning.d.ts.map +1 -0
  448. package/dest/versioning.js +17 -0
  449. package/package.json +131 -0
  450. package/src/bootstrap/bootstrap.ts +178 -0
  451. package/src/client/factory.ts +282 -0
  452. package/src/client/index.ts +3 -0
  453. package/src/client/interface.ts +264 -0
  454. package/src/client/p2p_client.ts +846 -0
  455. package/src/client/test/p2p_client.batch_tx_requester.bench.README.md +197 -0
  456. package/src/config.ts +787 -0
  457. package/src/enr/generate-enr.ts +71 -0
  458. package/src/enr/index.ts +1 -0
  459. package/src/errors/attestation-pool.error.ts +13 -0
  460. package/src/errors/p2p-service.error.ts +11 -0
  461. package/src/errors/reqresp.error.ts +29 -0
  462. package/src/errors/tx-pool.error.ts +12 -0
  463. package/src/index.ts +11 -0
  464. package/src/mem_pools/attestation_pool/attestation_pool.ts +648 -0
  465. package/src/mem_pools/attestation_pool/attestation_pool_test_suite.ts +896 -0
  466. package/src/mem_pools/attestation_pool/index.ts +9 -0
  467. package/src/mem_pools/attestation_pool/mocks.ts +56 -0
  468. package/src/mem_pools/index.ts +3 -0
  469. package/src/mem_pools/instrumentation.ts +160 -0
  470. package/src/mem_pools/interface.ts +10 -0
  471. package/src/mem_pools/tx_pool_v2/README.md +283 -0
  472. package/src/mem_pools/tx_pool_v2/archive/index.ts +1 -0
  473. package/src/mem_pools/tx_pool_v2/archive/tx_archive.ts +130 -0
  474. package/src/mem_pools/tx_pool_v2/deleted_pool.ts +321 -0
  475. package/src/mem_pools/tx_pool_v2/eviction/eviction_manager.ts +160 -0
  476. package/src/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.ts +120 -0
  477. package/src/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.ts +126 -0
  478. package/src/mem_pools/tx_pool_v2/eviction/index.ts +28 -0
  479. package/src/mem_pools/tx_pool_v2/eviction/insufficient_fee_per_gas_eviction_rule.ts +67 -0
  480. package/src/mem_pools/tx_pool_v2/eviction/interfaces.ts +219 -0
  481. package/src/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.ts +72 -0
  482. package/src/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.ts +99 -0
  483. package/src/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.ts +90 -0
  484. package/src/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.ts +99 -0
  485. package/src/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.ts +32 -0
  486. package/src/mem_pools/tx_pool_v2/index.ts +12 -0
  487. package/src/mem_pools/tx_pool_v2/instrumentation.ts +96 -0
  488. package/src/mem_pools/tx_pool_v2/interfaces.ts +274 -0
  489. package/src/mem_pools/tx_pool_v2/tx_metadata.ts +349 -0
  490. package/src/mem_pools/tx_pool_v2/tx_pool_bench_metrics.ts +77 -0
  491. package/src/mem_pools/tx_pool_v2/tx_pool_indices.ts +465 -0
  492. package/src/mem_pools/tx_pool_v2/tx_pool_v2.ts +300 -0
  493. package/src/mem_pools/tx_pool_v2/tx_pool_v2_impl.ts +1242 -0
  494. package/src/msg_validators/attestation_validator/README.md +49 -0
  495. package/src/msg_validators/attestation_validator/attestation_validator.ts +116 -0
  496. package/src/msg_validators/attestation_validator/fisherman_attestation_validator.ts +107 -0
  497. package/src/msg_validators/attestation_validator/index.ts +2 -0
  498. package/src/msg_validators/index.ts +3 -0
  499. package/src/msg_validators/msg_seen_validator/msg_seen_validator.ts +36 -0
  500. package/src/msg_validators/proposal_validator/README.md +123 -0
  501. package/src/msg_validators/proposal_validator/block_proposal_validator.ts +37 -0
  502. package/src/msg_validators/proposal_validator/checkpoint_proposal_validator.ts +49 -0
  503. package/src/msg_validators/proposal_validator/index.ts +3 -0
  504. package/src/msg_validators/proposal_validator/proposal_validator.ts +198 -0
  505. package/src/msg_validators/tx_validator/README.md +137 -0
  506. package/src/msg_validators/tx_validator/aggregate_tx_validator.ts +24 -0
  507. package/src/msg_validators/tx_validator/allowed_public_setup.ts +30 -0
  508. package/src/msg_validators/tx_validator/allowed_setup_helpers.ts +31 -0
  509. package/src/msg_validators/tx_validator/archive_cache.ts +28 -0
  510. package/src/msg_validators/tx_validator/block_header_validator.ts +38 -0
  511. package/src/msg_validators/tx_validator/cached_tx_validator.ts +31 -0
  512. package/src/msg_validators/tx_validator/contract_instance_validator.ts +56 -0
  513. package/src/msg_validators/tx_validator/data_validator.ts +173 -0
  514. package/src/msg_validators/tx_validator/double_spend_validator.ts +46 -0
  515. package/src/msg_validators/tx_validator/factory.ts +490 -0
  516. package/src/msg_validators/tx_validator/fee_payer_balance.ts +44 -0
  517. package/src/msg_validators/tx_validator/gas_limits_validator.ts +148 -0
  518. package/src/msg_validators/tx_validator/gas_validator.ts +149 -0
  519. package/src/msg_validators/tx_validator/index.ts +19 -0
  520. package/src/msg_validators/tx_validator/metadata_validator.ts +104 -0
  521. package/src/msg_validators/tx_validator/nullifier_cache.ts +30 -0
  522. package/src/msg_validators/tx_validator/phases_validator.ts +173 -0
  523. package/src/msg_validators/tx_validator/size_validator.ts +22 -0
  524. package/src/msg_validators/tx_validator/test_utils.ts +43 -0
  525. package/src/msg_validators/tx_validator/timestamp_validator.ts +61 -0
  526. package/src/msg_validators/tx_validator/tx_permitted_validator.ts +22 -0
  527. package/src/msg_validators/tx_validator/tx_proof_validator.ts +26 -0
  528. package/src/msg_validators/tx_validator/tx_validation_cache.ts +100 -0
  529. package/src/services/data_store.ts +229 -0
  530. package/src/services/discv5/discV5_service.ts +413 -0
  531. package/src/services/discv5/persisted_enr_store.ts +157 -0
  532. package/src/services/dummy_service.ts +320 -0
  533. package/src/services/encoding.ts +170 -0
  534. package/src/services/gossipsub/README.md +663 -0
  535. package/src/services/gossipsub/index.ts +2 -0
  536. package/src/services/gossipsub/scoring.ts +37 -0
  537. package/src/services/gossipsub/topic_score_params.ts +477 -0
  538. package/src/services/index.ts +7 -0
  539. package/src/services/libp2p/instrumentation.ts +147 -0
  540. package/src/services/libp2p/libp2p_service.ts +1972 -0
  541. package/src/services/peer-manager/interface.ts +28 -0
  542. package/src/services/peer-manager/metrics.ts +90 -0
  543. package/src/services/peer-manager/peer_manager.ts +1221 -0
  544. package/src/services/peer-manager/peer_scoring.ts +265 -0
  545. package/src/services/reqresp/README.md +194 -0
  546. package/src/services/reqresp/batch-tx-requester/README.md +344 -0
  547. package/src/services/reqresp/batch-tx-requester/batch_tx_requester.ts +659 -0
  548. package/src/services/reqresp/batch-tx-requester/config.ts +40 -0
  549. package/src/services/reqresp/batch-tx-requester/interface.ts +60 -0
  550. package/src/services/reqresp/batch-tx-requester/missing_txs.ts +167 -0
  551. package/src/services/reqresp/batch-tx-requester/peer_collection.ts +248 -0
  552. package/src/services/reqresp/batch-tx-requester/tx_validator.ts +24 -0
  553. package/src/services/reqresp/config.ts +69 -0
  554. package/src/services/reqresp/connection-sampler/connection_sampler.ts +287 -0
  555. package/src/services/reqresp/constants.ts +14 -0
  556. package/src/services/reqresp/index.ts +6 -0
  557. package/src/services/reqresp/interface.ts +241 -0
  558. package/src/services/reqresp/metrics.ts +68 -0
  559. package/src/services/reqresp/protocols/auth.ts +83 -0
  560. package/src/services/reqresp/protocols/block_txs/bitvector.ts +107 -0
  561. package/src/services/reqresp/protocols/block_txs/block_txs_handler.ts +79 -0
  562. package/src/services/reqresp/protocols/block_txs/block_txs_reqresp.ts +170 -0
  563. package/src/services/reqresp/protocols/block_txs/index.ts +3 -0
  564. package/src/services/reqresp/protocols/goodbye.ts +102 -0
  565. package/src/services/reqresp/protocols/index.ts +9 -0
  566. package/src/services/reqresp/protocols/ping.ts +8 -0
  567. package/src/services/reqresp/protocols/status.ts +123 -0
  568. package/src/services/reqresp/protocols/tx.ts +76 -0
  569. package/src/services/reqresp/rate-limiter/index.ts +1 -0
  570. package/src/services/reqresp/rate-limiter/rate_limiter.ts +240 -0
  571. package/src/services/reqresp/rate-limiter/rate_limits.ts +65 -0
  572. package/src/services/reqresp/reqresp.ts +675 -0
  573. package/src/services/reqresp/status.ts +68 -0
  574. package/src/services/service.ts +219 -0
  575. package/src/services/tx_collection/config.ts +89 -0
  576. package/src/services/tx_collection/file_store_tx_collection.ts +153 -0
  577. package/src/services/tx_collection/file_store_tx_source.ts +129 -0
  578. package/src/services/tx_collection/index.ts +3 -0
  579. package/src/services/tx_collection/instrumentation.ts +35 -0
  580. package/src/services/tx_collection/request_tracker.ts +127 -0
  581. package/src/services/tx_collection/tx_collection.ts +467 -0
  582. package/src/services/tx_collection/tx_collection_sink.ts +124 -0
  583. package/src/services/tx_collection/tx_source.ts +61 -0
  584. package/src/services/tx_file_store/config.ts +37 -0
  585. package/src/services/tx_file_store/index.ts +3 -0
  586. package/src/services/tx_file_store/instrumentation.ts +42 -0
  587. package/src/services/tx_file_store/tx_file_store.ts +163 -0
  588. package/src/services/tx_provider.ts +237 -0
  589. package/src/services/tx_provider_instrumentation.ts +54 -0
  590. package/src/test-helpers/generate-peer-id-private-keys.ts +15 -0
  591. package/src/test-helpers/get-ports.ts +8 -0
  592. package/src/test-helpers/index.ts +8 -0
  593. package/src/test-helpers/make-enrs.ts +42 -0
  594. package/src/test-helpers/make-test-p2p-clients.ts +213 -0
  595. package/src/test-helpers/mock-pubsub.ts +325 -0
  596. package/src/test-helpers/mock-tx-helpers.ts +24 -0
  597. package/src/test-helpers/reqresp-nodes.ts +327 -0
  598. package/src/test-helpers/test_tx_provider.ts +68 -0
  599. package/src/test-helpers/testbench-utils.ts +465 -0
  600. package/src/testbench/README.md +20 -0
  601. package/src/testbench/p2p_client_testbench_worker.ts +553 -0
  602. package/src/testbench/parse_log_file.ts +174 -0
  603. package/src/testbench/testbench.ts +66 -0
  604. package/src/testbench/worker_client_manager.ts +621 -0
  605. package/src/types/index.ts +38 -0
  606. package/src/util.ts +230 -0
  607. package/src/versioning.ts +26 -0
@@ -0,0 +1,1972 @@
1
+ import type { EpochCacheInterface } from '@aztec-labs/epoch-cache';
2
+ import { BlockNumber, type SlotNumber } from '@aztec-labs/foundation/branded-types';
3
+ import { compactArray, maxBy, merge } from '@aztec-labs/foundation/collection';
4
+ import { type Logger, createLibp2pComponentLogger, createLogger } from '@aztec-labs/foundation/log';
5
+ import { RunningPromise } from '@aztec-labs/foundation/running-promise';
6
+ import { Timer } from '@aztec-labs/foundation/timer';
7
+ import type { AztecAsyncKVStore } from '@aztec-labs/kv-store';
8
+ import { protocolContractsHash } from '@aztec-labs/protocol-contracts';
9
+ import type { EthAddress, L2BlockSource } from '@aztec-labs/stdlib/block';
10
+ import { DEFAULT_MAX_BLOCKS_PER_CHECKPOINT } from '@aztec-labs/stdlib/config';
11
+ import type { ContractDataSource } from '@aztec-labs/stdlib/contract';
12
+ import { type BlockMinFeesProvider, GasFees, getNetworkTxGasLimits } from '@aztec-labs/stdlib/gas';
13
+ import type {
14
+ ClientProtocolCircuitVerifier,
15
+ P2PConnectivity,
16
+ PeerInfo,
17
+ WorldStateSynchronizer,
18
+ } from '@aztec-labs/stdlib/interfaces/server';
19
+ import {
20
+ BlockProposal,
21
+ CheckpointAttestation,
22
+ CheckpointProposal,
23
+ type Gossipable,
24
+ P2PMessage,
25
+ PeerErrorSeverity,
26
+ PeerErrorSeverityByHarshness,
27
+ TopicType,
28
+ ValidatedBlockProposal,
29
+ ValidatedCheckpointProposalCore,
30
+ createTopicString,
31
+ getTopicsForConfig,
32
+ metricsTopicStrToLabels,
33
+ } from '@aztec-labs/stdlib/p2p';
34
+ import { ConsensusTimetable, getDefaultCheckpointProposalSyncGrace } from '@aztec-labs/stdlib/timetable';
35
+ import { MerkleTreeId } from '@aztec-labs/stdlib/trees';
36
+ import { Tx, type TxValidationResult } from '@aztec-labs/stdlib/tx';
37
+ import type { UInt64 } from '@aztec-labs/stdlib/types';
38
+ import { InvalidBlockProposalTxsError } from '@aztec-labs/stdlib/validators';
39
+ import { compressComponentVersions } from '@aztec-labs/stdlib/versioning';
40
+ import {
41
+ Attributes,
42
+ OtelMetricsAdapter,
43
+ SpanStatusCode,
44
+ type TelemetryClient,
45
+ WithTracer,
46
+ trackSpan,
47
+ } from '@aztec-labs/telemetry-client';
48
+ import {
49
+ type GossipSub,
50
+ type GossipSubComponents,
51
+ type GossipsubMessage,
52
+ gossipsub,
53
+ } from '@chainsafe/libp2p-gossipsub';
54
+ import { createPeerScoreParams } from '@chainsafe/libp2p-gossipsub/score';
55
+ import { SignaturePolicy } from '@chainsafe/libp2p-gossipsub/types';
56
+ import { noise } from '@chainsafe/libp2p-noise';
57
+ import { yamux } from '@chainsafe/libp2p-yamux';
58
+ import { bootstrap } from '@libp2p/bootstrap';
59
+ import { identify } from '@libp2p/identify';
60
+ import { type Message, type MultiaddrConnection, type PeerId, TopicValidatorResult } from '@libp2p/interface';
61
+ import type { AddressManager, ConnectionManager } from '@libp2p/interface-internal';
62
+ import { mplex } from '@libp2p/mplex';
63
+ import { tcp } from '@libp2p/tcp';
64
+ import { multiaddr } from '@multiformats/multiaddr';
65
+ import { ENR } from '@nethermindeth/enr';
66
+ import { createLibp2p } from 'libp2p';
67
+
68
+ import type { P2PConfig } from '../../config.js';
69
+ import { CheckpointProposalReceivedCallbackNotRegisteredError } from '../../errors/p2p-service.error.js';
70
+ import type { MemPools } from '../../mem_pools/interface.js';
71
+ import {
72
+ BlockProposalValidator,
73
+ CheckpointAttestationValidator,
74
+ CheckpointProposalValidator,
75
+ DoubleSpendTxValidator,
76
+ FishermanAttestationValidator,
77
+ getDefaultAllowedSetupFunctions,
78
+ } from '../../msg_validators/index.js';
79
+ import { MessageSeenValidator } from '../../msg_validators/msg_seen_validator/msg_seen_validator.js';
80
+ import {
81
+ type TransactionValidator,
82
+ createFirstStageTxValidationsForGossipedTransactions,
83
+ createSecondStageTxValidationsForGossipedTransactions,
84
+ createTxValidatorForBlockProposalReceivedTxs,
85
+ } from '../../msg_validators/tx_validator/factory.js';
86
+ import { TxValidationCache } from '../../msg_validators/tx_validator/tx_validation_cache.js';
87
+ import { GossipSubEvent } from '../../types/index.js';
88
+ import { type PubSubLibp2p, convertToMultiaddr } from '../../util.js';
89
+ import { getVersions } from '../../versioning.js';
90
+ import { AztecDatastore } from '../data_store.js';
91
+ import { DiscV5Service } from '../discv5/discV5_service.js';
92
+ import { SnappyTransform, getMsgIdFn, msgIdToStrFn } from '../encoding.js';
93
+ import { APP_SPECIFIC_WEIGHT, gossipScoreThresholds } from '../gossipsub/scoring.js';
94
+ import { createAllTopicScoreParams } from '../gossipsub/topic_score_params.js';
95
+ import type { PeerManagerInterface } from '../peer-manager/interface.js';
96
+ import { PeerManager } from '../peer-manager/peer_manager.js';
97
+ import { PeerScoring } from '../peer-manager/peer_scoring.js';
98
+ import type { BatchTxRequesterLibP2PService } from '../reqresp/batch-tx-requester/interface.js';
99
+ import { type P2PReqRespConfig, YAMUX_MAX_MESSAGE_SIZE_BYTES } from '../reqresp/config.js';
100
+ import {
101
+ AuthRequest,
102
+ BlockTxsRequest,
103
+ BlockTxsResponse,
104
+ type ReqRespInterface,
105
+ type ReqRespResponse,
106
+ ReqRespSubProtocol,
107
+ type ReqRespSubProtocolHandler,
108
+ type ReqRespSubProtocolHandlers,
109
+ StatusMessage,
110
+ ValidationError,
111
+ pingHandler,
112
+ reqGoodbyeHandler,
113
+ reqRespBlockTxsHandler,
114
+ reqRespStatusHandler,
115
+ reqRespTxHandler,
116
+ } from '../reqresp/index.js';
117
+ import { ReqResp } from '../reqresp/reqresp.js';
118
+ import type {
119
+ P2PBlockReceivedCallback,
120
+ P2PCheckpointAttestationCallback,
121
+ P2PCheckpointReceivedCallback,
122
+ P2PDuplicateAttestationCallback,
123
+ P2POversizedProposalCallback,
124
+ P2PService,
125
+ PeerDiscoveryService,
126
+ } from '../service.js';
127
+ import { P2PInstrumentation } from './instrumentation.js';
128
+
129
+ /**
130
+ * Builds the {@link ConsensusTimetable} shared by the gossip validators for proposal/attestation receive-window
131
+ * bounds. Derived purely from protocol slot-timing constants plus the block sub-slot duration and the consensus
132
+ * materialization grace, so every node agrees on these bounds without depending on proposer operational budgets.
133
+ */
134
+ function buildConsensusTimetable(
135
+ config: P2PConfig,
136
+ l1Constants: ReturnType<EpochCacheInterface['getL1Constants']>,
137
+ ): ConsensusTimetable {
138
+ const blockDuration = config.blockDurationMs / 1000;
139
+ return new ConsensusTimetable({
140
+ l1Constants,
141
+ blockDuration,
142
+ checkpointProposalSyncGrace:
143
+ config.checkpointProposalSyncGraceSeconds ?? getDefaultCheckpointProposalSyncGrace(blockDuration),
144
+ });
145
+ }
146
+
147
+ interface ValidationResult {
148
+ name: string;
149
+ isValid: TxValidationResult;
150
+ severity: PeerErrorSeverity;
151
+ }
152
+
153
+ type ValidationOutcome = { allPassed: true } | { allPassed: false; failure: ValidationResult };
154
+
155
+ // REFACTOR: Unify with the type above
156
+ type ReceivedMessageValidationResult<T, M = undefined> =
157
+ | { obj: T; result: Exclude<TopicValidatorResult, TopicValidatorResult.Reject>; metadata?: M }
158
+ | { obj?: T; result: TopicValidatorResult.Reject; metadata?: M; severity: PeerErrorSeverity };
159
+
160
+ /**
161
+ * Lib P2P implementation of the P2PService interface.
162
+ */
163
+ export class LibP2PService extends WithTracer implements P2PService {
164
+ private discoveryRunningPromise?: RunningPromise;
165
+ private msgIdSeenValidators: Record<TopicType, MessageSeenValidator> = {} as Record<TopicType, MessageSeenValidator>;
166
+
167
+ // Message validators
168
+ private blockProposalValidator: BlockProposalValidator;
169
+ private checkpointProposalValidator: CheckpointProposalValidator;
170
+ private checkpointAttestationValidator: CheckpointAttestationValidator;
171
+
172
+ private protocolVersion = '';
173
+ private topicStrings: Record<TopicType, string> = {} as Record<TopicType, string>;
174
+
175
+ /** Callback invoked when a duplicate proposal is detected (triggers slashing). */
176
+ private duplicateProposalCallback?: (info: {
177
+ slot: SlotNumber;
178
+ proposer: EthAddress;
179
+ type: 'checkpoint' | 'block';
180
+ }) => void;
181
+
182
+ /** Callback invoked when an oversized block proposal is stored as slashing evidence (triggers slashing). */
183
+ private oversizedProposalCallback?: P2POversizedProposalCallback;
184
+
185
+ /** Callback invoked when a duplicate attestation is detected (triggers slashing). */
186
+ private duplicateAttestationCallback?: P2PDuplicateAttestationCallback;
187
+
188
+ /** Callback invoked when a valid checkpoint attestation is accepted into the pool. */
189
+ private checkpointAttestationCallback?: P2PCheckpointAttestationCallback;
190
+
191
+ /**
192
+ * Callback for when a block is received from a peer.
193
+ * @param block - The block received from the peer.
194
+ * @returns The attestation for the block, if any.
195
+ */
196
+ private blockReceivedCallback: P2PBlockReceivedCallback;
197
+
198
+ /**
199
+ * Callback for when a checkpoint proposal is received from a peer.
200
+ * @param checkpoint - The checkpoint proposal received from the peer.
201
+ * @returns The attestations for the checkpoint, if any.
202
+ */
203
+ private allNodesCheckpointReceivedCallback: P2PCheckpointReceivedCallback;
204
+ /**
205
+ * Callback for when a checkpoint proposal is received - specifically for validators - from a peer.
206
+ * @param checkpoint - The checkpoint proposal received from the peer.
207
+ * @returns The attestations for the checkpoint, if any.
208
+ */
209
+ private validatorCheckpointReceivedCallback: P2PCheckpointReceivedCallback;
210
+
211
+ private gossipSubEventHandler: (e: CustomEvent<GossipsubMessage>) => void;
212
+
213
+ private ipChangedHandler?: (ip: string) => void;
214
+ private discoveredP2pIp?: string;
215
+
216
+ private instrumentation: P2PInstrumentation;
217
+
218
+ private telemetry: TelemetryClient;
219
+
220
+ protected logger: Logger;
221
+
222
+ constructor(
223
+ private config: P2PConfig,
224
+ protected node: PubSubLibp2p,
225
+ private peerDiscoveryService: PeerDiscoveryService,
226
+ private reqresp: ReqRespInterface,
227
+ protected peerManager: PeerManagerInterface,
228
+ protected mempools: MemPools,
229
+ protected archiver: L2BlockSource & ContractDataSource,
230
+ private epochCache: EpochCacheInterface,
231
+ private proofVerifier: ClientProtocolCircuitVerifier,
232
+ private worldStateSynchronizer: WorldStateSynchronizer,
233
+ private blockMinFeesProvider: BlockMinFeesProvider,
234
+ telemetry: TelemetryClient,
235
+ logger: Logger = createLogger('p2p:libp2p_service'),
236
+ private txValidationCache?: TxValidationCache,
237
+ ) {
238
+ super(telemetry, 'LibP2PService');
239
+ this.telemetry = telemetry;
240
+
241
+ // Create child logger with fisherman prefix if in fisherman mode
242
+ this.logger = config.fishermanMode ? logger.createChild('[FISHERMAN]') : logger;
243
+
244
+ this.instrumentation = new P2PInstrumentation(telemetry, 'LibP2PService');
245
+
246
+ this.msgIdSeenValidators[TopicType.tx] = new MessageSeenValidator(config.seenMessageCacheSize);
247
+ this.msgIdSeenValidators[TopicType.block_proposal] = new MessageSeenValidator(config.seenMessageCacheSize);
248
+ this.msgIdSeenValidators[TopicType.checkpoint_proposal] = new MessageSeenValidator(config.seenMessageCacheSize);
249
+ this.msgIdSeenValidators[TopicType.checkpoint_attestation] = new MessageSeenValidator(config.seenMessageCacheSize);
250
+
251
+ const versions = getVersions(config);
252
+ this.protocolVersion = compressComponentVersions(versions);
253
+ logger.info(`Started libp2p service with protocol version ${this.protocolVersion}`);
254
+
255
+ this.topicStrings[TopicType.tx] = createTopicString(TopicType.tx, this.protocolVersion);
256
+ this.topicStrings[TopicType.block_proposal] = createTopicString(TopicType.block_proposal, this.protocolVersion);
257
+ this.topicStrings[TopicType.checkpoint_proposal] = createTopicString(
258
+ TopicType.checkpoint_proposal,
259
+ this.protocolVersion,
260
+ );
261
+ this.topicStrings[TopicType.checkpoint_attestation] = createTopicString(
262
+ TopicType.checkpoint_attestation,
263
+ this.protocolVersion,
264
+ );
265
+
266
+ // Build the consensus timetable once from protocol slot-timing constants and inject it into every
267
+ // validator so they share one set of receive-window bounds, independent of proposer operational budgets.
268
+ const consensusTimetable = buildConsensusTimetable(config, epochCache.getL1Constants());
269
+ const proposalValidatorOpts = {
270
+ txsPermitted: !config.disableTransactions,
271
+ maxTxsPerBlock: config.validateMaxTxsPerBlock ?? config.validateMaxTxsPerCheckpoint,
272
+ maxBlocksPerCheckpoint: config.maxBlocksPerCheckpoint,
273
+ skipSlotValidation: config.skipProposalSlotValidation,
274
+ signatureContext: {
275
+ chainId: config.l1ChainId,
276
+ rollupAddress: config.rollupAddress,
277
+ },
278
+ clockDisparityMs: config.maxGossipClockDisparityMs,
279
+ };
280
+ this.blockProposalValidator = new BlockProposalValidator(epochCache, consensusTimetable, proposalValidatorOpts);
281
+ this.checkpointProposalValidator = new CheckpointProposalValidator(
282
+ epochCache,
283
+ consensusTimetable,
284
+ proposalValidatorOpts,
285
+ );
286
+ const attestationValidatorOpts = {
287
+ signatureContext: proposalValidatorOpts.signatureContext,
288
+ clockDisparityMs: config.maxGossipClockDisparityMs,
289
+ };
290
+ this.checkpointAttestationValidator = config.fishermanMode
291
+ ? new FishermanAttestationValidator(
292
+ epochCache,
293
+ consensusTimetable,
294
+ mempools.attestationPool,
295
+ telemetry,
296
+ attestationValidatorOpts,
297
+ )
298
+ : new CheckpointAttestationValidator(epochCache, consensusTimetable, attestationValidatorOpts);
299
+
300
+ this.gossipSubEventHandler = this.handleGossipSubEvent.bind(this);
301
+
302
+ this.blockReceivedCallback = async (block: BlockProposal): Promise<boolean> => {
303
+ this.logger.warn(
304
+ `Handler for block received not yet registered on P2P service. Received block ${block.blockNumber} for slot ${block.slotNumber} from peer.`,
305
+ { p2pMessageIdentifier: await block.p2pMessageLoggingIdentifier() },
306
+ );
307
+ return true;
308
+ };
309
+
310
+ this.allNodesCheckpointReceivedCallback = (
311
+ _checkpoint: ValidatedCheckpointProposalCore,
312
+ ): Promise<CheckpointAttestation[] | undefined> => {
313
+ throw new CheckpointProposalReceivedCallbackNotRegisteredError();
314
+ };
315
+
316
+ this.validatorCheckpointReceivedCallback = (
317
+ _checkpoint: ValidatedCheckpointProposalCore,
318
+ ): Promise<CheckpointAttestation[] | undefined> => {
319
+ return Promise.resolve(undefined);
320
+ };
321
+ }
322
+
323
+ public updateConfig(config: Partial<P2PReqRespConfig & Pick<P2PConfig, 'skipIncomingProposals'>>) {
324
+ this.reqresp.updateConfig(config);
325
+ this.config = merge(this.config, config);
326
+ }
327
+
328
+ /**
329
+ * Creates an instance of the LibP2P service.
330
+ * @param config - The configuration to use when creating the service.
331
+ * @param txPool - The transaction pool to be accessed by the service.
332
+ * @returns The new service.
333
+ */
334
+ public static async new(
335
+ config: P2PConfig,
336
+ peerId: PeerId,
337
+ deps: {
338
+ mempools: MemPools;
339
+ l2BlockSource: L2BlockSource & ContractDataSource;
340
+ epochCache: EpochCacheInterface;
341
+ proofVerifier: ClientProtocolCircuitVerifier;
342
+ worldStateSynchronizer: WorldStateSynchronizer;
343
+ peerStore: AztecAsyncKVStore;
344
+ blockMinFeesProvider: BlockMinFeesProvider;
345
+ telemetry: TelemetryClient;
346
+ logger: Logger;
347
+ packageVersion: string;
348
+ txValidationCache?: TxValidationCache;
349
+ },
350
+ ) {
351
+ const {
352
+ worldStateSynchronizer,
353
+ epochCache,
354
+ l2BlockSource,
355
+ mempools,
356
+ proofVerifier,
357
+ peerStore,
358
+ blockMinFeesProvider,
359
+ telemetry,
360
+ logger,
361
+ packageVersion,
362
+ txValidationCache,
363
+ } = deps;
364
+ const { p2pPort, maxPeerCount, listenAddress } = config;
365
+ const bindAddrTcp = convertToMultiaddr(listenAddress, p2pPort, 'tcp');
366
+
367
+ const datastore = new AztecDatastore(peerStore);
368
+
369
+ const otelMetricsAdapter = new OtelMetricsAdapter(telemetry, logger.getBindings());
370
+
371
+ const peerDiscoveryService = new DiscV5Service(
372
+ peerId,
373
+ config,
374
+ packageVersion,
375
+ telemetry,
376
+ createLogger(`${logger.module}:discv5_service`, logger.getBindings()),
377
+ peerStore,
378
+ );
379
+
380
+ // Seed libp2p's bootstrap discovery with private and trusted peers
381
+ const bootstrapNodes = [...config.privatePeers, ...config.trustedPeers];
382
+
383
+ const peerDiscovery = [];
384
+ if (bootstrapNodes.length > 0) {
385
+ peerDiscovery.push(bootstrap({ list: bootstrapNodes }));
386
+ }
387
+
388
+ const versions = getVersions(config);
389
+ const protocolVersion = compressComponentVersions(versions);
390
+
391
+ const preferredPeersEnrs: ENR[] = config.preferredPeers.map(enr => ENR.decodeTxt(enr));
392
+ const directPeers = compactArray(
393
+ await Promise.all(
394
+ preferredPeersEnrs.map(async enr => {
395
+ try {
396
+ const peerId = await enr.peerId();
397
+ const address = enr.getLocationMultiaddr('tcp');
398
+ if (address === undefined) {
399
+ throw new Error(`Direct peer ${peerId.toString()} has no TCP address, ENR: ${enr.encodeTxt()}`);
400
+ }
401
+ return {
402
+ id: peerId,
403
+ addrs: [address],
404
+ };
405
+ } catch (err) {
406
+ // A malformed configured ENR shouldn't abort node setup — skip it and log.
407
+ logger.warn(`Skipping preferred peer with invalid ENR`, { err });
408
+ return undefined;
409
+ }
410
+ }),
411
+ ),
412
+ );
413
+
414
+ const announceTcpMultiaddr = config.p2pIp ? [convertToMultiaddr(config.p2pIp, p2pPort, 'tcp')] : [];
415
+
416
+ // Create dynamic topic score params based on network configuration. Scoring uses the network-wide
417
+ // max-blocks-per-checkpoint config value directly to size expected per-slot message rates; these are
418
+ // peer-rate thresholds, not consensus deadlines, so they need no proposer operational budgets.
419
+ const l1Constants = epochCache.getL1Constants();
420
+ const topicScoreParams = createAllTopicScoreParams(protocolVersion, {
421
+ slotDurationMs: l1Constants.slotDuration * 1000,
422
+ heartbeatIntervalMs: config.gossipsubInterval,
423
+ targetCommitteeSize: l1Constants.targetCommitteeSize,
424
+ maxBlocksPerCheckpoint: config.maxBlocksPerCheckpoint ?? DEFAULT_MAX_BLOCKS_PER_CHECKPOINT,
425
+ expectedBlockProposalsPerSlot: config.expectedBlockProposalsPerSlot,
426
+ });
427
+
428
+ // Restrict gossipsub to exactly the topics we subscribe to. Without this, an arbitrary-topic
429
+ // message is transformed, msg-id'd and inserted into the seenCache before the subscription check,
430
+ // so a crafted topic colliding on msg id can suppress a real message as a duplicate.
431
+ const allowedTopics = getTopicsForConfig(config.disableTransactions).map(topic =>
432
+ createTopicString(topic, protocolVersion),
433
+ );
434
+
435
+ const node = await createLibp2p({
436
+ start: false,
437
+ peerId,
438
+ addresses: {
439
+ listen: [bindAddrTcp],
440
+ announce: announceTcpMultiaddr,
441
+ },
442
+ transports: [
443
+ tcp({
444
+ // It's better to have this number a bit higher than our maxPeerCount because it's sets the limit on transport (TCP) layer
445
+ // The connection attempts to the node on TCP layer are not necessarily valid Aztec peers so we want to have a bit of leeway here
446
+ // If we hit the limit, the connection will be temporarily accepted and immediately dropped.
447
+ // Docs: https://nodejs.org/api/net.html#servermaxconnections
448
+ maxConnections: maxPeerCount * 2,
449
+ // socket option: the maximum length of the queue of pending connections
450
+ // https://nodejs.org/dist/latest-v22.x/docs/api/net.html#serverlisten
451
+ // it's not safe if we increase this number
452
+ backlog: 5,
453
+ closeServerOnMaxConnections: {
454
+ // The property `maxConnections` will protect us against the most DDOS attack
455
+ // This property protects us in case of burst of new connections where server is not able to close them quickly enough
456
+ // In case closeAbove is reached, the server stops listening altogether
457
+ // It's important that there is enough difference between closeAbove and listenAbove,
458
+ // otherwise the server.listener will flap between being closed and open potentially degrading perf even more
459
+ closeAbove: maxPeerCount * 3,
460
+ listenBelow: Math.floor(maxPeerCount * 0.9),
461
+ },
462
+ }),
463
+ ],
464
+ datastore,
465
+ peerDiscovery,
466
+ // Pin the yamux frame size: MAX_REQRESP_REQUEST_SIZE_BYTES relies on a reqresp request fitting in one frame.
467
+ streamMuxers: [yamux({ maxMessageSize: YAMUX_MAX_MESSAGE_SIZE_BYTES }), mplex()],
468
+ connectionEncryption: [noise()],
469
+ connectionManager: {
470
+ minConnections: 0, // Disable libp2p peer dialing, we do it manually
471
+ // We set maxConnections above maxPeerCount because if we hit limit of maxPeerCount
472
+ // libp2p will start aggressively rejecting all new connections, preventing network discovery and crawling.
473
+ maxConnections: maxPeerCount * 2,
474
+ maxParallelDials: 100,
475
+ dialTimeout: 30_000,
476
+ maxPeerAddrsToDial: 5,
477
+ maxIncomingPendingConnections: 5,
478
+ },
479
+ connectionGater: {
480
+ denyInboundConnection: (maConn: MultiaddrConnection) => {
481
+ const allowed = peerManager.isAddressAllowedToConnect(maConn.remoteAddr.nodeAddress().address);
482
+ if (allowed) {
483
+ return false;
484
+ }
485
+
486
+ logger.debug(`Connection gater: Denying inbound connection from ${maConn.remoteAddr.toString()}`);
487
+ return true;
488
+ },
489
+ denyInboundEncryptedConnection: (peerId: PeerId, _maConn: MultiaddrConnection) => {
490
+ //NOTE: it is not necessary to check address here because this was already done by
491
+ // denyInboundConnection
492
+ const allowed = peerManager.isPeerAllowedToConnect(peerId);
493
+ if (allowed) {
494
+ return false;
495
+ }
496
+
497
+ logger.debug(`Connection gater: Denying inbound encrypted connection from ${peerId.toString()}`);
498
+ return true;
499
+ },
500
+ },
501
+ services: {
502
+ identify: identify({
503
+ protocolPrefix: 'aztec',
504
+ runOnConnectionOpen: true,
505
+ }),
506
+ pubsub: gossipsub({
507
+ directPeers,
508
+ debugName: 'gossipsub',
509
+ globalSignaturePolicy: SignaturePolicy.StrictNoSign,
510
+ allowPublishToZeroTopicPeers: true,
511
+ floodPublish: config.gossipsubFloodPublish,
512
+ D: config.gossipsubD,
513
+ Dlo: config.gossipsubDlo,
514
+ Dhi: config.gossipsubDhi,
515
+ Dlazy: config.gossipsubDLazy,
516
+ heartbeatInterval: config.gossipsubInterval,
517
+ mcacheLength: config.gossipsubMcacheLength,
518
+ mcacheGossip: config.gossipsubMcacheGossip,
519
+ seenTTL: config.gossipsubSeenTTL,
520
+ allowedTopics,
521
+ // No fastMsgIdFn: the fast-path dedup cache keys on a non-cryptographic 64-bit hash of the
522
+ // raw data only (no topic), so a collision — accidental or engineered via a weak seed — drops
523
+ // a different message with no fallback to the full id. Dedup instead rests solely on the
524
+ // cryptographic, topic-framed msgIdFn below.
525
+ msgIdFn: getMsgIdFn,
526
+ msgIdToStrFn: msgIdToStrFn,
527
+ dataTransform: new SnappyTransform(),
528
+ metricsRegister: otelMetricsAdapter,
529
+ metricsTopicStrToLabel: metricsTopicStrToLabels(protocolVersion),
530
+ asyncValidation: true,
531
+ scoreThresholds: gossipScoreThresholds,
532
+ scoreParams: createPeerScoreParams({
533
+ // IPColocation factor can be disabled for local testing - default to -5
534
+ IPColocationFactorWeight: config.debugDisableColocationPenalty ? 0 : -5.0,
535
+ topics: topicScoreParams,
536
+ }),
537
+ }) as (components: GossipSubComponents) => GossipSub,
538
+ components: (components: { connectionManager: ConnectionManager; addressManager: AddressManager }) => ({
539
+ connectionManager: components.connectionManager,
540
+ addressManager: components.addressManager,
541
+ }),
542
+ },
543
+ logger: createLibp2pComponentLogger(logger.module, logger.getBindings()),
544
+ });
545
+
546
+ const peerScoring = new PeerScoring(config, telemetry);
547
+ const reqresp = new ReqResp(config, node, peerScoring, createLogger(`${logger.module}:reqresp`));
548
+
549
+ const peerManager = new PeerManager(
550
+ node,
551
+ peerDiscoveryService,
552
+ config,
553
+ telemetry,
554
+ createLogger(`${logger.module}:peer_manager`),
555
+ peerScoring,
556
+ reqresp,
557
+ worldStateSynchronizer,
558
+ protocolVersion,
559
+ epochCache,
560
+ );
561
+
562
+ // Gate req/resp data protocols for unauthenticated peers when p2pAllowOnlyValidators is enabled
563
+ reqresp.setShouldRejectPeer(peerId => peerManager.shouldDisableP2PGossip(peerId));
564
+
565
+ // Configure application-specific scoring for gossipsub.
566
+ // The weight scales app score to align with gossipsub thresholds:
567
+ // - Disconnect (-50) × 10 = -500 = gossipThreshold (stops receiving gossip)
568
+ // - Ban (-100) × 10 = -1000 = publishThreshold (cannot publish)
569
+ // Note: positive topic scores can offset penalties, so alignment is best-effort.
570
+ node.services.pubsub.score.params.appSpecificWeight = APP_SPECIFIC_WEIGHT;
571
+ node.services.pubsub.score.params.appSpecificScore = (peerId: string) =>
572
+ peerManager.shouldDisableP2PGossip(peerId) ? -Infinity : peerManager.getPeerScore(peerId);
573
+
574
+ return new LibP2PService(
575
+ config,
576
+ node,
577
+ peerDiscoveryService,
578
+ reqresp,
579
+ peerManager,
580
+ mempools,
581
+ l2BlockSource,
582
+ epochCache,
583
+ proofVerifier,
584
+ worldStateSynchronizer,
585
+ blockMinFeesProvider,
586
+ telemetry,
587
+ logger,
588
+ txValidationCache,
589
+ );
590
+ }
591
+
592
+ /**
593
+ * Starts the LibP2P service.
594
+ * @returns An empty promise.
595
+ */
596
+ public async start() {
597
+ // Check if service is already started
598
+ if (this.node.status === 'started') {
599
+ throw new Error('P2P service already started');
600
+ }
601
+
602
+ const { p2pIp, p2pPort } = this.config;
603
+ if (!p2pIp && !this.config.queryForIp) {
604
+ throw new Error('Announce address not provided and queryForIp is not enabled.');
605
+ }
606
+ const announceTcpMultiaddr = p2pIp ? convertToMultiaddr(p2pIp, p2pPort, 'tcp') : undefined;
607
+
608
+ // Create request response protocol handlers
609
+ const txHandler = reqRespTxHandler(this.mempools);
610
+ const goodbyeHandler = reqGoodbyeHandler(this.peerManager);
611
+ const statusHandler = reqRespStatusHandler(this.protocolVersion, this.worldStateSynchronizer, this.logger);
612
+
613
+ const requestResponseHandlers: Partial<ReqRespSubProtocolHandlers> = {
614
+ [ReqRespSubProtocol.PING]: pingHandler,
615
+ [ReqRespSubProtocol.STATUS]: statusHandler.bind(this),
616
+ [ReqRespSubProtocol.GOODBYE]: goodbyeHandler.bind(this),
617
+ };
618
+
619
+ if (!this.config.disableTransactions) {
620
+ const blockTxsHandler = reqRespBlockTxsHandler(
621
+ this.mempools.attestationPool,
622
+ this.archiver,
623
+ this.mempools.txPool,
624
+ );
625
+ requestResponseHandlers[ReqRespSubProtocol.BLOCK_TXS] = blockTxsHandler.bind(this);
626
+ }
627
+
628
+ if (!this.config.disableTransactions) {
629
+ requestResponseHandlers[ReqRespSubProtocol.TX] = txHandler.bind(this);
630
+ }
631
+
632
+ await this.peerManager.initializePeers();
633
+
634
+ await this.reqresp.start(requestResponseHandlers);
635
+
636
+ await this.node.start();
637
+
638
+ // Subscribe to standard GossipSub topics by default
639
+ for (const topic of getTopicsForConfig(this.config.disableTransactions)) {
640
+ this.subscribeToTopic(this.topicStrings[topic]);
641
+ }
642
+
643
+ // add GossipSub listener
644
+ this.node.services.pubsub.addEventListener(GossipSubEvent.MESSAGE, this.gossipSubEventHandler);
645
+
646
+ // Start running promise for peer discovery and metrics collection
647
+ if (!this.config.p2pDiscoveryDisabled) {
648
+ await this.peerDiscoveryService.start();
649
+ }
650
+
651
+ // Bridge discv5 IP changes to libp2p's AddressManager so peers see the updated address
652
+ if (this.config.queryForIp) {
653
+ this.discoveredP2pIp = this.config.p2pIp;
654
+ this.logger.info('IP change tracking enabled, bridging discv5 IP updates to libp2p AddressManager');
655
+ this.ipChangedHandler = (ip: string) => {
656
+ const addressManager = this.node.services.components.addressManager;
657
+ const newAddr = multiaddr(convertToMultiaddr(ip, this.config.p2pPort, 'tcp'));
658
+ const previousIp = this.discoveredP2pIp;
659
+
660
+ if (previousIp) {
661
+ const oldAddr = multiaddr(convertToMultiaddr(previousIp, this.config.p2pPort, 'tcp'));
662
+ addressManager.removeObservedAddr(oldAddr);
663
+ this.logger.info('Libp2p announce address updated due to IP change', {
664
+ previousIp,
665
+ newIp: ip,
666
+ newMultiaddr: newAddr.toString(),
667
+ });
668
+ } else {
669
+ this.logger.info('Libp2p announce address set from initial discv5 IP discovery', {
670
+ ip,
671
+ multiaddr: newAddr.toString(),
672
+ });
673
+ }
674
+
675
+ addressManager.addObservedAddr(newAddr);
676
+ addressManager.confirmObservedAddr(newAddr);
677
+ this.discoveredP2pIp = ip;
678
+ };
679
+ this.peerDiscoveryService.on('ip:changed', this.ipChangedHandler);
680
+ }
681
+
682
+ this.discoveryRunningPromise = new RunningPromise(
683
+ async () => {
684
+ await this.peerManager.heartbeat();
685
+ },
686
+ this.logger,
687
+ this.config.peerCheckIntervalMS,
688
+ );
689
+ this.discoveryRunningPromise.start();
690
+
691
+ this.logger.info(`Started P2P service`, {
692
+ listen: this.config.listenAddress,
693
+ port: this.config.p2pPort,
694
+ announce: announceTcpMultiaddr,
695
+ peerId: this.node.peerId.toString(),
696
+ });
697
+ }
698
+
699
+ /**
700
+ * Stops the LibP2P service.
701
+ * @returns An empty promise.
702
+ */
703
+ public async stop() {
704
+ // Remove gossip sub listener
705
+ this.node.services.pubsub.removeEventListener(GossipSubEvent.MESSAGE, this.gossipSubEventHandler);
706
+
707
+ if (this.ipChangedHandler) {
708
+ this.peerDiscoveryService.removeListener('ip:changed', this.ipChangedHandler);
709
+ this.ipChangedHandler = undefined;
710
+ }
711
+
712
+ // Stop peer manager
713
+ this.logger.debug('Stopping peer manager...');
714
+ await this.peerManager.stop();
715
+ this.logger.debug('Stopping running promise...');
716
+ await this.discoveryRunningPromise?.stop();
717
+ this.logger.debug('Stopping peer discovery service...');
718
+ await this.peerDiscoveryService.stop();
719
+ this.logger.debug('Request response service stopped...');
720
+ await this.reqresp.stop();
721
+ this.logger.debug('Stopping LibP2P...');
722
+ await this.stopLibP2P();
723
+ this.logger.info('LibP2P service stopped');
724
+ }
725
+
726
+ addReqRespSubProtocol(subProtocol: ReqRespSubProtocol, handler: ReqRespSubProtocolHandler): Promise<void> {
727
+ return this.reqresp.addSubProtocol(subProtocol, handler);
728
+ }
729
+
730
+ public registerThisValidatorAddresses(address: EthAddress[]): void {
731
+ this.peerManager.registerThisValidatorAddresses(address);
732
+ }
733
+
734
+ public getPeers(includePending?: boolean): PeerInfo[] {
735
+ return this.peerManager.getPeers(includePending);
736
+ }
737
+
738
+ public getP2PConnectivity(): P2PConnectivity {
739
+ const connectedPeers = this.peerManager.getPeers().filter(peer => peer.status === 'connected').length;
740
+ return { enabled: true, connectedPeers };
741
+ }
742
+
743
+ public getGossipMeshPeerCount(topicType: TopicType): number {
744
+ return this.node.services.pubsub.getMeshPeers(this.topicStrings[topicType]).length;
745
+ }
746
+
747
+ private handleGossipSubEvent(e: CustomEvent<GossipsubMessage>) {
748
+ this.logger.trace(`Received PUBSUB message.`);
749
+
750
+ const safeJob = async () => {
751
+ try {
752
+ await this.handleNewGossipMessage(e.detail.msg, e.detail.msgId, e.detail.propagationSource);
753
+ } catch (err) {
754
+ this.logger.error(`Error handling gossipsub message: ${err}`);
755
+ }
756
+ };
757
+ setImmediate(() => void safeJob());
758
+ }
759
+
760
+ public sendRequestToPeer(
761
+ peerId: PeerId,
762
+ subProtocol: ReqRespSubProtocol,
763
+ payload: Buffer,
764
+ dialTimeout?: number,
765
+ ): Promise<ReqRespResponse> {
766
+ return this.reqresp.sendRequestToPeer(peerId, subProtocol, payload, dialTimeout);
767
+ }
768
+
769
+ /**
770
+ * Get the ENR of the node
771
+ * @returns The ENR of the node
772
+ */
773
+ public getEnr(): ENR | undefined {
774
+ return this.peerDiscoveryService.getEnr();
775
+ }
776
+
777
+ public registerBlockReceivedCallback(callback: P2PBlockReceivedCallback) {
778
+ this.blockReceivedCallback = callback;
779
+ }
780
+
781
+ public registerValidatorCheckpointReceivedCallback(callback: P2PCheckpointReceivedCallback) {
782
+ this.validatorCheckpointReceivedCallback = callback;
783
+ }
784
+
785
+ public registerAllNodesCheckpointReceivedCallback(callback: P2PCheckpointReceivedCallback) {
786
+ this.allNodesCheckpointReceivedCallback = callback;
787
+ }
788
+
789
+ /**
790
+ * Registers a callback to be invoked when a duplicate proposal is detected.
791
+ * This callback is triggered on the first duplicate (when count goes from 1 to 2).
792
+ */
793
+ public registerDuplicateProposalCallback(
794
+ callback: (info: { slot: SlotNumber; proposer: EthAddress; type: 'checkpoint' | 'block' }) => void,
795
+ ): void {
796
+ this.duplicateProposalCallback = callback;
797
+ }
798
+
799
+ /**
800
+ * Registers a callback to be invoked when an oversized block proposal is stored as slashing evidence.
801
+ */
802
+ public registerOversizedProposalCallback(callback: P2POversizedProposalCallback): void {
803
+ this.oversizedProposalCallback = callback;
804
+ }
805
+
806
+ /**
807
+ * Registers a callback to be invoked when a duplicate attestation is detected.
808
+ * A validator signing attestations for different proposals at the same slot.
809
+ * This callback is triggered on the first duplicate (when count goes from 1 to 2).
810
+ */
811
+ public registerDuplicateAttestationCallback(callback: P2PDuplicateAttestationCallback): void {
812
+ this.duplicateAttestationCallback = callback;
813
+ }
814
+
815
+ public registerCheckpointAttestationCallback(callback: P2PCheckpointAttestationCallback): void {
816
+ this.checkpointAttestationCallback = callback;
817
+ }
818
+
819
+ /**
820
+ * Subscribes to a topic.
821
+ * @param topic - The topic to subscribe to.
822
+ */
823
+ private subscribeToTopic(topic: string) {
824
+ if (!this.node.services.pubsub) {
825
+ throw new Error('Pubsub service not available.');
826
+ }
827
+ void this.node.services.pubsub.subscribe(topic);
828
+ }
829
+
830
+ /**
831
+ * Publishes data to a topic.
832
+ * @param topic - The topic to publish to.
833
+ * @param data - The message to publish.
834
+ * @returns The number of recipients the data was sent to.
835
+ */
836
+ private async publishToTopic(topic: string, message: Gossipable) {
837
+ if (!this.node.services.pubsub) {
838
+ throw new Error('Pubsub service not available.');
839
+ }
840
+ const isBlockProposal = topic === this.topicStrings[TopicType.block_proposal];
841
+ const traceContext =
842
+ this.config.debugP2PInstrumentMessages && isBlockProposal ? this.telemetry.getTraceContext() : undefined;
843
+ const p2pMessage = P2PMessage.fromGossipable(message, this.config.debugP2PInstrumentMessages, traceContext);
844
+ const result = await this.node.services.pubsub.publish(topic, p2pMessage.toMessageData());
845
+ return result.recipients.length;
846
+ }
847
+
848
+ /**
849
+ * Checks if this message has already been seen, based on its msgId computed from hashing the message data.
850
+ * Note that we do not rely on the seenCache from gossipsub since we want to keep a longer history of seen
851
+ * messages to avoid tx echoes across the network.
852
+ */
853
+ protected preValidateReceivedMessage(
854
+ msg: Message,
855
+ msgId: string,
856
+ source: PeerId,
857
+ ): { result: boolean; topicType?: TopicType } {
858
+ let topicType: TopicType | undefined;
859
+
860
+ switch (msg.topic) {
861
+ case this.topicStrings[TopicType.tx]:
862
+ topicType = TopicType.tx;
863
+ break;
864
+ case this.topicStrings[TopicType.block_proposal]:
865
+ topicType = TopicType.block_proposal;
866
+ break;
867
+ case this.topicStrings[TopicType.checkpoint_proposal]:
868
+ topicType = TopicType.checkpoint_proposal;
869
+ break;
870
+ case this.topicStrings[TopicType.checkpoint_attestation]:
871
+ topicType = TopicType.checkpoint_attestation;
872
+ break;
873
+ default:
874
+ this.logger.error(`Received message on unknown topic: ${msg.topic}`);
875
+ break;
876
+ }
877
+
878
+ const validator = topicType ? this.msgIdSeenValidators[topicType] : undefined;
879
+
880
+ if (!validator || !validator.addMessage(msgId)) {
881
+ this.instrumentation.incMessagePrevalidationStatus(false, topicType);
882
+ this.node.services.pubsub.reportMessageValidationResult(msgId, source.toString(), TopicValidatorResult.Ignore);
883
+ if (topicType === TopicType.tx) {
884
+ this.logger.verbose(`Ignoring already-seen tx gossip message`, { msgId, source: source.toString() });
885
+ }
886
+ return { result: false, topicType };
887
+ }
888
+
889
+ this.instrumentation.incMessagePrevalidationStatus(true, topicType);
890
+
891
+ return { result: true, topicType };
892
+ }
893
+
894
+ /**
895
+ * Safely deserializes a P2PMessage from raw message data.
896
+ * @param msgId - The message ID.
897
+ * @param source - The peer ID of the message source.
898
+ * @param data - The raw message data.
899
+ * @returns The deserialized P2PMessage or undefined if deserialization fails.
900
+ */
901
+ private safelyDeserializeP2PMessage(msgId: string, source: PeerId, data: Uint8Array): P2PMessage | undefined {
902
+ try {
903
+ return P2PMessage.fromMessageData(Buffer.from(data), this.config.debugP2PInstrumentMessages);
904
+ } catch (err) {
905
+ this.logger.error(`Error deserializing P2PMessage`, err, {
906
+ msgId,
907
+ source: source.toString(),
908
+ });
909
+ this.node.services.pubsub.reportMessageValidationResult(msgId, source.toString(), TopicValidatorResult.Reject);
910
+ this.peerManager.penalizePeer(source, PeerErrorSeverity.LowToleranceError);
911
+ return undefined;
912
+ }
913
+ }
914
+
915
+ /**
916
+ * Handles a new gossip message that was received by the client.
917
+ * @param topic - The message's topic.
918
+ * @param data - The message data
919
+ */
920
+ protected async handleNewGossipMessage(msg: Message, msgId: string, source: PeerId) {
921
+ const msgReceivedTime = Date.now();
922
+ let topicType: TopicType | undefined;
923
+ const p2pMessage = this.safelyDeserializeP2PMessage(msgId, source, msg.data);
924
+ if (!p2pMessage) {
925
+ return;
926
+ }
927
+
928
+ const preValidationResult = this.preValidateReceivedMessage(msg, msgId, source);
929
+
930
+ if (!preValidationResult.result) {
931
+ return;
932
+ }
933
+
934
+ // Determine topic type for attributes
935
+ if (msg.topic === this.topicStrings[TopicType.tx]) {
936
+ topicType = TopicType.tx;
937
+ } else if (msg.topic === this.topicStrings[TopicType.checkpoint_attestation]) {
938
+ topicType = TopicType.checkpoint_attestation;
939
+ } else if (msg.topic === this.topicStrings[TopicType.block_proposal]) {
940
+ topicType = TopicType.block_proposal;
941
+ } else if (msg.topic === this.topicStrings[TopicType.checkpoint_proposal]) {
942
+ topicType = TopicType.checkpoint_proposal;
943
+ }
944
+
945
+ // Process the message, optionally within a linked span for trace propagation
946
+ const processMessage = async () => {
947
+ if (
948
+ this.config.skipIncomingProposals &&
949
+ (msg.topic === this.topicStrings[TopicType.block_proposal] ||
950
+ msg.topic === this.topicStrings[TopicType.checkpoint_proposal])
951
+ ) {
952
+ this.logger.warn(`Ignoring incoming proposal (skipIncomingProposals is set)`, { topic: msg.topic });
953
+ this.node.services.pubsub.reportMessageValidationResult(msgId, source.toString(), TopicValidatorResult.Ignore);
954
+ return;
955
+ }
956
+ if (msg.topic === this.topicStrings[TopicType.tx]) {
957
+ await this.handleGossipedTx(p2pMessage.payload, msgId, source);
958
+ } else if (msg.topic === this.topicStrings[TopicType.checkpoint_attestation]) {
959
+ await this.processCheckpointAttestationFromPeer(p2pMessage.payload, msgId, source);
960
+ } else if (msg.topic === this.topicStrings[TopicType.block_proposal]) {
961
+ await this.processBlockFromPeer(p2pMessage.payload, msgId, source);
962
+ } else if (msg.topic === this.topicStrings[TopicType.checkpoint_proposal]) {
963
+ await this.handleGossipedCheckpointProposal(p2pMessage.payload, msgId, source);
964
+ } else {
965
+ this.logger.error(`Received message on unknown topic: ${msg.topic}`);
966
+ }
967
+ };
968
+
969
+ const latency = p2pMessage.timestamp !== undefined ? msgReceivedTime - p2pMessage.timestamp.getTime() : undefined;
970
+ const propagatedContext = p2pMessage.traceContext
971
+ ? this.telemetry.extractPropagatedContext(p2pMessage.traceContext)
972
+ : undefined;
973
+
974
+ if (propagatedContext) {
975
+ await this.tracer.startActiveSpan(
976
+ 'LibP2PService.processMessage',
977
+ {
978
+ attributes: {
979
+ [Attributes.TOPIC_NAME]: topicType!,
980
+ [Attributes.PEER_ID]: source.toString(),
981
+ },
982
+ },
983
+ propagatedContext,
984
+ async span => {
985
+ try {
986
+ await processMessage();
987
+ span.setStatus({
988
+ code: SpanStatusCode.OK,
989
+ });
990
+ } catch (err) {
991
+ span.setStatus({
992
+ code: SpanStatusCode.ERROR,
993
+ message: String(err),
994
+ });
995
+ if (typeof err === 'string' || (err && err instanceof Error)) {
996
+ span.recordException(err);
997
+ }
998
+ throw err;
999
+ } finally {
1000
+ span.end();
1001
+ }
1002
+ },
1003
+ );
1004
+ } else {
1005
+ await processMessage();
1006
+ }
1007
+
1008
+ if (latency !== undefined && topicType !== undefined) {
1009
+ this.instrumentation.recordMessageLatency(topicType, latency);
1010
+ }
1011
+
1012
+ return;
1013
+ }
1014
+
1015
+ protected async validateReceivedMessage<T, M = undefined>(
1016
+ validationFunc: () => Promise<ReceivedMessageValidationResult<T, M>>,
1017
+ msgId: string,
1018
+ source: PeerId,
1019
+ topicType: TopicType,
1020
+ stageTimings?: Record<string, number>,
1021
+ ): Promise<ReceivedMessageValidationResult<T, M>> {
1022
+ // Default to reject result with a penalty if validation function throws an error
1023
+ let resultAndObj: ReceivedMessageValidationResult<T, M> = {
1024
+ result: TopicValidatorResult.Reject,
1025
+ severity: PeerErrorSeverity.MidToleranceError,
1026
+ };
1027
+ const timer = new Timer();
1028
+ try {
1029
+ resultAndObj = await validationFunc();
1030
+ } catch (err) {
1031
+ this.logger.error(`Error validating gossipsub message`, err, { msgId, source: source.toString(), topicType });
1032
+ }
1033
+
1034
+ const validationTimeMs = timer.ms();
1035
+ const mcacheWindowMs = this.config.gossipsubMcacheLength * this.config.gossipsubInterval;
1036
+ if (validationTimeMs > mcacheWindowMs * 0.75) {
1037
+ this.instrumentation.incSlowValidation(topicType);
1038
+ this.logger.warn(
1039
+ `Gossip validation for ${topicType} took ${validationTimeMs}ms, approaching mcache eviction window of ${mcacheWindowMs}ms. ` +
1040
+ `Message forwarding may be skipped if validation exceeds the window.`,
1041
+ { msgId, source: source.toString(), topicType, validationTimeMs, mcacheWindowMs, stageTimings },
1042
+ );
1043
+ }
1044
+
1045
+ if (resultAndObj.result === TopicValidatorResult.Accept) {
1046
+ this.logger.debug(`Message ${topicType} accepted by validator`, {
1047
+ msgId,
1048
+ source: source.toString(),
1049
+ topicType,
1050
+ validationTimeMs,
1051
+ stageTimings,
1052
+ });
1053
+ this.instrumentation.recordMessageValidation(topicType, timer);
1054
+ } else if (resultAndObj.result === TopicValidatorResult.Reject) {
1055
+ this.logger.warn(`Message ${topicType} rejected by validator with severity ${resultAndObj.severity}`, {
1056
+ msgId,
1057
+ source: source.toString(),
1058
+ topicType,
1059
+ severity: resultAndObj.severity,
1060
+ });
1061
+ this.peerManager.penalizePeer(source, resultAndObj.severity);
1062
+ } else {
1063
+ this.logger.trace(`Message ${topicType} ignored by validator`, { msgId, source: source.toString(), topicType });
1064
+ }
1065
+
1066
+ this.node.services.pubsub.reportMessageValidationResult(msgId, source.toString(), resultAndObj.result);
1067
+ return resultAndObj;
1068
+ }
1069
+
1070
+ private tryDeserialize<T>(deserializeFunc: () => T, msgId: string, source: PeerId): T | undefined {
1071
+ try {
1072
+ return deserializeFunc();
1073
+ } catch (err) {
1074
+ this.logger.warn(`Failed to deserialize gossipsub message from buffer`, {
1075
+ err,
1076
+ msgId,
1077
+ source: source.toString(),
1078
+ });
1079
+ return undefined;
1080
+ }
1081
+ }
1082
+
1083
+ protected async handleGossipedTx(payloadData: Buffer, msgId: string, source: PeerId) {
1084
+ // Per-stage timings so slow validations can be attributed to a specific stage (see A-1656).
1085
+ const stageTimings: Record<string, number> = {};
1086
+ const timed = async <T>(stage: string, fn: () => T | Promise<T>): Promise<T> => {
1087
+ const timer = new Timer();
1088
+ try {
1089
+ return await fn();
1090
+ } finally {
1091
+ const ms = timer.ms();
1092
+ stageTimings[stage] = Math.ceil(ms);
1093
+ this.instrumentation.recordTxValidationStage(stage, ms);
1094
+ }
1095
+ };
1096
+
1097
+ const validationFunc: () => Promise<ReceivedMessageValidationResult<Tx>> = async () => {
1098
+ const tx = await timed('deserialize', () => this.tryDeserialize(() => Tx.fromBuffer(payloadData), msgId, source));
1099
+ if (!tx) {
1100
+ return { result: TopicValidatorResult.Reject, severity: PeerErrorSeverity.LowToleranceError };
1101
+ }
1102
+
1103
+ // Stage 1 setup: chain tip, epoch info, gas fees, and L1 constants reads
1104
+ const { currentBlockNumber, firstStageValidators } = await timed('fast_validation_setup', async () => {
1105
+ const currentBlockNumber = await this.archiver.getBlockNumber();
1106
+ const { ts: nextSlotTimestamp } = this.epochCache.getEpochAndSlotInNextL1Slot();
1107
+ const firstStageValidators = await this.createFirstStageMessageValidators(
1108
+ currentBlockNumber,
1109
+ nextSlotTimestamp,
1110
+ );
1111
+ return { currentBlockNumber, firstStageValidators };
1112
+ });
1113
+
1114
+ // Stage 1: fast validators (metadata, data, timestamps, double-spend, gas, phases, block header)
1115
+ const firstStageOutcome = await timed('fast_validation', () => this.runValidations(tx, firstStageValidators));
1116
+ if (!firstStageOutcome.allPassed) {
1117
+ const { name } = firstStageOutcome.failure;
1118
+ let { severity } = firstStageOutcome.failure;
1119
+
1120
+ // Double spend validator has a special case handler. We perform more detailed examination
1121
+ // as to how recently the nullifier was entered into the tree and if the transaction should
1122
+ // have 'known' the nullifier existed. This determines the severity of the penalty applied to the peer.
1123
+ if (name === 'doubleSpendValidator') {
1124
+ const txBlockNumber = BlockNumber(currentBlockNumber + 1);
1125
+ severity = await this.handleDoubleSpendFailure(tx, txBlockNumber);
1126
+ }
1127
+
1128
+ this.logger.verbose(`Rejecting gossiped tx ${tx.getTxHash().toString()}: stage 1 validation failed`, {
1129
+ validator: name,
1130
+ severity,
1131
+ source: source.toString(),
1132
+ });
1133
+ return { result: TopicValidatorResult.Reject, severity };
1134
+ }
1135
+
1136
+ // Pool pre-check: see if the pool would accept this tx before doing expensive proof verification
1137
+ const canAdd = await timed('pool_precheck', () => this.mempools.txPool.canAddPendingTx(tx));
1138
+ if (canAdd === 'ignored') {
1139
+ this.logger.verbose(`Ignoring gossiped tx ${tx.getTxHash().toString()}: pool pre-check returned ignored`, {
1140
+ source: source.toString(),
1141
+ });
1142
+ return { result: TopicValidatorResult.Ignore, obj: tx };
1143
+ }
1144
+
1145
+ // Stage 2: expensive proof verification
1146
+ const secondStageValidators = this.createSecondStageMessageValidators();
1147
+ const secondStageOutcome = await timed('proof_verify', () => this.runValidations(tx, secondStageValidators));
1148
+ if (!secondStageOutcome.allPassed) {
1149
+ const { severity, name } = secondStageOutcome.failure;
1150
+ this.logger.verbose(`Rejecting gossiped tx ${tx.getTxHash().toString()}: stage 2 validation failed`, {
1151
+ validator: name,
1152
+ severity,
1153
+ source: source.toString(),
1154
+ });
1155
+ return { result: TopicValidatorResult.Reject, severity };
1156
+ }
1157
+
1158
+ // Pool add: persist the tx
1159
+ const txHash = tx.getTxHash();
1160
+ const addResult = await timed('pool_add', () => this.mempools.txPool.addPendingTxs([tx], { source: 'gossip' }));
1161
+
1162
+ const wasAccepted = addResult.accepted.some(h => h.equals(txHash));
1163
+ const wasIgnored = addResult.ignored.some(h => h.equals(txHash));
1164
+
1165
+ this.logger.verbose(`Validate propagated tx ${txHash.toString()}`, {
1166
+ wasAccepted,
1167
+ wasIgnored,
1168
+ [Attributes.P2P_ID]: source.toString(),
1169
+ });
1170
+
1171
+ if (wasAccepted) {
1172
+ return { result: TopicValidatorResult.Accept, obj: tx };
1173
+ } else if (wasIgnored) {
1174
+ return { result: TopicValidatorResult.Ignore, obj: tx };
1175
+ } else {
1176
+ this.logger.warn(`Gossiped tx ${txHash.toString()} unexpectedly rejected by pool`, {
1177
+ source: source.toString(),
1178
+ txHash: txHash.toString(),
1179
+ });
1180
+ return { result: TopicValidatorResult.Reject, severity: PeerErrorSeverity.HighToleranceError };
1181
+ }
1182
+ };
1183
+
1184
+ const { result, obj: tx } = await this.validateReceivedMessage<Tx>(
1185
+ validationFunc,
1186
+ msgId,
1187
+ source,
1188
+ TopicType.tx,
1189
+ stageTimings,
1190
+ );
1191
+ if (result !== TopicValidatorResult.Accept || !tx) {
1192
+ return;
1193
+ }
1194
+
1195
+ // Tx was accepted into pool and will be propagated - just log and record metrics
1196
+ const txHash = tx.getTxHash();
1197
+ const txHashString = txHash.toString();
1198
+ this.logger.verbose(`Received tx ${txHashString} from external peer ${source.toString()} via gossip`, {
1199
+ source: source.toString(),
1200
+ txHash: txHashString,
1201
+ });
1202
+
1203
+ this.instrumentation.incrementTxReceived(1);
1204
+ }
1205
+
1206
+ /**
1207
+ * Process a checkpoint attestation from a peer.
1208
+ * Validates the attestation and adds it to the pool.
1209
+ */
1210
+ private async processCheckpointAttestationFromPeer(
1211
+ payloadData: Buffer,
1212
+ msgId: string,
1213
+ source: PeerId,
1214
+ ): Promise<void> {
1215
+ const { result, obj: attestation } = await this.validateReceivedMessage<CheckpointAttestation>(
1216
+ () => {
1217
+ const attestation = this.tryDeserialize(() => CheckpointAttestation.fromBuffer(payloadData), msgId, source);
1218
+ if (!attestation) {
1219
+ return Promise.resolve({
1220
+ result: TopicValidatorResult.Reject,
1221
+ severity: PeerErrorSeverity.LowToleranceError,
1222
+ });
1223
+ }
1224
+ return this.validateAndStoreCheckpointAttestation(source, attestation);
1225
+ },
1226
+ msgId,
1227
+ source,
1228
+ TopicType.checkpoint_attestation,
1229
+ );
1230
+
1231
+ if (result !== TopicValidatorResult.Accept || !attestation) {
1232
+ return;
1233
+ }
1234
+
1235
+ this.logger.verbose(
1236
+ `Received valid checkpoint attestation for slot ${attestation.slotNumber} from external peer ${source.toString()}`,
1237
+ {
1238
+ p2pMessageIdentifier: await attestation.p2pMessageLoggingIdentifier(),
1239
+ slot: attestation.slotNumber,
1240
+ archive: attestation.archive.toString(),
1241
+ source: source.toString(),
1242
+ },
1243
+ );
1244
+ }
1245
+
1246
+ /** Validates a checkpoint attestation and adds it to the pool. Penalizes the peer if validation fails. */
1247
+ @trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId, attestation) => ({
1248
+ [Attributes.SLOT_NUMBER]: attestation.payload.header.slotNumber.toString(),
1249
+ }))
1250
+ protected async validateAndStoreCheckpointAttestation(
1251
+ peerId: PeerId,
1252
+ attestation: CheckpointAttestation,
1253
+ ): Promise<ReceivedMessageValidationResult<CheckpointAttestation>> {
1254
+ const validationResult = await this.checkpointAttestationValidator.validate(attestation);
1255
+
1256
+ if (validationResult.result === 'reject') {
1257
+ this.logger.warn(`Penalizing peer ${peerId} for checkpoint attestation validation failure`);
1258
+ return { result: TopicValidatorResult.Reject, severity: validationResult.severity };
1259
+ }
1260
+
1261
+ if (validationResult.result === 'ignore') {
1262
+ return { result: TopicValidatorResult.Ignore, obj: attestation };
1263
+ }
1264
+
1265
+ // Try to add the attestation: this handles existence check, cap check, and adding in one call
1266
+ // count is the number of attestations by this signer for this slot (for duplicate detection)
1267
+ const slot = attestation.payload.header.slotNumber;
1268
+ const { added, alreadyExists, count } =
1269
+ await this.mempools.attestationPool.tryAddCheckpointAttestation(attestation);
1270
+
1271
+ this.logger.trace(`Validate propagated checkpoint attestation`, {
1272
+ added,
1273
+ alreadyExists,
1274
+ count,
1275
+ [Attributes.SLOT_NUMBER]: slot.toString(),
1276
+ [Attributes.P2P_ID]: peerId.toString(),
1277
+ });
1278
+
1279
+ // Exact same attestation received, no need to re-broadcast
1280
+ if (alreadyExists) {
1281
+ return { result: TopicValidatorResult.Ignore, obj: attestation };
1282
+ }
1283
+
1284
+ // Could not add (cap reached for signer), penalize and do not re-broadcast
1285
+ if (!added) {
1286
+ this.logger.warn(`Rejecting checkpoint attestation due to cap`, {
1287
+ slot: slot.toString(),
1288
+ archive: attestation.archive.toString(),
1289
+ source: peerId.toString(),
1290
+ attester: attestation.getSender()?.toString(),
1291
+ count,
1292
+ });
1293
+ return { result: TopicValidatorResult.Reject, severity: PeerErrorSeverity.HighToleranceError };
1294
+ }
1295
+
1296
+ // Check if this is a duplicate attestation (signer attested to a different proposal at the same slot)
1297
+ // count is the number of attestations by this signer for this slot
1298
+ if (count === 2) {
1299
+ const attester = attestation.getSender();
1300
+ if (attester) {
1301
+ this.logger.warn(`Detected duplicate attestation (equivocation) at slot ${slot}`, {
1302
+ slot: slot.toString(),
1303
+ archive: attestation.archive.toString(),
1304
+ source: peerId.toString(),
1305
+ attester: attester.toString(),
1306
+ });
1307
+ this.duplicateAttestationCallback?.({ slot, attester });
1308
+ }
1309
+ }
1310
+
1311
+ // Attestation was added successfully - accept it so other nodes can also detect the equivocation
1312
+ this.checkpointAttestationCallback?.(attestation);
1313
+ return { result: TopicValidatorResult.Accept, obj: attestation };
1314
+ }
1315
+
1316
+ protected async processBlockFromPeer(payloadData: Buffer, msgId: string, source: PeerId): Promise<void> {
1317
+ const {
1318
+ result,
1319
+ obj: block,
1320
+ metadata: { isEquivocated, isOversized } = {},
1321
+ } = await this.validateReceivedMessage<BlockProposal, { isEquivocated: boolean; isOversized: boolean }>(
1322
+ () => this.validateAndStoreBlockProposal(source, BlockProposal.fromBuffer(payloadData)),
1323
+ msgId,
1324
+ source,
1325
+ TopicType.block_proposal,
1326
+ );
1327
+
1328
+ // If not accepted, equivocated, or oversized, return. Oversized proposals are re-broadcast as
1329
+ // slashing evidence but never attested or processed.
1330
+ if (result !== TopicValidatorResult.Accept || !block || isEquivocated || isOversized) {
1331
+ return;
1332
+ }
1333
+
1334
+ await this.processValidBlockProposal(ValidatedBlockProposal(block), source);
1335
+ }
1336
+
1337
+ /** Validates a block proposal. Triggers a penalization to the peer that sent it if invalid. Adds to the mempool if valid. */
1338
+ @trackSpan('Libp2pService.validateAndStoreBlockProposal', (_peerId, block) => ({
1339
+ [Attributes.BLOCK_NUMBER]: block.blockNumber.toString(),
1340
+ [Attributes.SLOT_NUMBER]: block.slotNumber.toString(),
1341
+ }))
1342
+ protected async validateAndStoreBlockProposal(
1343
+ peerId: PeerId,
1344
+ block: BlockProposal,
1345
+ ): Promise<ReceivedMessageValidationResult<BlockProposal, { isEquivocated: boolean; isOversized: boolean }>> {
1346
+ const validationResult = await this.blockProposalValidator.validate(block);
1347
+
1348
+ if (validationResult.result === 'reject') {
1349
+ this.logger.warn(`Penalizing peer ${peerId} for block proposal validation failure`);
1350
+ return { result: TopicValidatorResult.Reject, severity: validationResult.severity };
1351
+ }
1352
+
1353
+ if (validationResult.result === 'ignore') {
1354
+ return { result: TopicValidatorResult.Ignore, obj: block };
1355
+ }
1356
+
1357
+ // Try to add the proposal: this handles existence check, cap check, and adding in one call
1358
+ const { added, alreadyExists, count } = await this.mempools.attestationPool.tryAddBlockProposal(block);
1359
+ const isEquivocated = count !== undefined && count > 1;
1360
+ // An oversized proposal (index at or beyond the consensus per-checkpoint limit) is structurally valid
1361
+ // proposer misbehavior: it is stored and re-broadcast as slashing evidence but never processed or
1362
+ // attested to. No-ops when maxBlocksPerCheckpoint is unset (local/test).
1363
+ const isOversized =
1364
+ this.config.maxBlocksPerCheckpoint !== undefined &&
1365
+ block.indexWithinCheckpoint >= this.config.maxBlocksPerCheckpoint;
1366
+
1367
+ // Duplicate proposal received, no need to re-broadcast
1368
+ if (alreadyExists) {
1369
+ this.logger.debug(`Ignoring duplicate block proposal received`, {
1370
+ ...block.toBlockInfo(),
1371
+ indexWithinCheckpoint: block.indexWithinCheckpoint,
1372
+ proposer: block.getSender()?.toString(),
1373
+ source: peerId.toString(),
1374
+ });
1375
+ return { result: TopicValidatorResult.Ignore, obj: block, metadata: { isEquivocated, isOversized } };
1376
+ }
1377
+
1378
+ // Too many blocks received for this slot and index, penalize peer and do not re-broadcast
1379
+ if (!added) {
1380
+ this.logger.warn(`Penalizing peer for block proposal exceeding per-position cap`, {
1381
+ ...block.toBlockInfo(),
1382
+ indexWithinCheckpoint: block.indexWithinCheckpoint,
1383
+ count,
1384
+ proposer: block.getSender()?.toString(),
1385
+ source: peerId.toString(),
1386
+ });
1387
+ return {
1388
+ result: TopicValidatorResult.Reject,
1389
+ metadata: { isEquivocated, isOversized },
1390
+ severity: PeerErrorSeverity.HighToleranceError,
1391
+ };
1392
+ }
1393
+
1394
+ // The proposal was stored: if oversized, invoke the oversized callback so the proposer can be
1395
+ // slashed. Fired alongside (not instead of) equivocation detection below.
1396
+ if (isOversized) {
1397
+ const proposer = block.getSender();
1398
+ if (proposer) {
1399
+ this.logger.warn(`Detected oversized block proposal at slot ${block.slotNumber}`, {
1400
+ ...block.toBlockInfo(),
1401
+ indexWithinCheckpoint: block.indexWithinCheckpoint,
1402
+ maxBlocksPerCheckpoint: this.config.maxBlocksPerCheckpoint,
1403
+ source: peerId.toString(),
1404
+ proposer: proposer.toString(),
1405
+ });
1406
+ this.oversizedProposalCallback?.({ slot: block.slotNumber, proposer });
1407
+ }
1408
+ }
1409
+
1410
+ // If this was a duplicate proposal, do not process it, but do invoke the duplicate callback,
1411
+ // and do re-broadcast it so other nodes in the network know to slash the proposer
1412
+ if (isEquivocated) {
1413
+ const proposer = block.getSender();
1414
+ this.logger.warn(`Detected duplicate block proposal (equivocation) at slot ${block.slotNumber}`, {
1415
+ ...block.toBlockInfo(),
1416
+ source: peerId.toString(),
1417
+ proposer: proposer?.toString(),
1418
+ });
1419
+ // Invoke the duplicate callback on the first duplicate spotted only
1420
+ if (proposer && count === 2) {
1421
+ this.duplicateProposalCallback?.({ slot: block.slotNumber, proposer, type: 'block' });
1422
+ }
1423
+ return { result: TopicValidatorResult.Accept, obj: block, metadata: { isEquivocated, isOversized } };
1424
+ }
1425
+
1426
+ // Otherwise, we're good to go!
1427
+ return { result: TopicValidatorResult.Accept, obj: block, metadata: { isEquivocated: false, isOversized } };
1428
+ }
1429
+
1430
+ // REFACTOR(palla): This method should be moved to the p2p_client or to a separate component,
1431
+ // should not be here as it does not deal with p2p networking.
1432
+ @trackSpan('Libp2pService.processValidBlockProposal', async block => ({
1433
+ [Attributes.SLOT_NUMBER]: block.slotNumber,
1434
+ [Attributes.BLOCK_ARCHIVE]: block.archive.toString(),
1435
+ [Attributes.P2P_ID]: await block.p2pMessageLoggingIdentifier().then(i => i.toString()),
1436
+ }))
1437
+ protected async processValidBlockProposal(block: ValidatedBlockProposal, sender: PeerId) {
1438
+ const slot = block.slotNumber;
1439
+ this.logger.verbose(`Received block proposal for slot ${slot} from external peer ${sender.toString()}.`, {
1440
+ p2pMessageIdentifier: await block.p2pMessageLoggingIdentifier(),
1441
+ source: sender.toString(),
1442
+ ...block.toBlockInfo(),
1443
+ });
1444
+
1445
+ // Mark the txs in this proposal as protected
1446
+ await this.mempools.txPool.protectTxs(block.txHashes, block.blockHeader);
1447
+
1448
+ if (!(await this.tryBlockReceivedCallback(block, sender))) {
1449
+ // Release the protections this proposal created so its txs return to pending. Only entries still
1450
+ // keyed to this slot are cleared, so a tx referenced by a live proposal at another slot stays protected.
1451
+ await this.mempools.txPool.unprotectTxs(block.txHashes, slot);
1452
+ }
1453
+ }
1454
+
1455
+ /**
1456
+ * Runs the block received callback to validate a proposal, and returns whether it was accepted.
1457
+ * A callback that throws is reported as a rejection: the proposal is no more usable than one explicitly
1458
+ * rejected, and letting the error escape would leave the proposal's tx protections in place.
1459
+ * Note: Validators do NOT attest to individual blocks, only to checkpoint proposals.
1460
+ */
1461
+ private async tryBlockReceivedCallback(block: ValidatedBlockProposal, sender: PeerId): Promise<boolean> {
1462
+ try {
1463
+ const isValid = await this.blockReceivedCallback(block, sender);
1464
+ if (!isValid) {
1465
+ this.logger.info(`Block proposal validation failed for block ${block.blockNumber}`, block.toBlockInfo());
1466
+ }
1467
+ return isValid;
1468
+ } catch (err) {
1469
+ this.logger.error(`Error validating block proposal for block ${block.blockNumber}`, err, block.toBlockInfo());
1470
+ return false;
1471
+ }
1472
+ }
1473
+
1474
+ /**
1475
+ * Handle a gossiped checkpoint proposal.
1476
+ * Validates and processes the checkpoint proposal, then triggers the callback for attestation.
1477
+ */
1478
+ protected async handleGossipedCheckpointProposal(payloadData: Buffer, msgId: string, source: PeerId): Promise<void> {
1479
+ const {
1480
+ result,
1481
+ obj: checkpoint,
1482
+ metadata: { isEquivocated, processBlock, isOversized } = {},
1483
+ } = await this.validateReceivedMessage<
1484
+ CheckpointProposal,
1485
+ { isEquivocated: boolean; processBlock: boolean; isOversized: boolean }
1486
+ >(
1487
+ () => this.validateAndStoreCheckpointProposal(source, CheckpointProposal.fromBuffer(payloadData)),
1488
+ msgId,
1489
+ source,
1490
+ TopicType.checkpoint_proposal,
1491
+ );
1492
+
1493
+ // An oversized checkpoint is re-broadcast as slashing evidence but never attested or processed.
1494
+ // Process checkpoint proposal if valid and neither equivocated nor oversized.
1495
+ const processCheckpointFn = () =>
1496
+ result === TopicValidatorResult.Accept && checkpoint && !isEquivocated && !isOversized
1497
+ ? this.processValidCheckpointProposal(ValidatedCheckpointProposalCore(checkpoint.toCore()), source)
1498
+ : Promise.resolve();
1499
+
1500
+ // If the checkpoint contained a valid last block, we process it even if the checkpoint itself is to be rejected
1501
+ // TODO(palla/mbps): Is this ok? Should we be considering a block from a checkpoint that was equivocated?
1502
+ const processBlockFn = () =>
1503
+ processBlock && checkpoint && checkpoint.getBlockProposal()
1504
+ ? this.processValidBlockProposal(ValidatedBlockProposal(checkpoint.getBlockProposal()!), source)
1505
+ : Promise.resolve();
1506
+
1507
+ // A node that skips checkpoint validation attests without re-executing the embedded last block, so run
1508
+ // the checkpoint callback first: this creates and broadcasts the attestation before the block is
1509
+ // processed. Otherwise the block's re-execution — which can stall until the re-execution deadline
1510
+ // waiting for a parent that may never arrive — would delay the attestation past the slot's attestation
1511
+ // window, after which peers reject it as stale.
1512
+ if (this.config.skipCheckpointProposalValidation) {
1513
+ await processCheckpointFn();
1514
+ await processBlockFn();
1515
+ return;
1516
+ }
1517
+
1518
+ // Process the block first, since it's required for the checkpoint proposal validation.
1519
+ await processBlockFn();
1520
+ await processCheckpointFn();
1521
+ }
1522
+
1523
+ /**
1524
+ * Validates a checkpoint proposal. Penalizes peer if validation fails. Adds the checkpoint and
1525
+ * its last block (if present) to the mempool if valid. Triggers equivocation detection on both.
1526
+ */
1527
+ @trackSpan('Libp2pService.validateAndStoreCheckpointProposal', (_peerId, checkpoint) => ({
1528
+ [Attributes.SLOT_NUMBER]: checkpoint.slotNumber.toString(),
1529
+ }))
1530
+ protected async validateAndStoreCheckpointProposal(
1531
+ peerId: PeerId,
1532
+ checkpoint: CheckpointProposal,
1533
+ ): Promise<
1534
+ ReceivedMessageValidationResult<
1535
+ CheckpointProposal,
1536
+ { isEquivocated: boolean; processBlock: boolean; isOversized: boolean }
1537
+ >
1538
+ > {
1539
+ const validationResult = await this.checkpointProposalValidator.validate(checkpoint);
1540
+
1541
+ if (validationResult.result === 'reject') {
1542
+ this.logger.warn(`Penalizing peer ${peerId} for checkpoint proposal validation failure`);
1543
+ return { result: TopicValidatorResult.Reject, severity: validationResult.severity };
1544
+ }
1545
+
1546
+ if (validationResult.result === 'ignore') {
1547
+ return { result: TopicValidatorResult.Ignore, obj: checkpoint };
1548
+ }
1549
+
1550
+ // Extract and try to add the block proposal first if present
1551
+ const blockProposal = checkpoint.getBlockProposal();
1552
+ let processBlock = false;
1553
+ let isOversized = false;
1554
+ if (blockProposal) {
1555
+ this.logger.debug(`Validating block proposal from propagated checkpoint`, {
1556
+ [Attributes.SLOT_NUMBER]: checkpoint.slotNumber.toString(),
1557
+ [Attributes.P2P_ID]: peerId.toString(),
1558
+ });
1559
+ const blockProposalResult = await this.validateAndStoreBlockProposal(peerId, blockProposal);
1560
+ const { obj, metadata: { isEquivocated, isOversized: blockIsOversized } = {} } = blockProposalResult;
1561
+ isOversized = blockIsOversized ?? false;
1562
+
1563
+ if (blockProposalResult.result === TopicValidatorResult.Reject || !obj || isEquivocated) {
1564
+ this.logger.debug(`Rejecting checkpoint due to invalid last block proposal`, {
1565
+ [Attributes.SLOT_NUMBER]: checkpoint.slotNumber.toString(),
1566
+ [Attributes.P2P_ID]: peerId.toString(),
1567
+ isEquivocated,
1568
+ result: blockProposalResult.result,
1569
+ });
1570
+ return {
1571
+ result: TopicValidatorResult.Reject,
1572
+ severity:
1573
+ 'severity' in blockProposalResult ? blockProposalResult.severity : PeerErrorSeverity.MidToleranceError,
1574
+ };
1575
+ } else if (blockProposalResult.result === TopicValidatorResult.Accept && obj && !isEquivocated && !isOversized) {
1576
+ // An oversized terminal block is re-broadcast as slashing evidence but never processed.
1577
+ processBlock = true;
1578
+ }
1579
+ }
1580
+
1581
+ // Try to add the checkpoint proposal core: this handles existence check, cap check, and adding in one call
1582
+ const checkpointCore = checkpoint.toCore();
1583
+ const tryAddResult = await this.mempools.attestationPool.tryAddCheckpointProposal(checkpointCore);
1584
+ const { added, alreadyExists, count } = tryAddResult;
1585
+ const isEquivocated = count !== undefined && count > 1;
1586
+
1587
+ // Duplicate proposal received, do not re-broadcast
1588
+ if (alreadyExists) {
1589
+ this.logger.debug(`Ignoring duplicate checkpoint proposal received`, {
1590
+ ...checkpoint.toCheckpointInfo(),
1591
+ source: peerId.toString(),
1592
+ });
1593
+ return {
1594
+ result: TopicValidatorResult.Ignore,
1595
+ obj: checkpoint,
1596
+ metadata: { isEquivocated, processBlock, isOversized },
1597
+ };
1598
+ }
1599
+
1600
+ // Too many checkpoint proposals received for this slot, penalize peer and do not re-broadcast.
1601
+ // Note: We still return the checkpoint obj so the lastBlock can be processed if valid
1602
+ if (!added) {
1603
+ this.logger.warn(`Penalizing peer for checkpoint proposal exceeding per-slot cap`, {
1604
+ ...checkpoint.toCheckpointInfo(),
1605
+ count,
1606
+ source: peerId.toString(),
1607
+ });
1608
+ return {
1609
+ result: TopicValidatorResult.Reject,
1610
+ obj: checkpoint,
1611
+ metadata: { isEquivocated, processBlock, isOversized },
1612
+ severity: PeerErrorSeverity.HighToleranceError,
1613
+ };
1614
+ }
1615
+
1616
+ // If this was a duplicate proposal, do not process it, but do invoke the duplicate callback,
1617
+ // and do re-broadcast it so other nodes in the network know to slash the proposer
1618
+ if (isEquivocated) {
1619
+ const proposer = checkpoint.getSender();
1620
+ this.logger.warn(`Detected duplicate checkpoint proposal (equivocation) at slot ${checkpoint.slotNumber}`, {
1621
+ ...checkpoint.toCheckpointInfo(),
1622
+ source: peerId.toString(),
1623
+ proposer: proposer?.toString(),
1624
+ });
1625
+ // Invoke the duplicate callback on the first duplicate spotted only
1626
+ if (proposer && count === 2) {
1627
+ this.duplicateProposalCallback?.({ slot: checkpoint.slotNumber, proposer, type: 'checkpoint' });
1628
+ }
1629
+ return {
1630
+ result: TopicValidatorResult.Accept,
1631
+ obj: checkpoint,
1632
+ metadata: { isEquivocated, processBlock, isOversized },
1633
+ };
1634
+ }
1635
+
1636
+ // Otherwise, we're good to go!
1637
+ return {
1638
+ result: TopicValidatorResult.Accept,
1639
+ obj: checkpoint,
1640
+ metadata: { processBlock, isEquivocated, isOversized },
1641
+ };
1642
+ }
1643
+
1644
+ /**
1645
+ * Process a validated checkpoint proposal.
1646
+ * Note: The proposal was already added to the pool by tryAddCheckpointProposal in handleGossipedCheckpointProposal.
1647
+ */
1648
+ @trackSpan('Libp2pService.processValidCheckpointProposal', async checkpoint => ({
1649
+ [Attributes.SLOT_NUMBER]: checkpoint.slotNumber,
1650
+ [Attributes.BLOCK_ARCHIVE]: checkpoint.archive.toString(),
1651
+ [Attributes.P2P_ID]: await checkpoint.p2pMessageLoggingIdentifier().then(i => i.toString()),
1652
+ }))
1653
+ protected async processValidCheckpointProposal(checkpoint: ValidatedCheckpointProposalCore, sender: PeerId) {
1654
+ const slot = checkpoint.slotNumber;
1655
+ this.logger.verbose(`Received checkpoint proposal for slot ${slot} from external peer ${sender.toString()}.`, {
1656
+ p2pMessageIdentifier: await checkpoint.p2pMessageLoggingIdentifier(),
1657
+ slot: checkpoint.slotNumber,
1658
+ archive: checkpoint.archive.toString(),
1659
+ source: sender.toString(),
1660
+ });
1661
+
1662
+ await this.allNodesCheckpointReceivedCallback(checkpoint, sender);
1663
+
1664
+ // Call the checkpoint received callback with the core version (without lastBlock)
1665
+ // to validate and potentially generate attestations
1666
+ const attestations = await this.validatorCheckpointReceivedCallback(checkpoint, sender);
1667
+ if (attestations && attestations.length > 0) {
1668
+ // If the callback returned attestations, add them to the pool and propagate them
1669
+ await this.mempools.attestationPool.addOwnCheckpointAttestations(attestations);
1670
+ for (const attestation of attestations) {
1671
+ await this.propagate(attestation);
1672
+ }
1673
+ }
1674
+ }
1675
+
1676
+ /**
1677
+ * Propagates provided message to peers.
1678
+ * @param message - The message to propagate.
1679
+ */
1680
+ public async propagate<T extends Gossipable>(message: T) {
1681
+ const p2pMessageIdentifier = await message.p2pMessageLoggingIdentifier();
1682
+ this.logger.trace(`Message ${p2pMessageIdentifier} queued`, { p2pMessageIdentifier });
1683
+ void this.sendToPeers(message).catch(error => {
1684
+ this.logger.error(`Error propagating message ${p2pMessageIdentifier}`, { error });
1685
+ });
1686
+ }
1687
+
1688
+ /**
1689
+ * Validate the requested block transactions request-response consistency.
1690
+ * It does NOT validate the transactions themselves.
1691
+ * @param request - The block transactions request.
1692
+ * @param response - The block transactions response.
1693
+ * @param peerId - The ID of the peer that made the request.
1694
+ * @returns True if the request-response is consistent, false otherwise.
1695
+ */
1696
+ @trackSpan('Libp2pService.validateRequestedBlockTxsConsistency', request => ({
1697
+ [Attributes.BLOCK_ARCHIVE]: request.archiveRoot.toString(),
1698
+ }))
1699
+ protected async validateRequestedBlockTxsConsistency(
1700
+ request: BlockTxsRequest,
1701
+ response: BlockTxsResponse,
1702
+ peerId: PeerId,
1703
+ ): Promise<boolean> {
1704
+ try {
1705
+ // Check for duplicates txs (or hashes) in the response.
1706
+ const returnedHashes = response.txs.map(tx => tx.getTxHash().toString());
1707
+ const uniqueReturned = new Set(returnedHashes.map(h => h.toString()));
1708
+ if (uniqueReturned.size !== returnedHashes.length) {
1709
+ this.peerManager.penalizePeer(peerId, PeerErrorSeverity.MidToleranceError);
1710
+ throw new ValidationError(`Received duplicate txs in block txs response`);
1711
+ }
1712
+
1713
+ // We get the block tx hashes from the proposal or the archiver.
1714
+ const proposal = await this.mempools.attestationPool.getBlockProposalByArchive(request.archiveRoot.toString());
1715
+ const blockTxHashes =
1716
+ proposal?.txHashes ??
1717
+ (await this.archiver.getBlock({ archive: request.archiveRoot }))?.body.txEffects.map(e => e.txHash);
1718
+
1719
+ // If we don't have the block, we can't verify membership/order of the returned txs.
1720
+ if (!blockTxHashes) {
1721
+ // This shouldn't happen, since we asked for the block (proposal).
1722
+ // Neither a local proposal nor an archived block: we cannot verify membership/order of the
1723
+ // returned txs. This is a local-state gap, not a peer fault, so we do not penalize.
1724
+ this.logger.warn(
1725
+ `Block ${request.archiveRoot.toString()} not found in attestation pool or archiver; cannot validate membership/order of returned txs`,
1726
+ );
1727
+ // NOTE: We mark the response as invalid, given the limitations of a true/false return value.
1728
+ return false;
1729
+ }
1730
+
1731
+ // Verify that the returned tx hashes are a subset of (tx hashes by index) U (explicitly requested tx hashes).
1732
+ const uniqueRequestedHashes = new Set([
1733
+ // tx hashes requested by index.
1734
+ ...request.txIndices.getTrueIndices().map(i => blockTxHashes[i].toString()),
1735
+ // explicitly requested tx hashes.
1736
+ ...request.txHashes.map(h => h.toString()),
1737
+ ]);
1738
+ if (!returnedHashes.every(h => uniqueRequestedHashes.has(h))) {
1739
+ this.peerManager.penalizePeer(peerId, PeerErrorSeverity.LowToleranceError);
1740
+ throw new ValidationError(
1741
+ 'Returned txs should be a subset of (tx hashes by index) U (explicitly requested tx hashes)',
1742
+ );
1743
+ }
1744
+
1745
+ // Tx indices information is optional, but if present, we need to verify a few things.
1746
+ if (!response.peerHasBlock()) {
1747
+ this.logger.debug(`Peer ${peerId.toString()} signalled missing block`);
1748
+ return true;
1749
+ }
1750
+
1751
+ // If the response has a non-empty bitvector, it needs to be consistent with the number of txs in the block.
1752
+ if (response.txIndices.getLength() !== blockTxHashes.length) {
1753
+ this.peerManager.penalizePeer(peerId, PeerErrorSeverity.MidToleranceError);
1754
+ throw new ValidationError(
1755
+ `Received block txs with mismatched bitvector length: expected ${blockTxHashes.length}, got ${response.txIndices.getLength()}`,
1756
+ );
1757
+ }
1758
+
1759
+ // For every index we requested that the peer claims to have (per its bitvector), the
1760
+ // corresponding tx must be present in the response. A peer advertising availability but
1761
+ // withholding the tx is inconsistent.
1762
+ const returnedHashSet = new Set(returnedHashes);
1763
+ const expectedIndices = request.txIndices.getTrueIndices().filter(i => response.txIndices.isSet(i));
1764
+ const missingExpected = expectedIndices.some(i => !returnedHashSet.has(blockTxHashes[i].toString()));
1765
+ if (missingExpected) {
1766
+ this.peerManager.penalizePeer(peerId, PeerErrorSeverity.LowToleranceError);
1767
+ throw new ValidationError('Peer advertised requested txs via indices but did not return them');
1768
+ }
1769
+
1770
+ return true;
1771
+ } catch (e: any) {
1772
+ if (e instanceof ValidationError) {
1773
+ this.logger.warn(`Failed validation for requested block txs from peer ${peerId.toString()}`);
1774
+ } else {
1775
+ this.logger.error(`Error during validation of requested block txs`, e);
1776
+ }
1777
+
1778
+ return false;
1779
+ }
1780
+ }
1781
+
1782
+ private getGasFees(): Promise<GasFees> {
1783
+ return this.blockMinFeesProvider.getCurrentMinFees();
1784
+ }
1785
+
1786
+ /**
1787
+ * Get the BatchTxRequesterLibP2PService dependencies for creating BatchTxRequester instances
1788
+ */
1789
+ public getBatchTxRequesterService(): BatchTxRequesterLibP2PService {
1790
+ return {
1791
+ reqResp: this.reqresp,
1792
+ connectionSampler: this.reqresp.getConnectionSampler(),
1793
+ txValidatorConfig: {
1794
+ l1ChainId: this.config.l1ChainId,
1795
+ rollupVersion: this.config.rollupVersion,
1796
+ proofVerifier: this.proofVerifier,
1797
+ txValidationCache: this.txValidationCache,
1798
+ },
1799
+ peerScoring: this.peerManager,
1800
+ validateRequestedBlockTxsConsistency: this.validateRequestedBlockTxsConsistency.bind(this),
1801
+ };
1802
+ }
1803
+
1804
+ public async validateTxsReceivedInBlockProposal(txs: Tx[]): Promise<void> {
1805
+ const validator = createTxValidatorForBlockProposalReceivedTxs(
1806
+ this.proofVerifier,
1807
+ { l1ChainId: this.config.l1ChainId, rollupVersion: this.config.rollupVersion },
1808
+ this.logger.getBindings(),
1809
+ this.txValidationCache,
1810
+ );
1811
+
1812
+ const results = await Promise.all(
1813
+ txs.map(async tx => ({ txHash: tx.getTxHash(), result: await validator.validateTx(tx) })),
1814
+ );
1815
+
1816
+ const invalidTxs = results.flatMap(({ txHash, result }) =>
1817
+ result.result === 'invalid' ? [{ txHash, reasons: result.reason }] : [],
1818
+ );
1819
+
1820
+ if (invalidTxs.length > 0) {
1821
+ throw new InvalidBlockProposalTxsError(invalidTxs);
1822
+ }
1823
+ }
1824
+
1825
+ /** Creates the first stage (fast) validators for gossiped transactions. */
1826
+ protected async createFirstStageMessageValidators(
1827
+ currentBlockNumber: BlockNumber,
1828
+ nextSlotTimestamp: UInt64,
1829
+ ): Promise<Record<string, TransactionValidator>> {
1830
+ const gasFees = await this.getGasFees();
1831
+ const allowedInSetup = [
1832
+ ...(await getDefaultAllowedSetupFunctions()),
1833
+ ...(this.config.txPublicSetupAllowListExtend ?? []),
1834
+ ];
1835
+ const blockNumber = BlockNumber(currentBlockNumber + 1);
1836
+ const l1Constants = await this.archiver.getL1Constants();
1837
+ const networkTxGasLimits = getNetworkTxGasLimits(this.config, l1Constants);
1838
+
1839
+ return createFirstStageTxValidationsForGossipedTransactions(
1840
+ nextSlotTimestamp,
1841
+ blockNumber,
1842
+ this.worldStateSynchronizer,
1843
+ gasFees,
1844
+ this.config.l1ChainId,
1845
+ this.config.rollupVersion,
1846
+ protocolContractsHash,
1847
+ this.archiver,
1848
+ !this.config.disableTransactions,
1849
+ allowedInSetup,
1850
+ this.logger.getBindings(),
1851
+ {
1852
+ maxTxL2Gas: networkTxGasLimits.l2Gas,
1853
+ maxTxDAGas: networkTxGasLimits.daGas,
1854
+ },
1855
+ );
1856
+ }
1857
+
1858
+ /** Creates the second stage (expensive proof verification) validators for gossiped transactions. */
1859
+ protected createSecondStageMessageValidators(): Record<string, TransactionValidator> {
1860
+ return createSecondStageTxValidationsForGossipedTransactions(this.proofVerifier, this.logger.getBindings());
1861
+ }
1862
+
1863
+ /**
1864
+ * Run validations on a tx.
1865
+ * @param tx - The tx to validate.
1866
+ * @param messageValidators - The message validators to run.
1867
+ * @returns The validation outcome.
1868
+ */
1869
+ private async runValidations(
1870
+ tx: Tx,
1871
+ messageValidators: Record<string, TransactionValidator>,
1872
+ ): Promise<ValidationOutcome> {
1873
+ // Gossip validation stays exhaustive within each stage because peer scoring uses the harshest failure severity;
1874
+ // failing fast would make the penalty depend on validator order. The stage boundaries themselves fail fast.
1875
+ const validationPromises = Object.entries(messageValidators).map(async ([name, { validator, severity }]) => {
1876
+ const { result } = await validator.validateTx(tx);
1877
+ return { name, isValid: result !== 'invalid', severity };
1878
+ });
1879
+
1880
+ // A promise that resolves when all validations have been run
1881
+ const allValidations = await Promise.all(validationPromises);
1882
+ const failures = allValidations.filter(x => !x.isValid);
1883
+ if (failures.length > 0) {
1884
+ // Pick the most severe failure (lowest tolerance = harshest penalty)
1885
+ const failed = maxBy(failures, f => PeerErrorSeverityByHarshness.indexOf(f.severity))!;
1886
+ return {
1887
+ allPassed: false,
1888
+ failure: {
1889
+ isValid: { result: 'invalid' as const, reason: ['Failed validation'] },
1890
+ name: failed.name,
1891
+ severity: failed.severity,
1892
+ },
1893
+ };
1894
+ } else {
1895
+ return {
1896
+ allPassed: true,
1897
+ };
1898
+ }
1899
+ }
1900
+
1901
+ /**
1902
+ * Handle a double spend failure.
1903
+ *
1904
+ * Double spend failures are managed on their own because they are a special case.
1905
+ * We must check if the double spend is recent or old, if it is past a threshold, then we heavily penalize the peer.
1906
+ *
1907
+ * @param tx - The tx that failed the double spend validator.
1908
+ * @param blockNumber - The block number of the tx.
1909
+ * @param peerId - The peer ID of the peer that sent the tx.
1910
+ * @returns Severity
1911
+ */
1912
+ private async handleDoubleSpendFailure(tx: Tx, blockNumber: BlockNumber): Promise<PeerErrorSeverity> {
1913
+ if (blockNumber <= this.config.doubleSpendSeverePeerPenaltyWindow) {
1914
+ return PeerErrorSeverity.HighToleranceError;
1915
+ }
1916
+
1917
+ const snapshotValidator = new DoubleSpendTxValidator(
1918
+ {
1919
+ nullifiersExist: async (nullifiers: Buffer[]) => {
1920
+ const merkleTree = this.worldStateSynchronizer.getSnapshot(
1921
+ BlockNumber(blockNumber - this.config.doubleSpendSeverePeerPenaltyWindow),
1922
+ );
1923
+ const indices = await merkleTree.findLeafIndices(MerkleTreeId.NULLIFIER_TREE, nullifiers);
1924
+ return indices.map(index => index !== undefined);
1925
+ },
1926
+ },
1927
+ this.logger.getBindings(),
1928
+ );
1929
+
1930
+ const validSnapshot = await snapshotValidator.validateTx(tx);
1931
+ if (validSnapshot.result !== 'valid') {
1932
+ return PeerErrorSeverity.LowToleranceError;
1933
+ }
1934
+
1935
+ return PeerErrorSeverity.HighToleranceError;
1936
+ }
1937
+
1938
+ public getPeerScore(peerId: PeerId): number {
1939
+ return this.node.services.pubsub.score.score(peerId.toString());
1940
+ }
1941
+
1942
+ public handleAuthRequestFromPeer(authRequest: AuthRequest, peerId: PeerId): Promise<StatusMessage> {
1943
+ return this.peerManager.handleAuthRequestFromPeer(authRequest, peerId);
1944
+ }
1945
+
1946
+ private async sendToPeers<T extends Gossipable>(message: T) {
1947
+ const parent = message.constructor as typeof Gossipable;
1948
+
1949
+ const identifier = await message.p2pMessageLoggingIdentifier().then(i => i.toString());
1950
+ this.logger.trace(`Sending message ${identifier}`, { p2pMessageIdentifier: identifier });
1951
+
1952
+ const recipientsNum = await this.publishToTopic(this.topicStrings[parent.p2pTopic], message);
1953
+ this.logger.debug(`Sent message ${identifier} to ${recipientsNum} peers`, {
1954
+ p2pMessageIdentifier: identifier,
1955
+ sourcePeer: this.node.peerId.toString(),
1956
+ });
1957
+ }
1958
+
1959
+ // Libp2p seems to hang sometimes if new peers are initiating connections.
1960
+ private async stopLibP2P() {
1961
+ const TIMEOUT_MS = 5000; // 5 seconds timeout
1962
+ const timeout = new Promise((_resolve, reject) => {
1963
+ setTimeout(() => reject(new Error('Timeout during libp2p.stop()')), TIMEOUT_MS);
1964
+ });
1965
+ try {
1966
+ await Promise.race([this.node.stop(), timeout]);
1967
+ this.logger.debug('LibP2P stopped');
1968
+ } catch (error) {
1969
+ this.logger.error('Error during stop or timeout:', error);
1970
+ }
1971
+ }
1972
+ }