@aztec/p2p 0.0.0-test.1 → 0.0.1-commit.017a351

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 (633) hide show
  1. package/README.md +129 -3
  2. package/dest/bootstrap/bootstrap.d.ts +4 -3
  3. package/dest/bootstrap/bootstrap.d.ts.map +1 -1
  4. package/dest/bootstrap/bootstrap.js +34 -13
  5. package/dest/client/factory.d.ts +23 -12
  6. package/dest/client/factory.d.ts.map +1 -1
  7. package/dest/client/factory.js +106 -26
  8. package/dest/client/index.d.ts +2 -1
  9. package/dest/client/index.d.ts.map +1 -1
  10. package/dest/client/index.js +1 -0
  11. package/dest/client/interface.d.ts +192 -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 +97 -221
  15. package/dest/client/p2p_client.d.ts.map +1 -1
  16. package/dest/client/p2p_client.js +818 -289
  17. package/dest/config.d.ts +235 -133
  18. package/dest/config.d.ts.map +1 -1
  19. package/dest/config.js +295 -36
  20. package/dest/enr/generate-enr.d.ts +11 -3
  21. package/dest/enr/generate-enr.d.ts.map +1 -1
  22. package/dest/enr/generate-enr.js +27 -5
  23. package/dest/enr/index.d.ts +1 -1
  24. package/dest/errors/attestation-pool.error.d.ts +7 -0
  25. package/dest/errors/attestation-pool.error.d.ts.map +1 -0
  26. package/dest/errors/attestation-pool.error.js +12 -0
  27. package/dest/errors/p2p-service.error.d.ts +9 -0
  28. package/dest/errors/p2p-service.error.d.ts.map +1 -0
  29. package/dest/errors/p2p-service.error.js +10 -0
  30. package/dest/errors/reqresp.error.d.ts +1 -20
  31. package/dest/errors/reqresp.error.d.ts.map +1 -1
  32. package/dest/errors/reqresp.error.js +0 -21
  33. package/dest/errors/tx-pool.error.d.ts +8 -0
  34. package/dest/errors/tx-pool.error.d.ts.map +1 -0
  35. package/dest/errors/tx-pool.error.js +9 -0
  36. package/dest/index.d.ts +5 -2
  37. package/dest/index.d.ts.map +1 -1
  38. package/dest/index.js +3 -1
  39. package/dest/mem_pools/attestation_pool/attestation_pool.d.ts +165 -30
  40. package/dest/mem_pools/attestation_pool/attestation_pool.d.ts.map +1 -1
  41. package/dest/mem_pools/attestation_pool/attestation_pool.js +511 -3
  42. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.d.ts +2 -2
  43. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.d.ts.map +1 -1
  44. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.js +680 -173
  45. package/dest/mem_pools/attestation_pool/index.d.ts +2 -3
  46. package/dest/mem_pools/attestation_pool/index.d.ts.map +1 -1
  47. package/dest/mem_pools/attestation_pool/index.js +1 -2
  48. package/dest/mem_pools/attestation_pool/mocks.d.ts +234 -11
  49. package/dest/mem_pools/attestation_pool/mocks.d.ts.map +1 -1
  50. package/dest/mem_pools/attestation_pool/mocks.js +21 -21
  51. package/dest/mem_pools/index.d.ts +3 -3
  52. package/dest/mem_pools/index.d.ts.map +1 -1
  53. package/dest/mem_pools/index.js +1 -1
  54. package/dest/mem_pools/instrumentation.d.ts +18 -12
  55. package/dest/mem_pools/instrumentation.d.ts.map +1 -1
  56. package/dest/mem_pools/instrumentation.js +74 -41
  57. package/dest/mem_pools/interface.d.ts +6 -7
  58. package/dest/mem_pools/interface.d.ts.map +1 -1
  59. package/dest/mem_pools/tx_pool_v2/archive/index.d.ts +2 -0
  60. package/dest/mem_pools/tx_pool_v2/archive/index.d.ts.map +1 -0
  61. package/dest/mem_pools/tx_pool_v2/archive/index.js +1 -0
  62. package/dest/mem_pools/tx_pool_v2/archive/tx_archive.d.ts +39 -0
  63. package/dest/mem_pools/tx_pool_v2/archive/tx_archive.d.ts.map +1 -0
  64. package/dest/mem_pools/tx_pool_v2/archive/tx_archive.js +97 -0
  65. package/dest/mem_pools/tx_pool_v2/deleted_pool.d.ts +104 -0
  66. package/dest/mem_pools/tx_pool_v2/deleted_pool.d.ts.map +1 -0
  67. package/dest/mem_pools/tx_pool_v2/deleted_pool.js +251 -0
  68. package/dest/mem_pools/tx_pool_v2/eviction/eviction_manager.d.ts +47 -0
  69. package/dest/mem_pools/tx_pool_v2/eviction/eviction_manager.d.ts.map +1 -0
  70. package/dest/mem_pools/tx_pool_v2/eviction/eviction_manager.js +128 -0
  71. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.d.ts +17 -0
  72. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.d.ts.map +1 -0
  73. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.js +94 -0
  74. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.d.ts +19 -0
  75. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.d.ts.map +1 -0
  76. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.js +97 -0
  77. package/dest/mem_pools/tx_pool_v2/eviction/index.d.ts +11 -0
  78. package/dest/mem_pools/tx_pool_v2/eviction/index.d.ts.map +1 -0
  79. package/dest/mem_pools/tx_pool_v2/eviction/index.js +12 -0
  80. package/dest/mem_pools/tx_pool_v2/eviction/insufficient_fee_per_gas_eviction_rule.d.ts +16 -0
  81. package/dest/mem_pools/tx_pool_v2/eviction/insufficient_fee_per_gas_eviction_rule.d.ts.map +1 -0
  82. package/dest/mem_pools/tx_pool_v2/eviction/insufficient_fee_per_gas_eviction_rule.js +62 -0
  83. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.d.ts +180 -0
  84. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.d.ts.map +1 -0
  85. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.js +25 -0
  86. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.d.ts +15 -0
  87. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.d.ts.map +1 -0
  88. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.js +65 -0
  89. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.d.ts +17 -0
  90. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.d.ts.map +1 -0
  91. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.js +93 -0
  92. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.d.ts +16 -0
  93. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.d.ts.map +1 -0
  94. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.js +78 -0
  95. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.d.ts +20 -0
  96. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.d.ts.map +1 -0
  97. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.js +75 -0
  98. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.d.ts +15 -0
  99. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.d.ts.map +1 -0
  100. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.js +19 -0
  101. package/dest/mem_pools/tx_pool_v2/index.d.ts +6 -0
  102. package/dest/mem_pools/tx_pool_v2/index.d.ts.map +1 -0
  103. package/dest/mem_pools/tx_pool_v2/index.js +5 -0
  104. package/dest/mem_pools/tx_pool_v2/instrumentation.d.ts +15 -0
  105. package/dest/mem_pools/tx_pool_v2/instrumentation.d.ts.map +1 -0
  106. package/dest/mem_pools/tx_pool_v2/instrumentation.js +43 -0
  107. package/dest/mem_pools/tx_pool_v2/interfaces.d.ts +218 -0
  108. package/dest/mem_pools/tx_pool_v2/interfaces.d.ts.map +1 -0
  109. package/dest/mem_pools/tx_pool_v2/interfaces.js +10 -0
  110. package/dest/mem_pools/tx_pool_v2/tx_metadata.d.ts +137 -0
  111. package/dest/mem_pools/tx_pool_v2/tx_metadata.d.ts.map +1 -0
  112. package/dest/mem_pools/tx_pool_v2/tx_metadata.js +223 -0
  113. package/dest/mem_pools/tx_pool_v2/tx_pool_bench_metrics.d.ts +26 -0
  114. package/dest/mem_pools/tx_pool_v2/tx_pool_bench_metrics.d.ts.map +1 -0
  115. package/dest/mem_pools/tx_pool_v2/tx_pool_bench_metrics.js +70 -0
  116. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.d.ts +108 -0
  117. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.d.ts.map +1 -0
  118. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.js +337 -0
  119. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.d.ts +62 -0
  120. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.d.ts.map +1 -0
  121. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.js +167 -0
  122. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.d.ts +78 -0
  123. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.d.ts.map +1 -0
  124. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.js +914 -0
  125. package/dest/msg_validators/attestation_validator/attestation_validator.d.ts +14 -6
  126. package/dest/msg_validators/attestation_validator/attestation_validator.d.ts.map +1 -1
  127. package/dest/msg_validators/attestation_validator/attestation_validator.js +106 -12
  128. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.d.ts +24 -0
  129. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.d.ts.map +1 -0
  130. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.js +75 -0
  131. package/dest/msg_validators/attestation_validator/index.d.ts +2 -1
  132. package/dest/msg_validators/attestation_validator/index.d.ts.map +1 -1
  133. package/dest/msg_validators/attestation_validator/index.js +1 -0
  134. package/dest/msg_validators/clock_tolerance.d.ts +32 -0
  135. package/dest/msg_validators/clock_tolerance.d.ts.map +1 -0
  136. package/dest/msg_validators/clock_tolerance.js +90 -0
  137. package/dest/msg_validators/index.d.ts +2 -2
  138. package/dest/msg_validators/index.d.ts.map +1 -1
  139. package/dest/msg_validators/index.js +1 -1
  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 +15 -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 +15 -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 +20 -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 +26 -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 +150 -0
  155. package/dest/msg_validators/tx_validator/aggregate_tx_validator.d.ts +4 -4
  156. package/dest/msg_validators/tx_validator/aggregate_tx_validator.d.ts.map +1 -1
  157. package/dest/msg_validators/tx_validator/aggregate_tx_validator.js +11 -18
  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 +20 -6
  168. package/dest/msg_validators/tx_validator/block_header_validator.d.ts.map +1 -1
  169. package/dest/msg_validators/tx_validator/block_header_validator.js +7 -6
  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 +4 -1
  177. package/dest/msg_validators/tx_validator/data_validator.d.ts.map +1 -1
  178. package/dest/msg_validators/tx_validator/data_validator.js +94 -87
  179. package/dest/msg_validators/tx_validator/double_spend_validator.d.ts +15 -6
  180. package/dest/msg_validators/tx_validator/double_spend_validator.d.ts.map +1 -1
  181. package/dest/msg_validators/tx_validator/double_spend_validator.js +24 -29
  182. package/dest/msg_validators/tx_validator/factory.d.ts +149 -0
  183. package/dest/msg_validators/tx_validator/factory.d.ts.map +1 -0
  184. package/dest/msg_validators/tx_validator/factory.js +275 -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_validator.d.ts +108 -0
  189. package/dest/msg_validators/tx_validator/gas_validator.d.ts.map +1 -0
  190. package/dest/msg_validators/tx_validator/gas_validator.js +194 -0
  191. package/dest/msg_validators/tx_validator/index.d.ts +13 -1
  192. package/dest/msg_validators/tx_validator/index.d.ts.map +1 -1
  193. package/dest/msg_validators/tx_validator/index.js +12 -0
  194. package/dest/msg_validators/tx_validator/metadata_validator.d.ts +10 -5
  195. package/dest/msg_validators/tx_validator/metadata_validator.d.ts.map +1 -1
  196. package/dest/msg_validators/tx_validator/metadata_validator.js +40 -21
  197. package/dest/msg_validators/tx_validator/nullifier_cache.d.ts +14 -0
  198. package/dest/msg_validators/tx_validator/nullifier_cache.d.ts.map +1 -0
  199. package/dest/msg_validators/tx_validator/nullifier_cache.js +24 -0
  200. package/dest/msg_validators/tx_validator/phases_validator.d.ts +35 -0
  201. package/dest/msg_validators/tx_validator/phases_validator.d.ts.map +1 -0
  202. package/dest/msg_validators/tx_validator/phases_validator.js +141 -0
  203. package/dest/msg_validators/tx_validator/size_validator.d.ts +8 -0
  204. package/dest/msg_validators/tx_validator/size_validator.d.ts.map +1 -0
  205. package/dest/msg_validators/tx_validator/size_validator.js +23 -0
  206. package/dest/msg_validators/tx_validator/test_utils.d.ts +17 -0
  207. package/dest/msg_validators/tx_validator/test_utils.d.ts.map +1 -0
  208. package/dest/msg_validators/tx_validator/test_utils.js +22 -0
  209. package/dest/msg_validators/tx_validator/timestamp_validator.d.ts +30 -0
  210. package/dest/msg_validators/tx_validator/timestamp_validator.d.ts.map +1 -0
  211. package/dest/msg_validators/tx_validator/timestamp_validator.js +32 -0
  212. package/dest/msg_validators/tx_validator/tx_permitted_validator.d.ts +9 -0
  213. package/dest/msg_validators/tx_validator/tx_permitted_validator.d.ts.map +1 -0
  214. package/dest/msg_validators/tx_validator/tx_permitted_validator.js +24 -0
  215. package/dest/msg_validators/tx_validator/tx_proof_validator.d.ts +4 -2
  216. package/dest/msg_validators/tx_validator/tx_proof_validator.d.ts.map +1 -1
  217. package/dest/msg_validators/tx_validator/tx_proof_validator.js +10 -7
  218. package/dest/msg_validators/tx_validator/tx_validation_cache.d.ts +48 -0
  219. package/dest/msg_validators/tx_validator/tx_validation_cache.d.ts.map +1 -0
  220. package/dest/msg_validators/tx_validator/tx_validation_cache.js +68 -0
  221. package/dest/services/data_store.d.ts +1 -1
  222. package/dest/services/data_store.d.ts.map +1 -1
  223. package/dest/services/data_store.js +14 -10
  224. package/dest/services/discv5/discV5_service.d.ts +11 -9
  225. package/dest/services/discv5/discV5_service.d.ts.map +1 -1
  226. package/dest/services/discv5/discV5_service.js +92 -38
  227. package/dest/services/dummy_service.d.ts +77 -18
  228. package/dest/services/dummy_service.d.ts.map +1 -1
  229. package/dest/services/dummy_service.js +139 -12
  230. package/dest/services/encoding.d.ts +30 -7
  231. package/dest/services/encoding.d.ts.map +1 -1
  232. package/dest/services/encoding.js +88 -12
  233. package/dest/services/gossipsub/index.d.ts +3 -0
  234. package/dest/services/gossipsub/index.d.ts.map +1 -0
  235. package/dest/services/gossipsub/index.js +2 -0
  236. package/dest/services/gossipsub/scoring.d.ts +21 -3
  237. package/dest/services/gossipsub/scoring.d.ts.map +1 -1
  238. package/dest/services/gossipsub/scoring.js +24 -7
  239. package/dest/services/gossipsub/topic_score_params.d.ts +184 -0
  240. package/dest/services/gossipsub/topic_score_params.d.ts.map +1 -0
  241. package/dest/services/gossipsub/topic_score_params.js +363 -0
  242. package/dest/services/index.d.ts +6 -1
  243. package/dest/services/index.d.ts.map +1 -1
  244. package/dest/services/index.js +5 -0
  245. package/dest/services/libp2p/instrumentation.d.ts +22 -0
  246. package/dest/services/libp2p/instrumentation.d.ts.map +1 -0
  247. package/dest/services/libp2p/instrumentation.js +136 -0
  248. package/dest/services/libp2p/libp2p_service.d.ts +165 -111
  249. package/dest/services/libp2p/libp2p_service.d.ts.map +1 -1
  250. package/dest/services/libp2p/libp2p_service.js +1517 -379
  251. package/dest/services/peer-manager/interface.d.ts +23 -0
  252. package/dest/services/peer-manager/interface.d.ts.map +1 -0
  253. package/dest/services/peer-manager/interface.js +1 -0
  254. package/dest/services/peer-manager/metrics.d.ts +14 -3
  255. package/dest/services/peer-manager/metrics.d.ts.map +1 -1
  256. package/dest/services/peer-manager/metrics.js +50 -12
  257. package/dest/services/peer-manager/peer_manager.d.ts +108 -24
  258. package/dest/services/peer-manager/peer_manager.d.ts.map +1 -1
  259. package/dest/services/peer-manager/peer_manager.js +583 -85
  260. package/dest/services/peer-manager/peer_scoring.d.ts +12 -2
  261. package/dest/services/peer-manager/peer_scoring.d.ts.map +1 -1
  262. package/dest/services/peer-manager/peer_scoring.js +99 -13
  263. package/dest/services/reqresp/batch-tx-requester/batch_tx_requester.d.ts +44 -0
  264. package/dest/services/reqresp/batch-tx-requester/batch_tx_requester.d.ts.map +1 -0
  265. package/dest/services/reqresp/batch-tx-requester/batch_tx_requester.js +534 -0
  266. package/dest/services/reqresp/batch-tx-requester/config.d.ts +17 -0
  267. package/dest/services/reqresp/batch-tx-requester/config.d.ts.map +1 -0
  268. package/dest/services/reqresp/batch-tx-requester/config.js +27 -0
  269. package/dest/services/reqresp/batch-tx-requester/interface.d.ts +50 -0
  270. package/dest/services/reqresp/batch-tx-requester/interface.d.ts.map +1 -0
  271. package/dest/services/reqresp/batch-tx-requester/interface.js +1 -0
  272. package/dest/services/reqresp/batch-tx-requester/missing_txs.d.ts +35 -0
  273. package/dest/services/reqresp/batch-tx-requester/missing_txs.d.ts.map +1 -0
  274. package/dest/services/reqresp/batch-tx-requester/missing_txs.js +136 -0
  275. package/dest/services/reqresp/batch-tx-requester/peer_collection.d.ts +62 -0
  276. package/dest/services/reqresp/batch-tx-requester/peer_collection.d.ts.map +1 -0
  277. package/dest/services/reqresp/batch-tx-requester/peer_collection.js +176 -0
  278. package/dest/services/reqresp/batch-tx-requester/tx_validator.d.ts +11 -0
  279. package/dest/services/reqresp/batch-tx-requester/tx_validator.d.ts.map +1 -0
  280. package/dest/services/reqresp/batch-tx-requester/tx_validator.js +7 -0
  281. package/dest/services/reqresp/config.d.ts +13 -11
  282. package/dest/services/reqresp/config.d.ts.map +1 -1
  283. package/dest/services/reqresp/config.js +18 -4
  284. package/dest/services/reqresp/connection-sampler/connection_sampler.d.ts +32 -17
  285. package/dest/services/reqresp/connection-sampler/connection_sampler.d.ts.map +1 -1
  286. package/dest/services/reqresp/connection-sampler/connection_sampler.js +154 -84
  287. package/dest/services/reqresp/constants.d.ts +12 -0
  288. package/dest/services/reqresp/constants.d.ts.map +1 -0
  289. package/dest/services/reqresp/constants.js +7 -0
  290. package/dest/services/reqresp/index.d.ts +3 -2
  291. package/dest/services/reqresp/index.d.ts.map +1 -1
  292. package/dest/services/reqresp/index.js +2 -1
  293. package/dest/services/reqresp/interface.d.ts +88 -30
  294. package/dest/services/reqresp/interface.d.ts.map +1 -1
  295. package/dest/services/reqresp/interface.js +61 -38
  296. package/dest/services/reqresp/metrics.d.ts +6 -5
  297. package/dest/services/reqresp/metrics.d.ts.map +1 -1
  298. package/dest/services/reqresp/metrics.js +16 -21
  299. package/dest/services/reqresp/protocols/auth.d.ts +43 -0
  300. package/dest/services/reqresp/protocols/auth.d.ts.map +1 -0
  301. package/dest/services/reqresp/protocols/auth.js +71 -0
  302. package/dest/services/reqresp/protocols/block_txs/bitvector.d.ts +35 -0
  303. package/dest/services/reqresp/protocols/block_txs/bitvector.d.ts.map +1 -0
  304. package/dest/services/reqresp/protocols/block_txs/bitvector.js +88 -0
  305. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.d.ts +13 -0
  306. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.d.ts.map +1 -0
  307. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.js +60 -0
  308. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.d.ts +75 -0
  309. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.d.ts.map +1 -0
  310. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.js +139 -0
  311. package/dest/services/reqresp/protocols/block_txs/index.d.ts +4 -0
  312. package/dest/services/reqresp/protocols/block_txs/index.d.ts.map +1 -0
  313. package/dest/services/reqresp/protocols/block_txs/index.js +3 -0
  314. package/dest/services/reqresp/protocols/goodbye.d.ts +3 -5
  315. package/dest/services/reqresp/protocols/goodbye.d.ts.map +1 -1
  316. package/dest/services/reqresp/protocols/goodbye.js +7 -7
  317. package/dest/services/reqresp/protocols/index.d.ts +3 -2
  318. package/dest/services/reqresp/protocols/index.d.ts.map +1 -1
  319. package/dest/services/reqresp/protocols/index.js +2 -1
  320. package/dest/services/reqresp/protocols/ping.d.ts +1 -3
  321. package/dest/services/reqresp/protocols/ping.d.ts.map +1 -1
  322. package/dest/services/reqresp/protocols/status.d.ts +40 -7
  323. package/dest/services/reqresp/protocols/status.d.ts.map +1 -1
  324. package/dest/services/reqresp/protocols/status.js +76 -5
  325. package/dest/services/reqresp/protocols/tx.d.ts +20 -4
  326. package/dest/services/reqresp/protocols/tx.d.ts.map +1 -1
  327. package/dest/services/reqresp/protocols/tx.js +52 -6
  328. package/dest/services/reqresp/rate-limiter/index.d.ts +1 -1
  329. package/dest/services/reqresp/rate-limiter/rate_limiter.d.ts +10 -7
  330. package/dest/services/reqresp/rate-limiter/rate_limiter.d.ts.map +1 -1
  331. package/dest/services/reqresp/rate-limiter/rate_limiter.js +20 -10
  332. package/dest/services/reqresp/rate-limiter/rate_limits.d.ts +1 -1
  333. package/dest/services/reqresp/rate-limiter/rate_limits.d.ts.map +1 -1
  334. package/dest/services/reqresp/rate-limiter/rate_limits.js +16 -6
  335. package/dest/services/reqresp/reqresp.d.ts +32 -91
  336. package/dest/services/reqresp/reqresp.d.ts.map +1 -1
  337. package/dest/services/reqresp/reqresp.js +695 -355
  338. package/dest/services/reqresp/status.d.ts +10 -4
  339. package/dest/services/reqresp/status.d.ts.map +1 -1
  340. package/dest/services/reqresp/status.js +9 -2
  341. package/dest/services/service.d.ts +76 -23
  342. package/dest/services/service.d.ts.map +1 -1
  343. package/dest/services/tx_collection/config.d.ts +25 -0
  344. package/dest/services/tx_collection/config.d.ts.map +1 -0
  345. package/dest/services/tx_collection/config.js +59 -0
  346. package/dest/services/tx_collection/file_store_tx_collection.d.ts +37 -0
  347. package/dest/services/tx_collection/file_store_tx_collection.d.ts.map +1 -0
  348. package/dest/services/tx_collection/file_store_tx_collection.js +127 -0
  349. package/dest/services/tx_collection/file_store_tx_source.d.ts +38 -0
  350. package/dest/services/tx_collection/file_store_tx_source.d.ts.map +1 -0
  351. package/dest/services/tx_collection/file_store_tx_source.js +100 -0
  352. package/dest/services/tx_collection/index.d.ts +4 -0
  353. package/dest/services/tx_collection/index.d.ts.map +1 -0
  354. package/dest/services/tx_collection/index.js +3 -0
  355. package/dest/services/tx_collection/instrumentation.d.ts +10 -0
  356. package/dest/services/tx_collection/instrumentation.d.ts.map +1 -0
  357. package/dest/services/tx_collection/instrumentation.js +30 -0
  358. package/dest/services/tx_collection/request_tracker.d.ts +53 -0
  359. package/dest/services/tx_collection/request_tracker.d.ts.map +1 -0
  360. package/dest/services/tx_collection/request_tracker.js +84 -0
  361. package/dest/services/tx_collection/tx_collection.d.ts +104 -0
  362. package/dest/services/tx_collection/tx_collection.d.ts.map +1 -0
  363. package/dest/services/tx_collection/tx_collection.js +356 -0
  364. package/dest/services/tx_collection/tx_collection_sink.d.ts +40 -0
  365. package/dest/services/tx_collection/tx_collection_sink.d.ts.map +1 -0
  366. package/dest/services/tx_collection/tx_collection_sink.js +108 -0
  367. package/dest/services/tx_collection/tx_source.d.ts +24 -0
  368. package/dest/services/tx_collection/tx_source.d.ts.map +1 -0
  369. package/dest/services/tx_collection/tx_source.js +50 -0
  370. package/dest/services/tx_file_store/config.d.ts +16 -0
  371. package/dest/services/tx_file_store/config.d.ts.map +1 -0
  372. package/dest/services/tx_file_store/config.js +22 -0
  373. package/dest/services/tx_file_store/index.d.ts +4 -0
  374. package/dest/services/tx_file_store/index.d.ts.map +1 -0
  375. package/dest/services/tx_file_store/index.js +3 -0
  376. package/dest/services/tx_file_store/instrumentation.d.ts +15 -0
  377. package/dest/services/tx_file_store/instrumentation.d.ts.map +1 -0
  378. package/dest/services/tx_file_store/instrumentation.js +29 -0
  379. package/dest/services/tx_file_store/tx_file_store.d.ts +46 -0
  380. package/dest/services/tx_file_store/tx_file_store.d.ts.map +1 -0
  381. package/dest/services/tx_file_store/tx_file_store.js +142 -0
  382. package/dest/services/tx_provider.d.ts +53 -0
  383. package/dest/services/tx_provider.d.ts.map +1 -0
  384. package/dest/services/tx_provider.js +223 -0
  385. package/dest/services/tx_provider_instrumentation.d.ts +16 -0
  386. package/dest/services/tx_provider_instrumentation.d.ts.map +1 -0
  387. package/dest/services/tx_provider_instrumentation.js +34 -0
  388. package/dest/test-helpers/generate-peer-id-private-keys.d.ts +1 -1
  389. package/dest/test-helpers/get-ports.d.ts +1 -1
  390. package/dest/test-helpers/get-ports.d.ts.map +1 -1
  391. package/dest/test-helpers/index.d.ts +4 -1
  392. package/dest/test-helpers/index.d.ts.map +1 -1
  393. package/dest/test-helpers/index.js +3 -0
  394. package/dest/test-helpers/make-enrs.d.ts +1 -1
  395. package/dest/test-helpers/make-enrs.d.ts.map +1 -1
  396. package/dest/test-helpers/make-enrs.js +4 -5
  397. package/dest/test-helpers/make-test-p2p-clients.d.ts +35 -8
  398. package/dest/test-helpers/make-test-p2p-clients.d.ts.map +1 -1
  399. package/dest/test-helpers/make-test-p2p-clients.js +89 -17
  400. package/dest/test-helpers/mock-pubsub.d.ts +99 -0
  401. package/dest/test-helpers/mock-pubsub.d.ts.map +1 -0
  402. package/dest/test-helpers/mock-pubsub.js +231 -0
  403. package/dest/test-helpers/mock-tx-helpers.d.ts +12 -0
  404. package/dest/test-helpers/mock-tx-helpers.d.ts.map +1 -0
  405. package/dest/test-helpers/mock-tx-helpers.js +19 -0
  406. package/dest/test-helpers/reqresp-nodes.d.ts +17 -15
  407. package/dest/test-helpers/reqresp-nodes.d.ts.map +1 -1
  408. package/dest/test-helpers/reqresp-nodes.js +73 -40
  409. package/dest/test-helpers/test_tx_provider.d.ts +42 -0
  410. package/dest/test-helpers/test_tx_provider.d.ts.map +1 -0
  411. package/dest/test-helpers/test_tx_provider.js +44 -0
  412. package/dest/test-helpers/testbench-utils.d.ts +161 -0
  413. package/dest/test-helpers/testbench-utils.d.ts.map +1 -0
  414. package/dest/test-helpers/testbench-utils.js +391 -0
  415. package/dest/testbench/p2p_client_testbench_worker.d.ts +26 -2
  416. package/dest/testbench/p2p_client_testbench_worker.d.ts.map +1 -1
  417. package/dest/testbench/p2p_client_testbench_worker.js +310 -95
  418. package/dest/testbench/parse_log_file.d.ts +1 -1
  419. package/dest/testbench/parse_log_file.js +4 -4
  420. package/dest/testbench/testbench.d.ts +1 -1
  421. package/dest/testbench/testbench.js +4 -4
  422. package/dest/testbench/worker_client_manager.d.ts +57 -11
  423. package/dest/testbench/worker_client_manager.d.ts.map +1 -1
  424. package/dest/testbench/worker_client_manager.js +283 -58
  425. package/dest/types/index.d.ts +4 -2
  426. package/dest/types/index.d.ts.map +1 -1
  427. package/dest/types/index.js +2 -0
  428. package/dest/util.d.ts +33 -20
  429. package/dest/util.d.ts.map +1 -1
  430. package/dest/util.js +98 -71
  431. package/dest/versioning.d.ts +6 -9
  432. package/dest/versioning.d.ts.map +1 -1
  433. package/dest/versioning.js +9 -25
  434. package/package.json +33 -27
  435. package/src/bootstrap/bootstrap.ts +42 -15
  436. package/src/client/factory.ts +242 -60
  437. package/src/client/index.ts +1 -0
  438. package/src/client/interface.ts +239 -0
  439. package/src/client/p2p_client.ts +527 -460
  440. package/src/client/test/p2p_client.batch_tx_requester.bench.README.md +197 -0
  441. package/src/config.ts +518 -127
  442. package/src/enr/generate-enr.ts +39 -6
  443. package/src/errors/attestation-pool.error.ts +13 -0
  444. package/src/errors/p2p-service.error.ts +11 -0
  445. package/src/errors/reqresp.error.ts +0 -25
  446. package/src/errors/tx-pool.error.ts +12 -0
  447. package/src/index.ts +5 -1
  448. package/src/mem_pools/attestation_pool/attestation_pool.ts +605 -29
  449. package/src/mem_pools/attestation_pool/attestation_pool_test_suite.ts +828 -201
  450. package/src/mem_pools/attestation_pool/index.ts +9 -2
  451. package/src/mem_pools/attestation_pool/mocks.ts +32 -19
  452. package/src/mem_pools/index.ts +2 -2
  453. package/src/mem_pools/instrumentation.ts +79 -47
  454. package/src/mem_pools/interface.ts +5 -7
  455. package/src/mem_pools/tx_pool_v2/README.md +283 -0
  456. package/src/mem_pools/tx_pool_v2/archive/index.ts +1 -0
  457. package/src/mem_pools/tx_pool_v2/archive/tx_archive.ts +112 -0
  458. package/src/mem_pools/tx_pool_v2/deleted_pool.ts +321 -0
  459. package/src/mem_pools/tx_pool_v2/eviction/eviction_manager.ts +160 -0
  460. package/src/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.ts +122 -0
  461. package/src/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.ts +125 -0
  462. package/src/mem_pools/tx_pool_v2/eviction/index.ts +28 -0
  463. package/src/mem_pools/tx_pool_v2/eviction/insufficient_fee_per_gas_eviction_rule.ts +65 -0
  464. package/src/mem_pools/tx_pool_v2/eviction/interfaces.ts +219 -0
  465. package/src/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.ts +74 -0
  466. package/src/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.ts +101 -0
  467. package/src/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.ts +91 -0
  468. package/src/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.ts +99 -0
  469. package/src/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.ts +32 -0
  470. package/src/mem_pools/tx_pool_v2/index.ts +12 -0
  471. package/src/mem_pools/tx_pool_v2/instrumentation.ts +69 -0
  472. package/src/mem_pools/tx_pool_v2/interfaces.ts +250 -0
  473. package/src/mem_pools/tx_pool_v2/tx_metadata.ts +349 -0
  474. package/src/mem_pools/tx_pool_v2/tx_pool_bench_metrics.ts +77 -0
  475. package/src/mem_pools/tx_pool_v2/tx_pool_indices.ts +430 -0
  476. package/src/mem_pools/tx_pool_v2/tx_pool_v2.ts +238 -0
  477. package/src/mem_pools/tx_pool_v2/tx_pool_v2_impl.ts +1090 -0
  478. package/src/msg_validators/attestation_validator/README.md +49 -0
  479. package/src/msg_validators/attestation_validator/attestation_validator.ts +105 -15
  480. package/src/msg_validators/attestation_validator/fisherman_attestation_validator.ts +101 -0
  481. package/src/msg_validators/attestation_validator/index.ts +1 -0
  482. package/src/msg_validators/clock_tolerance.ts +121 -0
  483. package/src/msg_validators/index.ts +1 -1
  484. package/src/msg_validators/msg_seen_validator/msg_seen_validator.ts +36 -0
  485. package/src/msg_validators/proposal_validator/README.md +123 -0
  486. package/src/msg_validators/proposal_validator/block_proposal_validator.ts +30 -0
  487. package/src/msg_validators/proposal_validator/checkpoint_proposal_validator.ts +41 -0
  488. package/src/msg_validators/proposal_validator/index.ts +3 -0
  489. package/src/msg_validators/proposal_validator/proposal_validator.ts +159 -0
  490. package/src/msg_validators/tx_validator/README.md +127 -0
  491. package/src/msg_validators/tx_validator/aggregate_tx_validator.ts +8 -17
  492. package/src/msg_validators/tx_validator/allowed_public_setup.ts +30 -0
  493. package/src/msg_validators/tx_validator/allowed_setup_helpers.ts +31 -0
  494. package/src/msg_validators/tx_validator/archive_cache.ts +28 -0
  495. package/src/msg_validators/tx_validator/block_header_validator.ts +23 -10
  496. package/src/msg_validators/tx_validator/cached_tx_validator.ts +31 -0
  497. package/src/msg_validators/tx_validator/contract_instance_validator.ts +56 -0
  498. package/src/msg_validators/tx_validator/data_validator.ts +138 -71
  499. package/src/msg_validators/tx_validator/double_spend_validator.ts +31 -23
  500. package/src/msg_validators/tx_validator/factory.ts +478 -0
  501. package/src/msg_validators/tx_validator/fee_payer_balance.ts +44 -0
  502. package/src/msg_validators/tx_validator/gas_validator.ts +268 -0
  503. package/src/msg_validators/tx_validator/index.ts +12 -0
  504. package/src/msg_validators/tx_validator/metadata_validator.ts +80 -24
  505. package/src/msg_validators/tx_validator/nullifier_cache.ts +30 -0
  506. package/src/msg_validators/tx_validator/phases_validator.ts +173 -0
  507. package/src/msg_validators/tx_validator/size_validator.ts +22 -0
  508. package/src/msg_validators/tx_validator/test_utils.ts +43 -0
  509. package/src/msg_validators/tx_validator/timestamp_validator.ts +57 -0
  510. package/src/msg_validators/tx_validator/tx_permitted_validator.ts +22 -0
  511. package/src/msg_validators/tx_validator/tx_proof_validator.ts +16 -8
  512. package/src/msg_validators/tx_validator/tx_validation_cache.ts +101 -0
  513. package/src/services/data_store.ts +14 -19
  514. package/src/services/discv5/discV5_service.ts +118 -39
  515. package/src/services/dummy_service.ts +196 -20
  516. package/src/services/encoding.ts +95 -11
  517. package/src/services/gossipsub/README.md +641 -0
  518. package/src/services/gossipsub/index.ts +2 -0
  519. package/src/services/gossipsub/scoring.ts +29 -5
  520. package/src/services/gossipsub/topic_score_params.ts +519 -0
  521. package/src/services/index.ts +5 -0
  522. package/src/services/libp2p/instrumentation.ts +140 -0
  523. package/src/services/libp2p/libp2p_service.ts +1373 -438
  524. package/src/services/peer-manager/interface.ts +29 -0
  525. package/src/services/peer-manager/metrics.ts +62 -12
  526. package/src/services/peer-manager/peer_manager.ts +695 -83
  527. package/src/services/peer-manager/peer_scoring.ts +96 -7
  528. package/src/services/reqresp/README.md +215 -0
  529. package/src/services/reqresp/batch-tx-requester/README.md +344 -0
  530. package/src/services/reqresp/batch-tx-requester/batch_tx_requester.ts +660 -0
  531. package/src/services/reqresp/batch-tx-requester/config.ts +40 -0
  532. package/src/services/reqresp/batch-tx-requester/interface.ts +61 -0
  533. package/src/services/reqresp/batch-tx-requester/missing_txs.ts +168 -0
  534. package/src/services/reqresp/batch-tx-requester/peer_collection.ts +249 -0
  535. package/src/services/reqresp/batch-tx-requester/tx_validator.ts +24 -0
  536. package/src/services/reqresp/config.ts +27 -10
  537. package/src/services/reqresp/connection-sampler/connection_sampler.ts +166 -95
  538. package/src/services/reqresp/constants.ts +14 -0
  539. package/src/services/reqresp/index.ts +2 -0
  540. package/src/services/reqresp/interface.ts +116 -59
  541. package/src/services/reqresp/metrics.ts +39 -28
  542. package/src/services/reqresp/protocols/auth.ts +83 -0
  543. package/src/services/reqresp/protocols/block_txs/bitvector.ts +107 -0
  544. package/src/services/reqresp/protocols/block_txs/block_txs_handler.ts +80 -0
  545. package/src/services/reqresp/protocols/block_txs/block_txs_reqresp.ts +171 -0
  546. package/src/services/reqresp/protocols/block_txs/index.ts +3 -0
  547. package/src/services/reqresp/protocols/goodbye.ts +9 -7
  548. package/src/services/reqresp/protocols/index.ts +2 -1
  549. package/src/services/reqresp/protocols/status.ts +121 -5
  550. package/src/services/reqresp/protocols/tx.ts +56 -8
  551. package/src/services/reqresp/rate-limiter/rate_limiter.ts +25 -12
  552. package/src/services/reqresp/rate-limiter/rate_limits.ts +16 -6
  553. package/src/services/reqresp/reqresp.ts +397 -422
  554. package/src/services/reqresp/status.ts +12 -3
  555. package/src/services/service.ts +104 -28
  556. package/src/services/tx_collection/config.ts +89 -0
  557. package/src/services/tx_collection/file_store_tx_collection.ts +153 -0
  558. package/src/services/tx_collection/file_store_tx_source.ts +129 -0
  559. package/src/services/tx_collection/index.ts +3 -0
  560. package/src/services/tx_collection/instrumentation.ts +35 -0
  561. package/src/services/tx_collection/request_tracker.ts +127 -0
  562. package/src/services/tx_collection/tx_collection.ts +468 -0
  563. package/src/services/tx_collection/tx_collection_sink.ts +125 -0
  564. package/src/services/tx_collection/tx_source.ts +57 -0
  565. package/src/services/tx_file_store/config.ts +37 -0
  566. package/src/services/tx_file_store/index.ts +3 -0
  567. package/src/services/tx_file_store/instrumentation.ts +36 -0
  568. package/src/services/tx_file_store/tx_file_store.ts +163 -0
  569. package/src/services/tx_provider.ts +238 -0
  570. package/src/services/tx_provider_instrumentation.ts +54 -0
  571. package/src/test-helpers/index.ts +3 -0
  572. package/src/test-helpers/make-enrs.ts +4 -5
  573. package/src/test-helpers/make-test-p2p-clients.ts +117 -26
  574. package/src/test-helpers/mock-pubsub.ts +311 -0
  575. package/src/test-helpers/mock-tx-helpers.ts +24 -0
  576. package/src/test-helpers/reqresp-nodes.ts +101 -62
  577. package/src/test-helpers/test_tx_provider.ts +69 -0
  578. package/src/test-helpers/testbench-utils.ts +453 -0
  579. package/src/testbench/p2p_client_testbench_worker.ts +477 -95
  580. package/src/testbench/parse_log_file.ts +4 -4
  581. package/src/testbench/testbench.ts +4 -4
  582. package/src/testbench/worker_client_manager.ts +366 -63
  583. package/src/types/index.ts +2 -0
  584. package/src/util.ts +128 -93
  585. package/src/versioning.ts +11 -34
  586. package/dest/mem_pools/attestation_pool/kv_attestation_pool.d.ts +0 -22
  587. package/dest/mem_pools/attestation_pool/kv_attestation_pool.d.ts.map +0 -1
  588. package/dest/mem_pools/attestation_pool/kv_attestation_pool.js +0 -112
  589. package/dest/mem_pools/attestation_pool/memory_attestation_pool.d.ts +0 -17
  590. package/dest/mem_pools/attestation_pool/memory_attestation_pool.d.ts.map +0 -1
  591. package/dest/mem_pools/attestation_pool/memory_attestation_pool.js +0 -129
  592. package/dest/mem_pools/tx_pool/aztec_kv_tx_pool.d.ts +0 -66
  593. package/dest/mem_pools/tx_pool/aztec_kv_tx_pool.d.ts.map +0 -1
  594. package/dest/mem_pools/tx_pool/aztec_kv_tx_pool.js +0 -245
  595. package/dest/mem_pools/tx_pool/index.d.ts +0 -4
  596. package/dest/mem_pools/tx_pool/index.d.ts.map +0 -1
  597. package/dest/mem_pools/tx_pool/index.js +0 -3
  598. package/dest/mem_pools/tx_pool/memory_tx_pool.d.ts +0 -56
  599. package/dest/mem_pools/tx_pool/memory_tx_pool.d.ts.map +0 -1
  600. package/dest/mem_pools/tx_pool/memory_tx_pool.js +0 -141
  601. package/dest/mem_pools/tx_pool/priority.d.ts +0 -8
  602. package/dest/mem_pools/tx_pool/priority.d.ts.map +0 -1
  603. package/dest/mem_pools/tx_pool/priority.js +0 -10
  604. package/dest/mem_pools/tx_pool/tx_pool.d.ts +0 -66
  605. package/dest/mem_pools/tx_pool/tx_pool.d.ts.map +0 -1
  606. package/dest/mem_pools/tx_pool/tx_pool.js +0 -3
  607. package/dest/mem_pools/tx_pool/tx_pool_test_suite.d.ts +0 -7
  608. package/dest/mem_pools/tx_pool/tx_pool_test_suite.d.ts.map +0 -1
  609. package/dest/mem_pools/tx_pool/tx_pool_test_suite.js +0 -169
  610. package/dest/msg_validators/block_proposal_validator/block_proposal_validator.d.ts +0 -8
  611. package/dest/msg_validators/block_proposal_validator/block_proposal_validator.d.ts.map +0 -1
  612. package/dest/msg_validators/block_proposal_validator/block_proposal_validator.js +0 -21
  613. package/dest/msg_validators/block_proposal_validator/index.d.ts +0 -2
  614. package/dest/msg_validators/block_proposal_validator/index.d.ts.map +0 -1
  615. package/dest/msg_validators/block_proposal_validator/index.js +0 -1
  616. package/dest/services/reqresp/connection-sampler/batch_connection_sampler.d.ts +0 -45
  617. package/dest/services/reqresp/connection-sampler/batch_connection_sampler.d.ts.map +0 -1
  618. package/dest/services/reqresp/connection-sampler/batch_connection_sampler.js +0 -88
  619. package/dest/services/reqresp/protocols/block.d.ts +0 -4
  620. package/dest/services/reqresp/protocols/block.d.ts.map +0 -1
  621. package/dest/services/reqresp/protocols/block.js +0 -8
  622. package/src/mem_pools/attestation_pool/kv_attestation_pool.ts +0 -159
  623. package/src/mem_pools/attestation_pool/memory_attestation_pool.ts +0 -161
  624. package/src/mem_pools/tx_pool/aztec_kv_tx_pool.ts +0 -309
  625. package/src/mem_pools/tx_pool/index.ts +0 -3
  626. package/src/mem_pools/tx_pool/memory_tx_pool.ts +0 -174
  627. package/src/mem_pools/tx_pool/priority.ts +0 -13
  628. package/src/mem_pools/tx_pool/tx_pool.ts +0 -76
  629. package/src/mem_pools/tx_pool/tx_pool_test_suite.ts +0 -130
  630. package/src/msg_validators/block_proposal_validator/block_proposal_validator.ts +0 -29
  631. package/src/msg_validators/block_proposal_validator/index.ts +0 -1
  632. package/src/services/reqresp/connection-sampler/batch_connection_sampler.ts +0 -94
  633. package/src/services/reqresp/protocols/block.ts +0 -15
@@ -1,28 +1,403 @@
1
1
  // @attribution: lodestar impl for inspiration
2
- function _ts_decorate(decorators, target, key, desc) {
3
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
- else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
- return c > 3 && r && Object.defineProperty(target, key, r), r;
2
+ function applyDecs2203RFactory() {
3
+ function createAddInitializerMethod(initializers, decoratorFinishedRef) {
4
+ return function addInitializer(initializer) {
5
+ assertNotFinished(decoratorFinishedRef, "addInitializer");
6
+ assertCallable(initializer, "An initializer");
7
+ initializers.push(initializer);
8
+ };
9
+ }
10
+ function memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value) {
11
+ var kindStr;
12
+ switch(kind){
13
+ case 1:
14
+ kindStr = "accessor";
15
+ break;
16
+ case 2:
17
+ kindStr = "method";
18
+ break;
19
+ case 3:
20
+ kindStr = "getter";
21
+ break;
22
+ case 4:
23
+ kindStr = "setter";
24
+ break;
25
+ default:
26
+ kindStr = "field";
27
+ }
28
+ var ctx = {
29
+ kind: kindStr,
30
+ name: isPrivate ? "#" + name : name,
31
+ static: isStatic,
32
+ private: isPrivate,
33
+ metadata: metadata
34
+ };
35
+ var decoratorFinishedRef = {
36
+ v: false
37
+ };
38
+ ctx.addInitializer = createAddInitializerMethod(initializers, decoratorFinishedRef);
39
+ var get, set;
40
+ if (kind === 0) {
41
+ if (isPrivate) {
42
+ get = desc.get;
43
+ set = desc.set;
44
+ } else {
45
+ get = function() {
46
+ return this[name];
47
+ };
48
+ set = function(v) {
49
+ this[name] = v;
50
+ };
51
+ }
52
+ } else if (kind === 2) {
53
+ get = function() {
54
+ return desc.value;
55
+ };
56
+ } else {
57
+ if (kind === 1 || kind === 3) {
58
+ get = function() {
59
+ return desc.get.call(this);
60
+ };
61
+ }
62
+ if (kind === 1 || kind === 4) {
63
+ set = function(v) {
64
+ desc.set.call(this, v);
65
+ };
66
+ }
67
+ }
68
+ ctx.access = get && set ? {
69
+ get: get,
70
+ set: set
71
+ } : get ? {
72
+ get: get
73
+ } : {
74
+ set: set
75
+ };
76
+ try {
77
+ return dec(value, ctx);
78
+ } finally{
79
+ decoratorFinishedRef.v = true;
80
+ }
81
+ }
82
+ function assertNotFinished(decoratorFinishedRef, fnName) {
83
+ if (decoratorFinishedRef.v) {
84
+ throw new Error("attempted to call " + fnName + " after decoration was finished");
85
+ }
86
+ }
87
+ function assertCallable(fn, hint) {
88
+ if (typeof fn !== "function") {
89
+ throw new TypeError(hint + " must be a function");
90
+ }
91
+ }
92
+ function assertValidReturnValue(kind, value) {
93
+ var type = typeof value;
94
+ if (kind === 1) {
95
+ if (type !== "object" || value === null) {
96
+ throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");
97
+ }
98
+ if (value.get !== undefined) {
99
+ assertCallable(value.get, "accessor.get");
100
+ }
101
+ if (value.set !== undefined) {
102
+ assertCallable(value.set, "accessor.set");
103
+ }
104
+ if (value.init !== undefined) {
105
+ assertCallable(value.init, "accessor.init");
106
+ }
107
+ } else if (type !== "function") {
108
+ var hint;
109
+ if (kind === 0) {
110
+ hint = "field";
111
+ } else if (kind === 10) {
112
+ hint = "class";
113
+ } else {
114
+ hint = "method";
115
+ }
116
+ throw new TypeError(hint + " decorators must return a function or void 0");
117
+ }
118
+ }
119
+ function applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata) {
120
+ var decs = decInfo[0];
121
+ var desc, init, value;
122
+ if (isPrivate) {
123
+ if (kind === 0 || kind === 1) {
124
+ desc = {
125
+ get: decInfo[3],
126
+ set: decInfo[4]
127
+ };
128
+ } else if (kind === 3) {
129
+ desc = {
130
+ get: decInfo[3]
131
+ };
132
+ } else if (kind === 4) {
133
+ desc = {
134
+ set: decInfo[3]
135
+ };
136
+ } else {
137
+ desc = {
138
+ value: decInfo[3]
139
+ };
140
+ }
141
+ } else if (kind !== 0) {
142
+ desc = Object.getOwnPropertyDescriptor(base, name);
143
+ }
144
+ if (kind === 1) {
145
+ value = {
146
+ get: desc.get,
147
+ set: desc.set
148
+ };
149
+ } else if (kind === 2) {
150
+ value = desc.value;
151
+ } else if (kind === 3) {
152
+ value = desc.get;
153
+ } else if (kind === 4) {
154
+ value = desc.set;
155
+ }
156
+ var newValue, get, set;
157
+ if (typeof decs === "function") {
158
+ newValue = memberDec(decs, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
159
+ if (newValue !== void 0) {
160
+ assertValidReturnValue(kind, newValue);
161
+ if (kind === 0) {
162
+ init = newValue;
163
+ } else if (kind === 1) {
164
+ init = newValue.init;
165
+ get = newValue.get || value.get;
166
+ set = newValue.set || value.set;
167
+ value = {
168
+ get: get,
169
+ set: set
170
+ };
171
+ } else {
172
+ value = newValue;
173
+ }
174
+ }
175
+ } else {
176
+ for(var i = decs.length - 1; i >= 0; i--){
177
+ var dec = decs[i];
178
+ newValue = memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
179
+ if (newValue !== void 0) {
180
+ assertValidReturnValue(kind, newValue);
181
+ var newInit;
182
+ if (kind === 0) {
183
+ newInit = newValue;
184
+ } else if (kind === 1) {
185
+ newInit = newValue.init;
186
+ get = newValue.get || value.get;
187
+ set = newValue.set || value.set;
188
+ value = {
189
+ get: get,
190
+ set: set
191
+ };
192
+ } else {
193
+ value = newValue;
194
+ }
195
+ if (newInit !== void 0) {
196
+ if (init === void 0) {
197
+ init = newInit;
198
+ } else if (typeof init === "function") {
199
+ init = [
200
+ init,
201
+ newInit
202
+ ];
203
+ } else {
204
+ init.push(newInit);
205
+ }
206
+ }
207
+ }
208
+ }
209
+ }
210
+ if (kind === 0 || kind === 1) {
211
+ if (init === void 0) {
212
+ init = function(instance, init) {
213
+ return init;
214
+ };
215
+ } else if (typeof init !== "function") {
216
+ var ownInitializers = init;
217
+ init = function(instance, init) {
218
+ var value = init;
219
+ for(var i = 0; i < ownInitializers.length; i++){
220
+ value = ownInitializers[i].call(instance, value);
221
+ }
222
+ return value;
223
+ };
224
+ } else {
225
+ var originalInitializer = init;
226
+ init = function(instance, init) {
227
+ return originalInitializer.call(instance, init);
228
+ };
229
+ }
230
+ ret.push(init);
231
+ }
232
+ if (kind !== 0) {
233
+ if (kind === 1) {
234
+ desc.get = value.get;
235
+ desc.set = value.set;
236
+ } else if (kind === 2) {
237
+ desc.value = value;
238
+ } else if (kind === 3) {
239
+ desc.get = value;
240
+ } else if (kind === 4) {
241
+ desc.set = value;
242
+ }
243
+ if (isPrivate) {
244
+ if (kind === 1) {
245
+ ret.push(function(instance, args) {
246
+ return value.get.call(instance, args);
247
+ });
248
+ ret.push(function(instance, args) {
249
+ return value.set.call(instance, args);
250
+ });
251
+ } else if (kind === 2) {
252
+ ret.push(value);
253
+ } else {
254
+ ret.push(function(instance, args) {
255
+ return value.call(instance, args);
256
+ });
257
+ }
258
+ } else {
259
+ Object.defineProperty(base, name, desc);
260
+ }
261
+ }
262
+ }
263
+ function applyMemberDecs(Class, decInfos, metadata) {
264
+ var ret = [];
265
+ var protoInitializers;
266
+ var staticInitializers;
267
+ var existingProtoNonFields = new Map();
268
+ var existingStaticNonFields = new Map();
269
+ for(var i = 0; i < decInfos.length; i++){
270
+ var decInfo = decInfos[i];
271
+ if (!Array.isArray(decInfo)) continue;
272
+ var kind = decInfo[1];
273
+ var name = decInfo[2];
274
+ var isPrivate = decInfo.length > 3;
275
+ var isStatic = kind >= 5;
276
+ var base;
277
+ var initializers;
278
+ if (isStatic) {
279
+ base = Class;
280
+ kind = kind - 5;
281
+ staticInitializers = staticInitializers || [];
282
+ initializers = staticInitializers;
283
+ } else {
284
+ base = Class.prototype;
285
+ protoInitializers = protoInitializers || [];
286
+ initializers = protoInitializers;
287
+ }
288
+ if (kind !== 0 && !isPrivate) {
289
+ var existingNonFields = isStatic ? existingStaticNonFields : existingProtoNonFields;
290
+ var existingKind = existingNonFields.get(name) || 0;
291
+ if (existingKind === true || existingKind === 3 && kind !== 4 || existingKind === 4 && kind !== 3) {
292
+ throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + name);
293
+ } else if (!existingKind && kind > 2) {
294
+ existingNonFields.set(name, kind);
295
+ } else {
296
+ existingNonFields.set(name, true);
297
+ }
298
+ }
299
+ applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata);
300
+ }
301
+ pushInitializers(ret, protoInitializers);
302
+ pushInitializers(ret, staticInitializers);
303
+ return ret;
304
+ }
305
+ function pushInitializers(ret, initializers) {
306
+ if (initializers) {
307
+ ret.push(function(instance) {
308
+ for(var i = 0; i < initializers.length; i++){
309
+ initializers[i].call(instance);
310
+ }
311
+ return instance;
312
+ });
313
+ }
314
+ }
315
+ function applyClassDecs(targetClass, classDecs, metadata) {
316
+ if (classDecs.length > 0) {
317
+ var initializers = [];
318
+ var newClass = targetClass;
319
+ var name = targetClass.name;
320
+ for(var i = classDecs.length - 1; i >= 0; i--){
321
+ var decoratorFinishedRef = {
322
+ v: false
323
+ };
324
+ try {
325
+ var nextNewClass = classDecs[i](newClass, {
326
+ kind: "class",
327
+ name: name,
328
+ addInitializer: createAddInitializerMethod(initializers, decoratorFinishedRef),
329
+ metadata
330
+ });
331
+ } finally{
332
+ decoratorFinishedRef.v = true;
333
+ }
334
+ if (nextNewClass !== undefined) {
335
+ assertValidReturnValue(10, nextNewClass);
336
+ newClass = nextNewClass;
337
+ }
338
+ }
339
+ return [
340
+ defineMetadata(newClass, metadata),
341
+ function() {
342
+ for(var i = 0; i < initializers.length; i++){
343
+ initializers[i].call(newClass);
344
+ }
345
+ }
346
+ ];
347
+ }
348
+ }
349
+ function defineMetadata(Class, metadata) {
350
+ return Object.defineProperty(Class, Symbol.metadata || Symbol.for("Symbol.metadata"), {
351
+ configurable: true,
352
+ enumerable: true,
353
+ value: metadata
354
+ });
355
+ }
356
+ return function applyDecs2203R(targetClass, memberDecs, classDecs, parentClass) {
357
+ if (parentClass !== void 0) {
358
+ var parentMetadata = parentClass[Symbol.metadata || Symbol.for("Symbol.metadata")];
359
+ }
360
+ var metadata = Object.create(parentMetadata === void 0 ? null : parentMetadata);
361
+ var e = applyMemberDecs(targetClass, memberDecs, metadata);
362
+ if (!classDecs.length) defineMetadata(targetClass, metadata);
363
+ return {
364
+ e: e,
365
+ get c () {
366
+ return applyClassDecs(targetClass, classDecs, metadata);
367
+ }
368
+ };
369
+ };
370
+ }
371
+ function _apply_decs_2203_r(targetClass, memberDecs, classDecs, parentClass) {
372
+ return (_apply_decs_2203_r = applyDecs2203RFactory())(targetClass, memberDecs, classDecs, parentClass);
7
373
  }
374
+ var _dec, _dec1, _initProto;
375
+ import { AbortError, TimeoutError } from '@aztec/foundation/error';
8
376
  import { createLogger } from '@aztec/foundation/log';
9
377
  import { executeTimeout } from '@aztec/foundation/timer';
10
378
  import { PeerErrorSeverity } from '@aztec/stdlib/p2p';
11
379
  import { Attributes, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
12
- import { pipe } from 'it-pipe';
13
- import { CollectiveReqRespTimeoutError, IndividualReqRespTimeoutError, InvalidResponseError } from '../../errors/reqresp.error.js';
14
- import { SnappyTransform } from '../encoding.js';
15
- import { BatchConnectionSampler } from './connection-sampler/batch_connection_sampler.js';
16
- import { ConnectionSampler } from './connection-sampler/connection_sampler.js';
17
- import { DEFAULT_SUB_PROTOCOL_HANDLERS, DEFAULT_SUB_PROTOCOL_VALIDATORS, ReqRespSubProtocol, subProtocolMap } from './interface.js';
380
+ import { pipeline } from 'node:stream/promises';
381
+ import { IndividualReqRespTimeoutError } from '../../errors/reqresp.error.js';
382
+ import { OversizedSnappyResponseError, SnappyTransform } from '../encoding.js';
383
+ import { DEFAULT_INDIVIDUAL_REQUEST_TIMEOUT_MS, DEFAULT_REQRESP_DIAL_TIMEOUT_MS } from './config.js';
384
+ import { ConnectionSampler, RandomSampler } from './connection-sampler/connection_sampler.js';
385
+ import { ReqRespSubProtocol, UNAUTHENTICATED_ALLOWED_PROTOCOLS, subProtocolSizeCalculators } from './interface.js';
18
386
  import { ReqRespMetrics } from './metrics.js';
19
387
  import { RateLimitStatus, RequestResponseRateLimiter, prettyPrintRateLimitStatus } from './rate-limiter/rate_limiter.js';
20
- import { ReqRespStatus, ReqRespStatusError, parseStatusChunk, prettyPrintReqRespStatus } from './status.js';
388
+ import { ReqRespStatus, ReqRespStatusError, parseStatusChunk } from './status.js';
389
+ _dec = trackSpan('ReqResp.sendRequestToPeer', (peerId, subProtocol, _)=>({
390
+ [Attributes.P2P_ID]: peerId.toString(),
391
+ [Attributes.P2P_REQ_RESP_PROTOCOL]: subProtocol
392
+ })), _dec1 = trackSpan('ReqResp.streamHandler', (protocol, { connection })=>({
393
+ [Attributes.P2P_REQ_RESP_PROTOCOL]: protocol,
394
+ [Attributes.P2P_ID]: connection.remotePeer.toString()
395
+ }));
21
396
  /**
22
397
  * The Request Response Service
23
398
  *
24
399
  * It allows nodes to request specific information from their peers, its use case covers recovering
25
- * information that was missed during a syncronisation or a gossip event.
400
+ * information that was missed during a synchronisation or a gossip event.
26
401
  *
27
402
  * This service implements the request response sub protocol, it is heavily inspired from
28
403
  * ethereum implementations of the same name.
@@ -35,43 +410,78 @@ import { ReqRespStatus, ReqRespStatusError, parseStatusChunk, prettyPrintReqResp
35
410
  libp2p;
36
411
  peerScoring;
37
412
  logger;
38
- overallRequestTimeoutMs;
413
+ static{
414
+ ({ e: [_initProto] } = _apply_decs_2203_r(this, [
415
+ [
416
+ _dec,
417
+ 2,
418
+ "sendRequestToPeer"
419
+ ],
420
+ [
421
+ _dec1,
422
+ 2,
423
+ "streamHandler"
424
+ ]
425
+ ], []));
426
+ }
39
427
  individualRequestTimeoutMs;
40
- // Warning, if the `start` function is not called as the parent class constructor, then the default sub protocol handlers will be used ( not good )
428
+ dialTimeoutMs;
41
429
  subProtocolHandlers;
42
- subProtocolValidators;
43
430
  connectionSampler;
44
431
  rateLimiter;
45
432
  snappyTransform;
433
+ shouldRejectPeer;
46
434
  metrics;
47
- constructor(config, libp2p, peerScoring, telemetryClient = getTelemetryClient()){
435
+ constructor(config, libp2p, peerScoring, logger = createLogger('p2p:reqresp'), rateLimits = {}, telemetryClient = getTelemetryClient()){
48
436
  this.libp2p = libp2p;
49
437
  this.peerScoring = peerScoring;
50
- this.subProtocolHandlers = DEFAULT_SUB_PROTOCOL_HANDLERS;
51
- this.subProtocolValidators = DEFAULT_SUB_PROTOCOL_VALIDATORS;
52
- this.logger = createLogger('p2p:reqresp');
53
- this.overallRequestTimeoutMs = config.overallRequestTimeoutMs;
54
- this.individualRequestTimeoutMs = config.individualRequestTimeoutMs;
55
- this.rateLimiter = new RequestResponseRateLimiter(peerScoring);
438
+ this.logger = logger;
439
+ this.individualRequestTimeoutMs = (_initProto(this), DEFAULT_INDIVIDUAL_REQUEST_TIMEOUT_MS);
440
+ this.dialTimeoutMs = DEFAULT_REQRESP_DIAL_TIMEOUT_MS;
441
+ this.subProtocolHandlers = {};
442
+ this.updateConfig(config);
443
+ this.rateLimiter = new RequestResponseRateLimiter(peerScoring, rateLimits);
56
444
  // Connection sampler is used to sample our connected peers
57
- this.connectionSampler = new ConnectionSampler(libp2p);
445
+ this.connectionSampler = new ConnectionSampler(libp2p, new RandomSampler(), createLogger(`${logger.module}:connection-sampler`), config);
58
446
  this.snappyTransform = new SnappyTransform();
59
447
  this.metrics = new ReqRespMetrics(telemetryClient);
60
448
  }
449
+ updateConfig(config) {
450
+ if (typeof config.individualRequestTimeoutMs === 'number') {
451
+ this.individualRequestTimeoutMs = config.individualRequestTimeoutMs;
452
+ }
453
+ if (typeof config.dialTimeoutMs === 'number') {
454
+ this.dialTimeoutMs = config.dialTimeoutMs;
455
+ }
456
+ }
457
+ setShouldRejectPeer(checker) {
458
+ this.shouldRejectPeer = checker;
459
+ }
61
460
  get tracer() {
62
461
  return this.metrics.tracer;
63
462
  }
64
463
  /**
464
+ * Get the connection sampler instance
465
+ */ getConnectionSampler() {
466
+ return this.connectionSampler;
467
+ }
468
+ /**
65
469
  * Start the reqresp service
66
- */ async start(subProtocolHandlers, subProtocolValidators) {
67
- this.subProtocolHandlers = subProtocolHandlers;
68
- this.subProtocolValidators = subProtocolValidators;
69
- // Register all protocol handlers
70
- for (const subProtocol of Object.keys(this.subProtocolHandlers)){
470
+ */ async start(subProtocolHandlers) {
471
+ Object.assign(this.subProtocolHandlers, subProtocolHandlers);
472
+ // Register streamHandler with libp2p.
473
+ // The streamHandler is responsible for reading the incoming stream, determining the protocol, then triggering the appropriate handler.
474
+ for (const subProtocol of Object.keys(subProtocolHandlers)){
475
+ this.logger.debug(`Registering handler for sub protocol ${subProtocol}`);
71
476
  await this.libp2p.handle(subProtocol, (data)=>void this.streamHandler(subProtocol, data).catch((err)=>this.logger.error(`Error on libp2p subprotocol ${subProtocol} handler`, err)));
72
477
  }
73
478
  this.rateLimiter.start();
74
479
  }
480
+ async addSubProtocol(subProtocol, handler) {
481
+ this.subProtocolHandlers[subProtocol] = handler;
482
+ this.logger.debug(`Registering handler for sub protocol ${subProtocol}`);
483
+ await this.libp2p.handle(subProtocol, (data)=>void this.streamHandler(subProtocol, data).catch((err)=>this.logger.error(`Error on libp2p subprotocol ${subProtocol} handler`, err)));
484
+ }
75
485
  /**
76
486
  * Stop the reqresp service
77
487
  */ async stop() {
@@ -90,206 +500,6 @@ import { ReqRespStatus, ReqRespStatusError, parseStatusChunk, prettyPrintReqResp
90
500
  // NOTE: We assume libp2p instance is managed by the caller
91
501
  }
92
502
  /**
93
- * Send a request to peers, returns the first response
94
- *
95
- * @param subProtocol - The protocol being requested
96
- * @param request - The request to send
97
- * @returns - The response from the peer, otherwise undefined
98
- *
99
- * @description
100
- * This method attempts to send a request to all active peers using the specified sub-protocol.
101
- * It opens a stream with each peer, sends the request, and awaits a response.
102
- * If a valid response is received, it returns the response; otherwise, it continues to the next peer.
103
- * If no response is received from any peer, it returns undefined.
104
- *
105
- * The method performs the following steps:
106
- * - Sample a peer to send the request to.
107
- * - Opens a stream with the peer using the specified sub-protocol.
108
- *
109
- * When a response is received, it is validated using the given sub protocols response validator.
110
- * To see the interface for the response validator - see `interface.ts`
111
- *
112
- * Failing a response validation requests in a severe peer penalty, and will
113
- * prompt the node to continue to search to the next peer.
114
- * For example, a transaction request validator will check that the payload returned does in fact
115
- * match the txHash that was requested. A peer that fails this check an only be an extremely naughty peer.
116
- *
117
- * This entire operation is wrapped in an overall timeout, that is independent of the
118
- * peer it is requesting data from.
119
- *
120
- */ async sendRequest(subProtocol, request) {
121
- const responseValidator = this.subProtocolValidators[subProtocol];
122
- const requestBuffer = request.toBuffer();
123
- const requestFunction = async ()=>{
124
- // Attempt to ask all of our peers, but sampled in a random order
125
- // This function is wrapped in a timeout, so we will exit the loop if we have not received a response
126
- const numberOfPeers = this.libp2p.getPeers().length;
127
- if (numberOfPeers === 0) {
128
- this.logger.debug('No active peers to send requests to');
129
- return undefined;
130
- }
131
- const attemptedPeers = new Map();
132
- for(let i = 0; i < numberOfPeers; i++){
133
- // Sample a peer to make a request to
134
- const peer = this.connectionSampler.getPeer(attemptedPeers);
135
- this.logger.trace(`Attempting to send request to peer: ${peer?.toString()}`);
136
- if (!peer) {
137
- this.logger.debug('No peers available to send requests to');
138
- return undefined;
139
- }
140
- attemptedPeers.set(peer.toString(), true);
141
- this.logger.trace(`Sending request to peer: ${peer.toString()}`);
142
- const response = await this.sendRequestToPeer(peer, subProtocol, requestBuffer);
143
- if (response && response.status !== ReqRespStatus.SUCCESS) {
144
- this.logger.debug(`Request to peer ${peer.toString()} failed with status ${prettyPrintReqRespStatus(response.status)}`);
145
- continue;
146
- }
147
- // If we get a response, return it, otherwise we iterate onto the next peer
148
- // We do not consider it a success if we have an empty buffer
149
- if (response && response.data.length > 0) {
150
- const object = subProtocolMap[subProtocol].response.fromBuffer(response.data);
151
- // The response validator handles peer punishment within
152
- const isValid = await responseValidator(request, object, peer);
153
- if (!isValid) {
154
- throw new InvalidResponseError();
155
- }
156
- return object;
157
- }
158
- }
159
- };
160
- try {
161
- return await executeTimeout(requestFunction, this.overallRequestTimeoutMs, ()=>new CollectiveReqRespTimeoutError());
162
- } catch (e) {
163
- this.logger.debug(`${e.message} | subProtocol: ${subProtocol}`);
164
- return undefined;
165
- }
166
- }
167
- /**
168
- * Request multiple messages over the same sub protocol, balancing the requests across peers.
169
- *
170
- * @devnote
171
- * - The function prioritizes sending requests to free peers using a batch sampling strategy.
172
- * - If a peer fails to respond or returns an invalid response, it is removed from the sampling pool and replaced.
173
- * - The function stops retrying once all requests are processed, no active peers remain, or the maximum retry attempts are reached.
174
- * - Responses are validated using a custom validator for the sub-protocol.*
175
- *
176
- * Requests are sent in parallel to each peer, but multiple requests are sent to the same peer in series
177
- * - If a peer fails to respond or returns an invalid response, it is removed from the sampling pool and replaced.
178
- * - The function stops retrying once all requests are processed, no active peers remain, or the maximum retry attempts are reached.
179
- * - Responses are validated using a custom validator for the sub-protocol.*
180
- *
181
- * @param subProtocol
182
- * @param requests
183
- * @param timeoutMs
184
- * @param maxPeers
185
- * @returns
186
- *
187
- * @throws {CollectiveReqRespTimeoutError} - If the request batch exceeds the specified timeout (`timeoutMs`).
188
- */ async sendBatchRequest(subProtocol, requests, timeoutMs = 10000, maxPeers = Math.min(10, requests.length), maxRetryAttempts = 3) {
189
- const responseValidator = this.subProtocolValidators[subProtocol];
190
- const responses = new Array(requests.length);
191
- const requestBuffers = requests.map((req)=>req.toBuffer());
192
- const requestFunction = async ()=>{
193
- // Track which requests still need to be processed
194
- const pendingRequestIndices = new Set(requestBuffers.map((_, i)=>i));
195
- // Create batch sampler with the total number of requests and max peers
196
- const batchSampler = new BatchConnectionSampler(this.connectionSampler, requests.length, maxPeers);
197
- if (batchSampler.activePeerCount === 0) {
198
- this.logger.debug('No active peers to send requests to');
199
- return [];
200
- }
201
- // This is where it gets fun
202
- // The outer loop is the retry loop, we will continue to retry until we process all indices we have
203
- // not received a response for, or we have reached the max retry attempts
204
- // The inner loop is the batch loop, we will process all requests for each peer in parallel
205
- // We will then process the results of the requests, and resample any peers that failed to respond
206
- // We will continue to retry until we have processed all indices, or we have reached the max retry attempts
207
- let retryAttempts = 0;
208
- while(pendingRequestIndices.size > 0 && batchSampler.activePeerCount > 0 && retryAttempts < maxRetryAttempts){
209
- // Process requests in parallel for each available peer
210
- const requestBatches = new Map();
211
- // Group requests by peer
212
- for (const requestIndex of pendingRequestIndices){
213
- const peer = batchSampler.getPeerForRequest(requestIndex);
214
- if (!peer) {
215
- break;
216
- }
217
- if (!requestBatches.has(peer)) {
218
- requestBatches.set(peer, []);
219
- }
220
- requestBatches.get(peer).push(requestIndex);
221
- }
222
- // Make parallel requests for each peer's batch
223
- // A batch entry will look something like this:
224
- // PeerId0: [0, 1, 2, 3]
225
- // PeerId1: [4, 5, 6, 7]
226
- // Peer Id 0 will send requests 0, 1, 2, 3 in serial
227
- // while simultaneously Peer Id 1 will send requests 4, 5, 6, 7 in serial
228
- const batchResults = await Promise.all(Array.from(requestBatches.entries()).map(async ([peer, indices])=>{
229
- try {
230
- // Requests all going to the same peer are sent synchronously
231
- const peerResults = [];
232
- for (const index of indices){
233
- const response = await this.sendRequestToPeer(peer, subProtocol, requestBuffers[index]);
234
- // Check the status of the response buffer
235
- if (response && response.status !== ReqRespStatus.SUCCESS) {
236
- this.logger.debug(`Request to peer ${peer.toString()} failed with status ${prettyPrintReqRespStatus(response.status)}`);
237
- // If we hit a rate limit or some failure, we remove the peer and return the results,
238
- // they will be split among remaining peers and the new sampled peer
239
- batchSampler.removePeerAndReplace(peer);
240
- return {
241
- peer,
242
- results: peerResults
243
- };
244
- }
245
- if (response && response.data.length > 0) {
246
- const object = subProtocolMap[subProtocol].response.fromBuffer(response.data);
247
- const isValid = await responseValidator(requests[index], object, peer);
248
- if (isValid) {
249
- peerResults.push({
250
- index,
251
- response: object
252
- });
253
- }
254
- }
255
- }
256
- return {
257
- peer,
258
- results: peerResults
259
- };
260
- } catch (error) {
261
- this.logger.debug(`Failed batch request to peer ${peer.toString()}:`, error);
262
- batchSampler.removePeerAndReplace(peer);
263
- return {
264
- peer,
265
- results: []
266
- };
267
- }
268
- }));
269
- // Process results
270
- for (const { results } of batchResults){
271
- for (const { index, response } of results){
272
- if (response) {
273
- responses[index] = response;
274
- pendingRequestIndices.delete(index);
275
- }
276
- }
277
- }
278
- retryAttempts++;
279
- }
280
- if (retryAttempts >= maxRetryAttempts) {
281
- this.logger.debug(`Max retry attempts ${maxRetryAttempts} reached for batch request`);
282
- }
283
- return responses;
284
- };
285
- try {
286
- return await executeTimeout(requestFunction, timeoutMs, ()=>new CollectiveReqRespTimeoutError());
287
- } catch (e) {
288
- this.logger.debug(`${e.message} | subProtocol: ${subProtocol}`);
289
- return [];
290
- }
291
- }
292
- /**
293
503
  * Sends a request to a specific peer
294
504
  *
295
505
  * We first dial a particular protocol for the peer, this ensures that the peer knows
@@ -299,6 +509,7 @@ import { ReqRespStatus, ReqRespStatusError, parseStatusChunk, prettyPrintReqResp
299
509
  * @param peerId - The peer to send the request to
300
510
  * @param subProtocol - The protocol to use to request
301
511
  * @param payload - The payload to send
512
+ * @param dialTimeout - If establishing a stream takes longer than this an error will be thrown
302
513
  * @returns If the request is successful, the response is returned, otherwise undefined
303
514
  *
304
515
  * @description
@@ -312,24 +523,51 @@ import { ReqRespStatus, ReqRespStatusError, parseStatusChunk, prettyPrintReqResp
312
523
  *
313
524
  * If the stream is not closed by the dialled peer, and a timeout occurs, then
314
525
  * the stream is closed on the requester's end and sender (us) updates its peer score
315
- */ async sendRequestToPeer(peerId, subProtocol, payload) {
526
+ */ async sendRequestToPeer(peerId, subProtocol, payload, dialTimeout = this.dialTimeoutMs) {
316
527
  let stream;
317
528
  try {
318
529
  this.metrics.recordRequestSent(subProtocol);
319
- stream = await this.connectionSampler.dialProtocol(peerId, subProtocol);
320
- // Open the stream with a timeout
321
- const result = await executeTimeout(()=>pipe([
322
- payload
323
- ], stream, this.readMessage.bind(this)), this.individualRequestTimeoutMs, ()=>new IndividualReqRespTimeoutError());
324
- return result;
530
+ // Calculate expected response size based on the request payload
531
+ const expectedSizeKb = subProtocolSizeCalculators[subProtocol](payload);
532
+ this.logger.trace(`Sending request to peer ${peerId.toString()} on sub protocol ${subProtocol}`);
533
+ stream = await this.connectionSampler.dialProtocol(peerId, subProtocol, dialTimeout);
534
+ this.logger.trace(`Opened stream ${stream.id} for sending request to peer ${peerId.toString()} on sub protocol ${subProtocol}`);
535
+ const timeoutErr = new IndividualReqRespTimeoutError();
536
+ // Create a wrapper to pass the expected size to readMessage
537
+ const readMessageWithSizeLimit = (source)=>this.readMessage(source, expectedSizeKb);
538
+ const [_, resp] = await executeTimeout((signal)=>Promise.all([
539
+ pipeline([
540
+ payload
541
+ ], stream.sink, {
542
+ signal
543
+ }),
544
+ pipeline(stream.source, readMessageWithSizeLimit, {
545
+ signal
546
+ })
547
+ ]), this.individualRequestTimeoutMs, ()=>timeoutErr);
548
+ return resp;
325
549
  } catch (e) {
550
+ this.logger.debug(`SUBPROTOCOL: ${subProtocol}\n`, e);
551
+ // On error we immediately abort the stream, this is preferred way,
552
+ // because it signals to the sender that error happened, whereas
553
+ // closing the stream only closes our side and is much slower
554
+ if (stream) {
555
+ stream.abort(e);
556
+ }
326
557
  this.metrics.recordRequestError(subProtocol);
327
558
  this.handleResponseError(e, peerId, subProtocol);
559
+ // If there is an exception, we return an unknown response
560
+ this.logger.debug(`Error sending request to peer ${peerId.toString()} on sub protocol ${subProtocol}: ${e}`);
561
+ return {
562
+ status: ReqRespStatus.FAILURE
563
+ };
328
564
  } finally{
329
565
  // Only close the stream if we created it
566
+ // Note even if we aborted the stream, calling close on it is ok, it's just a no-op
330
567
  if (stream) {
331
568
  try {
332
- await this.connectionSampler.close(stream.id);
569
+ this.logger.trace(`Closing stream ${stream.id} for request to peer ${peerId.toString()} on sub protocol ${subProtocol}`);
570
+ await this.connectionSampler.close(stream);
333
571
  } catch (closeError) {
334
572
  this.logger.error(`Error closing stream: ${closeError instanceof Error ? closeError.message : 'Unknown error'}`);
335
573
  }
@@ -346,94 +584,59 @@ import { ReqRespStatus, ReqRespStatusError, parseStatusChunk, prettyPrintReqResp
346
584
  * @param subProtocol - The sub protocol
347
585
  * @returns If the error is non pubishable, then undefined is returned, otherwise the peer is penalized
348
586
  */ handleResponseError(e, peerId, subProtocol) {
349
- const severity = this.categorizeError(e, peerId, subProtocol);
587
+ const severity = this.categorizeResponseError(e, peerId, subProtocol);
350
588
  if (severity) {
351
589
  this.peerScoring.penalizePeer(peerId, severity);
352
590
  }
353
591
  }
354
592
  /**
355
- * Categorize the error and log it.
356
- */ categorizeError(e, peerId, subProtocol) {
357
- // Non punishable errors - we do not expect a response for goodbye messages
358
- if (subProtocol === ReqRespSubProtocol.GOODBYE) {
359
- this.logger.debug('Error encountered on goodbye sub protocol, no penalty', {
360
- peerId: peerId.toString(),
361
- subProtocol
362
- });
363
- return undefined;
364
- }
365
- // We do not punish a collective timeout, as the node triggers this interupt, independent of the peer's behaviour
366
- const logTags = {
367
- peerId: peerId.toString(),
368
- subProtocol
369
- };
370
- if (e instanceof CollectiveReqRespTimeoutError || e instanceof InvalidResponseError) {
371
- this.logger.debug(`Non-punishable error: ${e.message} | peerId: ${peerId.toString()} | subProtocol: ${subProtocol}`, logTags);
372
- return undefined;
373
- }
374
- // Pubishable errors
375
- // Connection reset errors in the networking stack are punished with high severity
376
- // it just signals an unreliable peer
377
- // We assume that the requesting node has a functioning networking stack.
378
- if (e?.code === 'ECONNRESET' || e?.code === 'EPIPE') {
379
- this.logger.debug(`Connection reset: ${peerId.toString()}`, logTags);
380
- return PeerErrorSeverity.HighToleranceError;
381
- }
382
- if (e?.code === 'ECONNREFUSED') {
383
- this.logger.debug(`Connection refused: ${peerId.toString()}`, logTags);
384
- return PeerErrorSeverity.HighToleranceError;
385
- }
386
- // Timeout errors are punished with high tolerance, they can be due to a geogrpahically far away peer or an
387
- // overloaded peer
388
- if (e instanceof IndividualReqRespTimeoutError) {
389
- this.logger.debug(`Timeout error: ${e.message} | peerId: ${peerId.toString()} | subProtocol: ${subProtocol}`, logTags);
390
- return PeerErrorSeverity.HighToleranceError;
391
- }
392
- // Catch all error
393
- this.logger.error(`Unexpected error sending request to peer`, e, logTags);
394
- return PeerErrorSeverity.HighToleranceError;
395
- }
396
- /**
397
593
  * Read a message returned from a stream into a single buffer
398
594
  *
399
595
  * The message is split into two components
400
596
  * - The first chunk should contain a control byte, indicating the status of the response see `ReqRespStatus`
401
597
  * - The second chunk should contain the response data
402
- */ async readMessage(source) {
403
- let statusBuffer;
598
+ *
599
+ * @param source - The async iterable source of data chunks
600
+ * @param maxSizeKb - Optional maximum expected size in KB for the decompressed response
601
+ */ async readMessage(source, maxSizeKb) {
602
+ let status;
404
603
  const chunks = [];
405
604
  try {
406
605
  for await (const chunk of source){
407
- if (statusBuffer === undefined) {
408
- const firstChunkBuffer = chunk.subarray();
409
- statusBuffer = parseStatusChunk(firstChunkBuffer);
410
- } else {
606
+ const statusParsed = status !== undefined;
607
+ if (statusParsed) {
411
608
  chunks.push(chunk.subarray());
609
+ continue;
610
+ }
611
+ const firstChunkBuffer = chunk.subarray();
612
+ status = parseStatusChunk(firstChunkBuffer);
613
+ // In case status is not SUCCESS, we do not expect any data in the response
614
+ // we can return early
615
+ if (status !== ReqRespStatus.SUCCESS) {
616
+ return {
617
+ status
618
+ };
412
619
  }
413
620
  }
414
621
  const messageData = Buffer.concat(chunks);
415
- const message = this.snappyTransform.inboundTransformNoTopic(messageData);
622
+ const message = this.snappyTransform.inboundTransformData(messageData, undefined, maxSizeKb);
416
623
  return {
417
- status: statusBuffer ?? ReqRespStatus.UNKNOWN,
624
+ status: status ?? ReqRespStatus.UNKNOWN,
418
625
  data: message
419
626
  };
420
627
  } catch (e) {
628
+ // All errors (invalid status bytes, oversized snappy responses, corrupt data, etc.)
629
+ // are re-thrown so the caller can penalize the peer via handleResponseError.
421
630
  this.logger.debug(`Reading message failed: ${e.message}`);
422
- let status = ReqRespStatus.UNKNOWN;
423
- if (e instanceof ReqRespStatusError) {
424
- status = e.status;
425
- }
426
- return {
427
- status,
428
- data: Buffer.from([])
429
- };
631
+ throw e;
430
632
  }
431
633
  }
432
634
  /**
433
635
  * Stream Handler
434
636
  * Reads the incoming stream, determines the protocol, then triggers the appropriate handler
435
637
  *
436
- * @param param0 - The incoming stream data
638
+ * @param protocol - The sub protocol to handle
639
+ * @param incomingStream - The incoming stream data containing the stream and connection
437
640
  *
438
641
  * @description
439
642
  * An individual stream handler will be bound to each sub protocol, and handles returning data back
@@ -444,73 +647,210 @@ import { ReqRespStatus, ReqRespStatusError, parseStatusChunk, prettyPrintReqResp
444
647
  *
445
648
  * We check rate limits for each peer, note the peer will be penalised within the rate limiter implementation
446
649
  * if they exceed their peer specific limits.
447
- */ async streamHandler(protocol, { stream, connection }) {
448
- this.metrics.recordRequestReceived(protocol);
650
+ */ async streamHandler(protocol, incomingStream) {
651
+ const { stream, connection } = incomingStream;
449
652
  try {
450
- // Store a reference to from this for the async generator
653
+ this.metrics.recordRequestReceived(protocol);
451
654
  const rateLimitStatus = this.rateLimiter.allow(protocol, connection.remotePeer);
452
- if (rateLimitStatus != RateLimitStatus.Allowed) {
453
- this.logger.warn(`Rate limit exceeded ${prettyPrintRateLimitStatus(rateLimitStatus)} for ${protocol} from ${connection.remotePeer}`);
655
+ if (rateLimitStatus !== RateLimitStatus.Allowed) {
656
+ this.logger.verbose(`Rate limit exceeded ${prettyPrintRateLimitStatus(rateLimitStatus)} for ${protocol} from ${connection.remotePeer}`);
454
657
  throw new ReqRespStatusError(ReqRespStatus.RATE_LIMIT_EXCEEDED);
455
658
  }
456
- const handler = this.subProtocolHandlers[protocol];
457
- const transform = this.snappyTransform;
458
- await pipe(stream, async function*(source) {
459
- for await (const chunkList of source){
460
- const msg = Buffer.from(chunkList.subarray());
461
- const response = await handler(connection.remotePeer, msg);
462
- if (protocol === ReqRespSubProtocol.GOODBYE) {
463
- // Don't respond
464
- await stream.close();
465
- return;
466
- }
467
- // Send success code first, then the response
468
- const successChunk = Buffer.from([
469
- ReqRespStatus.SUCCESS
470
- ]);
471
- yield new Uint8Array(successChunk);
472
- yield new Uint8Array(transform.outboundTransformNoTopic(response));
473
- }
474
- }, stream);
475
- } catch (e) {
476
- this.logger.warn('Reqresp Response error: ', e);
659
+ // When p2pAllowOnlyValidators is enabled, reject unauthenticated peers on data protocols
660
+ if (!UNAUTHENTICATED_ALLOWED_PROTOCOLS.has(protocol) && (this.shouldRejectPeer?.(connection.remotePeer.toString()) ?? false)) {
661
+ this.logger.debug(`Rejecting unauthenticated peer ${connection.remotePeer} on gated protocol ${protocol}`);
662
+ throw new ReqRespStatusError(ReqRespStatus.FAILURE);
663
+ }
664
+ await this.processStream(protocol, incomingStream);
665
+ } catch (err) {
477
666
  this.metrics.recordResponseError(protocol);
478
- // If we receive a known error, we use the error status in the response chunk, otherwise we categorize as unknown
479
- let errorStatus = ReqRespStatus.UNKNOWN;
480
- if (e instanceof ReqRespStatusError) {
481
- errorStatus = e.status;
667
+ this.handleRequestError(err, connection.remotePeer, protocol);
668
+ if (err instanceof ReqRespStatusError) {
669
+ const errorSent = await this.trySendError(stream, connection.remotePeer, protocol, err.status);
670
+ const logMessage = errorSent ? 'Protocol error sent successfully.' : 'Stream already closed or poisoned, not sending error response.';
671
+ const isRateLimit = err.status === ReqRespStatus.RATE_LIMIT_EXCEEDED;
672
+ const level = isRateLimit ? 'debug' : 'warn';
673
+ this.logger[level](logMessage + ` Status: ${ReqRespStatus[err.status]}`, {
674
+ protocol,
675
+ err,
676
+ errorStatus: err.status,
677
+ cause: err.cause ?? 'Cause unknown'
678
+ });
679
+ } else {
680
+ // In erroneous case we abort the stream, this will signal the peer that something went wrong
681
+ // and that this stream should be dropped
682
+ const isMessageToNotWarn = err instanceof Error && [
683
+ 'stream reset',
684
+ 'Cannot push value onto an ended pushable',
685
+ 'read ECONNRESET'
686
+ ].some((msg)=>err.message.includes(msg));
687
+ const level = isMessageToNotWarn ? 'debug' : 'warn';
688
+ this.logger[level]('Unknown stream error while handling the stream, aborting', {
689
+ protocol,
690
+ err
691
+ });
692
+ stream.abort(err);
482
693
  }
483
- const sendErrorChunk = this.sendErrorChunk(errorStatus);
484
- // Return and yield the response chunk
485
- await pipe(stream, async function*(_source) {
486
- yield* sendErrorChunk;
487
- }, stream);
488
694
  } finally{
695
+ //NOTE: This is idempotent action, so it's ok to call it even if stream was aborted
489
696
  await stream.close();
490
697
  }
491
698
  }
492
- async *sendErrorChunk(error) {
493
- const errorChunk = Buffer.from([
494
- error
495
- ]);
496
- yield new Uint8Array(errorChunk);
699
+ /**
700
+ * Reads incoming data from the stream, processes it according to the sub protocol,
701
+ * and puts response back into the stream.
702
+ *
703
+ * @param protocol - The sub protocol to use for processing the stream
704
+ * @param incomingStream - The incoming stream data containing the stream and connection
705
+ *
706
+ * */ async processStream(protocol, { stream, connection }) {
707
+ const handler = this.subProtocolHandlers[protocol];
708
+ if (!handler) {
709
+ throw new Error(`No handler defined for reqresp subprotocol ${protocol}`);
710
+ }
711
+ const snappy = this.snappyTransform;
712
+ const SUCCESS = Uint8Array.of(ReqRespStatus.SUCCESS);
713
+ await pipeline(stream.source, async function*(source) {
714
+ for await (const chunk of source){
715
+ const response = await handler(connection.remotePeer, chunk.subarray());
716
+ if (protocol === ReqRespSubProtocol.GOODBYE) {
717
+ // NOTE: The stream was already closed by Goodbye handler
718
+ // peerManager.goodbyeReceived(peerId, reason); will call libp2p.hangUp closing all active streams and connections
719
+ // Don't try to respond
720
+ return;
721
+ }
722
+ stream.metadata.written = true; // Mark the stream as written to;
723
+ yield SUCCESS;
724
+ yield snappy.outboundTransformData(response);
725
+ }
726
+ }, stream.sink);
727
+ }
728
+ /**
729
+ * Try to send error status to the peer. We say try, because the stream,
730
+ * might already be closed
731
+ * @param stream - The stream opened between us and the peer
732
+ * @param status - The error status to send back to the peer
733
+ * @returns true if error was sent successfully, otherwise false
734
+ *
735
+ */ async trySendError(stream, peerId, protocol, status) {
736
+ const canWriteToStream = // 'writing' is a bit weird naming, but it actually means that the stream is ready to write
737
+ // 'ready' means that stream ready to be opened for writing
738
+ stream.status === 'open' && (stream.writeStatus === 'writing' || stream.writeStatus === 'ready');
739
+ // Stream was already written to, we consider it poisoned, in a sense,
740
+ // that even if we write an error response, it will not be interpreted correctly by the peer
741
+ const streamPoisoned = stream.metadata.written === true;
742
+ const shouldWriteToStream = canWriteToStream && !streamPoisoned;
743
+ if (!shouldWriteToStream) {
744
+ return false;
745
+ }
746
+ try {
747
+ await pipeline(function*() {
748
+ yield Uint8Array.of(status);
749
+ }, stream.sink);
750
+ return true;
751
+ } catch (e) {
752
+ this.logger.warn('Error while sending error response', e);
753
+ stream.abort(e);
754
+ this.handleRequestError(e, peerId, protocol);
755
+ return false;
756
+ }
757
+ }
758
+ handleRequestError(e, peerId, subProtocol) {
759
+ const severity = this.categorizeRequestError(e, peerId, subProtocol);
760
+ if (severity) {
761
+ this.peerScoring.penalizePeer(peerId, severity);
762
+ }
763
+ }
764
+ /**
765
+ * Categorize the request error and log it.
766
+ *
767
+ * @returns Severity of the error, or undefined if the error is not punishable.
768
+ */ categorizeRequestError(e, peerId, subProtocol) {
769
+ const logTags = {
770
+ peerId: peerId.toString(),
771
+ subProtocol
772
+ };
773
+ // Punishable error - peer should never send badly formed request
774
+ if (e instanceof ReqRespStatusError && e.status === ReqRespStatus.BADLY_FORMED_REQUEST) {
775
+ this.logger.debug(`Punishable error in ${subProtocol}: ${e.cause}`, logTags);
776
+ return PeerErrorSeverity.LowToleranceError;
777
+ }
778
+ // TODO: (mralj): think if we should penalize peer here based on connection errors
779
+ return undefined;
780
+ }
781
+ /**
782
+ * Categorize the response error and log it.
783
+ *
784
+ * @returns Severity of the error, or undefined if the error is not punishable.
785
+ */ categorizeResponseError(e, peerId, subProtocol) {
786
+ const logTags = {
787
+ peerId: peerId.toString(),
788
+ subProtocol
789
+ };
790
+ // Non punishable errors - we do not expect a response for goodbye messages
791
+ if (subProtocol === ReqRespSubProtocol.GOODBYE) {
792
+ this.logger.debug('Error encountered on goodbye sub protocol, no penalty', logTags);
793
+ return undefined;
794
+ }
795
+ // Invalid status byte: the peer sent a status byte that doesn't match any known status code.
796
+ // This is a protocol violation, penalize harshly.
797
+ if (e instanceof ReqRespStatusError) {
798
+ this.logger.warn(`Invalid status byte from peer ${peerId.toString()} in ${subProtocol}: ${e.message}`, logTags);
799
+ return PeerErrorSeverity.LowToleranceError;
800
+ }
801
+ // Oversized snappy response: the peer is sending data that exceeds the allowed size.
802
+ // This is a protocol violation that wastes bandwidth, so penalize harshly.
803
+ if (e instanceof OversizedSnappyResponseError) {
804
+ this.logger.warn(`Oversized response from peer ${peerId.toString()} in ${subProtocol}: ${e.message}`, logTags);
805
+ return PeerErrorSeverity.LowToleranceError;
806
+ }
807
+ return this.categorizeConnectionErrors(e, peerId, subProtocol);
808
+ }
809
+ /*
810
+ * Errors specific to connection handling
811
+ * These can happen both when sending request and response.
812
+ */ categorizeConnectionErrors(e, peerId, subProtocol) {
813
+ const logTags = {
814
+ peerId: peerId.toString(),
815
+ subProtocol
816
+ };
817
+ // Do not punish if we are stopping the service
818
+ if (e instanceof AbortError || e?.code == 'ABORT_ERR') {
819
+ this.logger.debug(`Request aborted: ${e.message}`, logTags);
820
+ return undefined;
821
+ }
822
+ // Do not punish if we are the ones closing the connection
823
+ if (e?.code === 'ERR_CONNECTION_BEING_CLOSED' || e?.code === 'ERR_CONNECTION_CLOSED' || e?.code === 'ERR_TRANSIENT_CONNECTION' || e?.message?.includes('Muxer already closed') || e?.message?.includes('muxer closed') || e?.message?.includes('ended pushable')) {
824
+ this.logger.debug(`Connection closed to peer from our side: ${peerId.toString()} (${e?.message ?? 'missing error message'})`, logTags);
825
+ return undefined;
826
+ }
827
+ // Pubishable errors
828
+ // Connection reset errors in the networking stack are punished with high severity
829
+ // it just signals an unreliable peer
830
+ // We assume that the requesting node has a functioning networking stack.
831
+ if (e?.code === 'ECONNRESET' || e?.code === 'EPIPE') {
832
+ this.logger.debug(`Connection reset: ${peerId.toString()}`, logTags);
833
+ return PeerErrorSeverity.HighToleranceError;
834
+ }
835
+ if (e?.code === 'ECONNREFUSED') {
836
+ this.logger.debug(`Connection refused: ${peerId.toString()}`, logTags);
837
+ return PeerErrorSeverity.HighToleranceError;
838
+ }
839
+ if (e?.code === 'ERR_UNEXPECTED_EOF') {
840
+ this.logger.debug(`Connection unexpected EOF: ${peerId.toString()}`, logTags);
841
+ return PeerErrorSeverity.HighToleranceError;
842
+ }
843
+ if (e?.code === 'ERR_UNSUPPORTED_PROTOCOL') {
844
+ this.logger.debug(`Sub protocol not supported by peer: ${peerId.toString()}`, logTags);
845
+ return PeerErrorSeverity.HighToleranceError;
846
+ }
847
+ // Timeout errors are punished with high tolerance, they can be due to a geographically far away or overloaded peer
848
+ if (e instanceof IndividualReqRespTimeoutError || e instanceof TimeoutError) {
849
+ this.logger.debug(`Timeout error in ${subProtocol}: ${e.message}`, logTags);
850
+ return PeerErrorSeverity.HighToleranceError;
851
+ }
852
+ // Catch all error
853
+ this.logger.error(`Unexpected error in ReqResp protocol`, e, logTags);
854
+ return PeerErrorSeverity.HighToleranceError;
497
855
  }
498
856
  }
499
- _ts_decorate([
500
- trackSpan('ReqResp.sendBatchRequest', (subProtocol, requests)=>({
501
- [Attributes.P2P_REQ_RESP_PROTOCOL]: subProtocol,
502
- [Attributes.P2P_REQ_RESP_BATCH_REQUESTS_COUNT]: requests.length
503
- }))
504
- ], ReqResp.prototype, "sendBatchRequest", null);
505
- _ts_decorate([
506
- trackSpan('ReqResp.sendRequestToPeer', (peerId, subProtocol, _)=>({
507
- [Attributes.P2P_ID]: peerId.toString(),
508
- [Attributes.P2P_REQ_RESP_PROTOCOL]: subProtocol
509
- }))
510
- ], ReqResp.prototype, "sendRequestToPeer", null);
511
- _ts_decorate([
512
- trackSpan('ReqResp.streamHandler', (protocol, { connection })=>({
513
- [Attributes.P2P_REQ_RESP_PROTOCOL]: protocol,
514
- [Attributes.P2P_ID]: connection.remotePeer.toString()
515
- }))
516
- ], ReqResp.prototype, "streamHandler", null);