@aztec/p2p 0.0.0-test.0

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 (311) hide show
  1. package/README.md +7 -0
  2. package/dest/bootstrap/bootstrap.d.ts +38 -0
  3. package/dest/bootstrap/bootstrap.d.ts.map +1 -0
  4. package/dest/bootstrap/bootstrap.js +123 -0
  5. package/dest/client/factory.d.ts +21 -0
  6. package/dest/client/factory.d.ts.map +1 -0
  7. package/dest/client/factory.js +37 -0
  8. package/dest/client/index.d.ts +3 -0
  9. package/dest/client/index.d.ts.map +1 -0
  10. package/dest/client/index.js +2 -0
  11. package/dest/client/p2p_client.d.ts +314 -0
  12. package/dest/client/p2p_client.d.ts.map +1 -0
  13. package/dest/client/p2p_client.js +505 -0
  14. package/dest/config.d.ts +180 -0
  15. package/dest/config.d.ts.map +1 -0
  16. package/dest/config.js +193 -0
  17. package/dest/enr/generate-enr.d.ts +9 -0
  18. package/dest/enr/generate-enr.d.ts.map +1 -0
  19. package/dest/enr/generate-enr.js +30 -0
  20. package/dest/enr/index.d.ts +2 -0
  21. package/dest/enr/index.d.ts.map +1 -0
  22. package/dest/enr/index.js +1 -0
  23. package/dest/errors/reqresp.error.d.ts +28 -0
  24. package/dest/errors/reqresp.error.d.ts.map +1 -0
  25. package/dest/errors/reqresp.error.js +30 -0
  26. package/dest/index.d.ts +8 -0
  27. package/dest/index.d.ts.map +1 -0
  28. package/dest/index.js +7 -0
  29. package/dest/mem_pools/attestation_pool/attestation_pool.d.ts +57 -0
  30. package/dest/mem_pools/attestation_pool/attestation_pool.d.ts.map +1 -0
  31. package/dest/mem_pools/attestation_pool/attestation_pool.js +6 -0
  32. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.d.ts +3 -0
  33. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.d.ts.map +1 -0
  34. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.js +195 -0
  35. package/dest/mem_pools/attestation_pool/index.d.ts +3 -0
  36. package/dest/mem_pools/attestation_pool/index.d.ts.map +1 -0
  37. package/dest/mem_pools/attestation_pool/index.js +2 -0
  38. package/dest/mem_pools/attestation_pool/kv_attestation_pool.d.ts +22 -0
  39. package/dest/mem_pools/attestation_pool/kv_attestation_pool.d.ts.map +1 -0
  40. package/dest/mem_pools/attestation_pool/kv_attestation_pool.js +112 -0
  41. package/dest/mem_pools/attestation_pool/memory_attestation_pool.d.ts +17 -0
  42. package/dest/mem_pools/attestation_pool/memory_attestation_pool.d.ts.map +1 -0
  43. package/dest/mem_pools/attestation_pool/memory_attestation_pool.js +129 -0
  44. package/dest/mem_pools/attestation_pool/mocks.d.ts +19 -0
  45. package/dest/mem_pools/attestation_pool/mocks.d.ts.map +1 -0
  46. package/dest/mem_pools/attestation_pool/mocks.js +33 -0
  47. package/dest/mem_pools/index.d.ts +4 -0
  48. package/dest/mem_pools/index.d.ts.map +1 -0
  49. package/dest/mem_pools/index.js +1 -0
  50. package/dest/mem_pools/instrumentation.d.ts +30 -0
  51. package/dest/mem_pools/instrumentation.d.ts.map +1 -0
  52. package/dest/mem_pools/instrumentation.js +84 -0
  53. package/dest/mem_pools/interface.d.ts +11 -0
  54. package/dest/mem_pools/interface.d.ts.map +1 -0
  55. package/dest/mem_pools/interface.js +3 -0
  56. package/dest/mem_pools/tx_pool/aztec_kv_tx_pool.d.ts +66 -0
  57. package/dest/mem_pools/tx_pool/aztec_kv_tx_pool.d.ts.map +1 -0
  58. package/dest/mem_pools/tx_pool/aztec_kv_tx_pool.js +245 -0
  59. package/dest/mem_pools/tx_pool/index.d.ts +4 -0
  60. package/dest/mem_pools/tx_pool/index.d.ts.map +1 -0
  61. package/dest/mem_pools/tx_pool/index.js +3 -0
  62. package/dest/mem_pools/tx_pool/memory_tx_pool.d.ts +56 -0
  63. package/dest/mem_pools/tx_pool/memory_tx_pool.d.ts.map +1 -0
  64. package/dest/mem_pools/tx_pool/memory_tx_pool.js +141 -0
  65. package/dest/mem_pools/tx_pool/priority.d.ts +8 -0
  66. package/dest/mem_pools/tx_pool/priority.d.ts.map +1 -0
  67. package/dest/mem_pools/tx_pool/priority.js +10 -0
  68. package/dest/mem_pools/tx_pool/tx_pool.d.ts +66 -0
  69. package/dest/mem_pools/tx_pool/tx_pool.d.ts.map +1 -0
  70. package/dest/mem_pools/tx_pool/tx_pool.js +3 -0
  71. package/dest/mem_pools/tx_pool/tx_pool_test_suite.d.ts +7 -0
  72. package/dest/mem_pools/tx_pool/tx_pool_test_suite.d.ts.map +1 -0
  73. package/dest/mem_pools/tx_pool/tx_pool_test_suite.js +169 -0
  74. package/dest/msg_validators/attestation_validator/attestation_validator.d.ts +8 -0
  75. package/dest/msg_validators/attestation_validator/attestation_validator.d.ts.map +1 -0
  76. package/dest/msg_validators/attestation_validator/attestation_validator.js +19 -0
  77. package/dest/msg_validators/attestation_validator/index.d.ts +2 -0
  78. package/dest/msg_validators/attestation_validator/index.d.ts.map +1 -0
  79. package/dest/msg_validators/attestation_validator/index.js +1 -0
  80. package/dest/msg_validators/block_proposal_validator/block_proposal_validator.d.ts +8 -0
  81. package/dest/msg_validators/block_proposal_validator/block_proposal_validator.d.ts.map +1 -0
  82. package/dest/msg_validators/block_proposal_validator/block_proposal_validator.js +21 -0
  83. package/dest/msg_validators/block_proposal_validator/index.d.ts +2 -0
  84. package/dest/msg_validators/block_proposal_validator/index.d.ts.map +1 -0
  85. package/dest/msg_validators/block_proposal_validator/index.js +1 -0
  86. package/dest/msg_validators/index.d.ts +4 -0
  87. package/dest/msg_validators/index.d.ts.map +1 -0
  88. package/dest/msg_validators/index.js +3 -0
  89. package/dest/msg_validators/tx_validator/aggregate_tx_validator.d.ts +7 -0
  90. package/dest/msg_validators/tx_validator/aggregate_tx_validator.d.ts.map +1 -0
  91. package/dest/msg_validators/tx_validator/aggregate_tx_validator.js +31 -0
  92. package/dest/msg_validators/tx_validator/block_header_validator.d.ts +11 -0
  93. package/dest/msg_validators/tx_validator/block_header_validator.d.ts.map +1 -0
  94. package/dest/msg_validators/tx_validator/block_header_validator.js +26 -0
  95. package/dest/msg_validators/tx_validator/data_validator.d.ts +6 -0
  96. package/dest/msg_validators/tx_validator/data_validator.d.ts.map +1 -0
  97. package/dest/msg_validators/tx_validator/data_validator.js +107 -0
  98. package/dest/msg_validators/tx_validator/double_spend_validator.d.ts +12 -0
  99. package/dest/msg_validators/tx_validator/double_spend_validator.d.ts.map +1 -0
  100. package/dest/msg_validators/tx_validator/double_spend_validator.js +41 -0
  101. package/dest/msg_validators/tx_validator/index.d.ts +7 -0
  102. package/dest/msg_validators/tx_validator/index.d.ts.map +1 -0
  103. package/dest/msg_validators/tx_validator/index.js +6 -0
  104. package/dest/msg_validators/tx_validator/metadata_validator.d.ts +10 -0
  105. package/dest/msg_validators/tx_validator/metadata_validator.d.ts.map +1 -0
  106. package/dest/msg_validators/tx_validator/metadata_validator.js +44 -0
  107. package/dest/msg_validators/tx_validator/tx_proof_validator.d.ts +9 -0
  108. package/dest/msg_validators/tx_validator/tx_proof_validator.d.ts.map +1 -0
  109. package/dest/msg_validators/tx_validator/tx_proof_validator.js +25 -0
  110. package/dest/services/data_store.d.ts +27 -0
  111. package/dest/services/data_store.d.ts.map +1 -0
  112. package/dest/services/data_store.js +188 -0
  113. package/dest/services/discv5/discV5_service.d.ts +42 -0
  114. package/dest/services/discv5/discV5_service.d.ts.map +1 -0
  115. package/dest/services/discv5/discV5_service.js +214 -0
  116. package/dest/services/dummy_service.d.ts +85 -0
  117. package/dest/services/dummy_service.d.ts.map +1 -0
  118. package/dest/services/dummy_service.js +92 -0
  119. package/dest/services/encoding.d.ts +31 -0
  120. package/dest/services/encoding.d.ts.map +1 -0
  121. package/dest/services/encoding.js +66 -0
  122. package/dest/services/gossipsub/scoring.d.ts +7 -0
  123. package/dest/services/gossipsub/scoring.d.ts.map +1 -0
  124. package/dest/services/gossipsub/scoring.js +10 -0
  125. package/dest/services/index.d.ts +3 -0
  126. package/dest/services/index.d.ts.map +1 -0
  127. package/dest/services/index.js +2 -0
  128. package/dest/services/libp2p/libp2p_service.d.ts +186 -0
  129. package/dest/services/libp2p/libp2p_service.d.ts.map +1 -0
  130. package/dest/services/libp2p/libp2p_service.js +712 -0
  131. package/dest/services/peer-manager/metrics.d.ts +12 -0
  132. package/dest/services/peer-manager/metrics.d.ts.map +1 -0
  133. package/dest/services/peer-manager/metrics.js +33 -0
  134. package/dest/services/peer-manager/peer_manager.d.ts +94 -0
  135. package/dest/services/peer-manager/peer_manager.d.ts.map +1 -0
  136. package/dest/services/peer-manager/peer_manager.js +445 -0
  137. package/dest/services/peer-manager/peer_scoring.d.ts +28 -0
  138. package/dest/services/peer-manager/peer_scoring.d.ts.map +1 -0
  139. package/dest/services/peer-manager/peer_scoring.js +86 -0
  140. package/dest/services/reqresp/config.d.ts +16 -0
  141. package/dest/services/reqresp/config.d.ts.map +1 -0
  142. package/dest/services/reqresp/config.js +20 -0
  143. package/dest/services/reqresp/connection-sampler/batch_connection_sampler.d.ts +45 -0
  144. package/dest/services/reqresp/connection-sampler/batch_connection_sampler.d.ts.map +1 -0
  145. package/dest/services/reqresp/connection-sampler/batch_connection_sampler.js +88 -0
  146. package/dest/services/reqresp/connection-sampler/connection_sampler.d.ts +61 -0
  147. package/dest/services/reqresp/connection-sampler/connection_sampler.d.ts.map +1 -0
  148. package/dest/services/reqresp/connection-sampler/connection_sampler.js +181 -0
  149. package/dest/services/reqresp/index.d.ts +6 -0
  150. package/dest/services/reqresp/index.d.ts.map +1 -0
  151. package/dest/services/reqresp/index.js +4 -0
  152. package/dest/services/reqresp/interface.d.ts +116 -0
  153. package/dest/services/reqresp/interface.d.ts.map +1 -0
  154. package/dest/services/reqresp/interface.js +84 -0
  155. package/dest/services/reqresp/metrics.d.ts +15 -0
  156. package/dest/services/reqresp/metrics.d.ts.map +1 -0
  157. package/dest/services/reqresp/metrics.js +55 -0
  158. package/dest/services/reqresp/protocols/block.d.ts +4 -0
  159. package/dest/services/reqresp/protocols/block.d.ts.map +1 -0
  160. package/dest/services/reqresp/protocols/block.js +8 -0
  161. package/dest/services/reqresp/protocols/goodbye.d.ts +51 -0
  162. package/dest/services/reqresp/protocols/goodbye.d.ts.map +1 -0
  163. package/dest/services/reqresp/protocols/goodbye.js +87 -0
  164. package/dest/services/reqresp/protocols/index.d.ts +9 -0
  165. package/dest/services/reqresp/protocols/index.d.ts.map +1 -0
  166. package/dest/services/reqresp/protocols/index.js +7 -0
  167. package/dest/services/reqresp/protocols/ping.d.ts +9 -0
  168. package/dest/services/reqresp/protocols/ping.d.ts.map +1 -0
  169. package/dest/services/reqresp/protocols/ping.js +7 -0
  170. package/dest/services/reqresp/protocols/status.d.ts +9 -0
  171. package/dest/services/reqresp/protocols/status.d.ts.map +1 -0
  172. package/dest/services/reqresp/protocols/status.js +7 -0
  173. package/dest/services/reqresp/protocols/tx.d.ts +13 -0
  174. package/dest/services/reqresp/protocols/tx.d.ts.map +1 -0
  175. package/dest/services/reqresp/protocols/tx.js +20 -0
  176. package/dest/services/reqresp/rate-limiter/index.d.ts +2 -0
  177. package/dest/services/reqresp/rate-limiter/index.d.ts.map +1 -0
  178. package/dest/services/reqresp/rate-limiter/index.js +1 -0
  179. package/dest/services/reqresp/rate-limiter/rate_limiter.d.ts +102 -0
  180. package/dest/services/reqresp/rate-limiter/rate_limiter.d.ts.map +1 -0
  181. package/dest/services/reqresp/rate-limiter/rate_limiter.js +184 -0
  182. package/dest/services/reqresp/rate-limiter/rate_limits.d.ts +3 -0
  183. package/dest/services/reqresp/rate-limiter/rate_limits.d.ts.map +1 -0
  184. package/dest/services/reqresp/rate-limiter/rate_limits.js +54 -0
  185. package/dest/services/reqresp/reqresp.d.ts +166 -0
  186. package/dest/services/reqresp/reqresp.d.ts.map +1 -0
  187. package/dest/services/reqresp/reqresp.js +516 -0
  188. package/dest/services/reqresp/status.d.ts +31 -0
  189. package/dest/services/reqresp/status.d.ts.map +1 -0
  190. package/dest/services/reqresp/status.js +51 -0
  191. package/dest/services/service.d.ts +87 -0
  192. package/dest/services/service.d.ts.map +1 -0
  193. package/dest/services/service.js +5 -0
  194. package/dest/test-helpers/generate-peer-id-private-keys.d.ts +7 -0
  195. package/dest/test-helpers/generate-peer-id-private-keys.d.ts.map +1 -0
  196. package/dest/test-helpers/generate-peer-id-private-keys.js +13 -0
  197. package/dest/test-helpers/get-ports.d.ts +7 -0
  198. package/dest/test-helpers/get-ports.d.ts.map +1 -0
  199. package/dest/test-helpers/get-ports.js +8 -0
  200. package/dest/test-helpers/index.d.ts +6 -0
  201. package/dest/test-helpers/index.d.ts.map +1 -0
  202. package/dest/test-helpers/index.js +5 -0
  203. package/dest/test-helpers/make-enrs.d.ts +16 -0
  204. package/dest/test-helpers/make-enrs.d.ts.map +1 -0
  205. package/dest/test-helpers/make-enrs.js +32 -0
  206. package/dest/test-helpers/make-test-p2p-clients.d.ts +36 -0
  207. package/dest/test-helpers/make-test-p2p-clients.d.ts.map +1 -0
  208. package/dest/test-helpers/make-test-p2p-clients.js +68 -0
  209. package/dest/test-helpers/reqresp-nodes.d.ts +66 -0
  210. package/dest/test-helpers/reqresp-nodes.d.ts.map +1 -0
  211. package/dest/test-helpers/reqresp-nodes.js +207 -0
  212. package/dest/testbench/p2p_client_testbench_worker.d.ts +2 -0
  213. package/dest/testbench/p2p_client_testbench_worker.d.ts.map +1 -0
  214. package/dest/testbench/p2p_client_testbench_worker.js +132 -0
  215. package/dest/testbench/parse_log_file.d.ts +2 -0
  216. package/dest/testbench/parse_log_file.d.ts.map +1 -0
  217. package/dest/testbench/parse_log_file.js +131 -0
  218. package/dest/testbench/testbench.d.ts +2 -0
  219. package/dest/testbench/testbench.d.ts.map +1 -0
  220. package/dest/testbench/testbench.js +61 -0
  221. package/dest/testbench/worker_client_manager.d.ts +56 -0
  222. package/dest/testbench/worker_client_manager.d.ts.map +1 -0
  223. package/dest/testbench/worker_client_manager.js +266 -0
  224. package/dest/types/index.d.ts +32 -0
  225. package/dest/types/index.d.ts.map +1 -0
  226. package/dest/types/index.js +28 -0
  227. package/dest/util.d.ts +53 -0
  228. package/dest/util.d.ts.map +1 -0
  229. package/dest/util.js +140 -0
  230. package/dest/versioning.d.ts +12 -0
  231. package/dest/versioning.d.ts.map +1 -0
  232. package/dest/versioning.js +33 -0
  233. package/package.json +127 -0
  234. package/src/bootstrap/bootstrap.ts +146 -0
  235. package/src/client/factory.ts +89 -0
  236. package/src/client/index.ts +2 -0
  237. package/src/client/p2p_client.ts +754 -0
  238. package/src/config.ts +371 -0
  239. package/src/enr/generate-enr.ts +39 -0
  240. package/src/enr/index.ts +1 -0
  241. package/src/errors/reqresp.error.ts +35 -0
  242. package/src/index.ts +7 -0
  243. package/src/mem_pools/attestation_pool/attestation_pool.ts +62 -0
  244. package/src/mem_pools/attestation_pool/attestation_pool_test_suite.ts +230 -0
  245. package/src/mem_pools/attestation_pool/index.ts +2 -0
  246. package/src/mem_pools/attestation_pool/kv_attestation_pool.ts +159 -0
  247. package/src/mem_pools/attestation_pool/memory_attestation_pool.ts +161 -0
  248. package/src/mem_pools/attestation_pool/mocks.ts +44 -0
  249. package/src/mem_pools/index.ts +3 -0
  250. package/src/mem_pools/instrumentation.ts +126 -0
  251. package/src/mem_pools/interface.ts +12 -0
  252. package/src/mem_pools/tx_pool/aztec_kv_tx_pool.ts +309 -0
  253. package/src/mem_pools/tx_pool/index.ts +3 -0
  254. package/src/mem_pools/tx_pool/memory_tx_pool.ts +174 -0
  255. package/src/mem_pools/tx_pool/priority.ts +13 -0
  256. package/src/mem_pools/tx_pool/tx_pool.ts +76 -0
  257. package/src/mem_pools/tx_pool/tx_pool_test_suite.ts +130 -0
  258. package/src/msg_validators/attestation_validator/attestation_validator.ts +26 -0
  259. package/src/msg_validators/attestation_validator/index.ts +1 -0
  260. package/src/msg_validators/block_proposal_validator/block_proposal_validator.ts +29 -0
  261. package/src/msg_validators/block_proposal_validator/index.ts +1 -0
  262. package/src/msg_validators/index.ts +3 -0
  263. package/src/msg_validators/tx_validator/aggregate_tx_validator.ts +32 -0
  264. package/src/msg_validators/tx_validator/block_header_validator.ts +25 -0
  265. package/src/msg_validators/tx_validator/data_validator.ts +106 -0
  266. package/src/msg_validators/tx_validator/double_spend_validator.ts +38 -0
  267. package/src/msg_validators/tx_validator/index.ts +6 -0
  268. package/src/msg_validators/tx_validator/metadata_validator.ts +48 -0
  269. package/src/msg_validators/tx_validator/tx_proof_validator.ts +18 -0
  270. package/src/services/data_store.ts +235 -0
  271. package/src/services/discv5/discV5_service.ts +256 -0
  272. package/src/services/dummy_service.ts +134 -0
  273. package/src/services/encoding.ts +79 -0
  274. package/src/services/gossipsub/scoring.ts +13 -0
  275. package/src/services/index.ts +2 -0
  276. package/src/services/libp2p/libp2p_service.ts +871 -0
  277. package/src/services/peer-manager/metrics.ts +41 -0
  278. package/src/services/peer-manager/peer_manager.ts +530 -0
  279. package/src/services/peer-manager/peer_scoring.ts +105 -0
  280. package/src/services/reqresp/config.ts +35 -0
  281. package/src/services/reqresp/connection-sampler/batch_connection_sampler.ts +94 -0
  282. package/src/services/reqresp/connection-sampler/connection_sampler.ts +217 -0
  283. package/src/services/reqresp/index.ts +4 -0
  284. package/src/services/reqresp/interface.ts +185 -0
  285. package/src/services/reqresp/metrics.ts +57 -0
  286. package/src/services/reqresp/protocols/block.ts +15 -0
  287. package/src/services/reqresp/protocols/goodbye.ts +101 -0
  288. package/src/services/reqresp/protocols/index.ts +8 -0
  289. package/src/services/reqresp/protocols/ping.ts +8 -0
  290. package/src/services/reqresp/protocols/status.ts +8 -0
  291. package/src/services/reqresp/protocols/tx.ts +29 -0
  292. package/src/services/reqresp/rate-limiter/index.ts +1 -0
  293. package/src/services/reqresp/rate-limiter/rate_limiter.ts +228 -0
  294. package/src/services/reqresp/rate-limiter/rate_limits.ts +55 -0
  295. package/src/services/reqresp/reqresp.ts +661 -0
  296. package/src/services/reqresp/status.ts +59 -0
  297. package/src/services/service.ts +112 -0
  298. package/src/test-helpers/generate-peer-id-private-keys.ts +15 -0
  299. package/src/test-helpers/get-ports.ts +8 -0
  300. package/src/test-helpers/index.ts +5 -0
  301. package/src/test-helpers/make-enrs.ts +44 -0
  302. package/src/test-helpers/make-test-p2p-clients.ts +122 -0
  303. package/src/test-helpers/reqresp-nodes.ts +289 -0
  304. package/src/testbench/README.md +20 -0
  305. package/src/testbench/p2p_client_testbench_worker.ts +152 -0
  306. package/src/testbench/parse_log_file.ts +175 -0
  307. package/src/testbench/testbench.ts +66 -0
  308. package/src/testbench/worker_client_manager.ts +318 -0
  309. package/src/types/index.ts +36 -0
  310. package/src/util.ts +196 -0
  311. package/src/versioning.ts +50 -0
@@ -0,0 +1,516 @@
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;
7
+ }
8
+ import { createLogger } from '@aztec/foundation/log';
9
+ import { executeTimeout } from '@aztec/foundation/timer';
10
+ import { PeerErrorSeverity } from '@aztec/stdlib/p2p';
11
+ 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';
18
+ import { ReqRespMetrics } from './metrics.js';
19
+ import { RateLimitStatus, RequestResponseRateLimiter, prettyPrintRateLimitStatus } from './rate-limiter/rate_limiter.js';
20
+ import { ReqRespStatus, ReqRespStatusError, parseStatusChunk, prettyPrintReqRespStatus } from './status.js';
21
+ /**
22
+ * The Request Response Service
23
+ *
24
+ * 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.
26
+ *
27
+ * This service implements the request response sub protocol, it is heavily inspired from
28
+ * ethereum implementations of the same name.
29
+ *
30
+ * Note, responses get compressed in streamHandler
31
+ * so they get decompressed in readMessage
32
+ *
33
+ * see: https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/p2p-interface.md#the-reqresp-domain
34
+ */ export class ReqResp {
35
+ libp2p;
36
+ peerScoring;
37
+ logger;
38
+ overallRequestTimeoutMs;
39
+ 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 )
41
+ subProtocolHandlers;
42
+ subProtocolValidators;
43
+ connectionSampler;
44
+ rateLimiter;
45
+ snappyTransform;
46
+ metrics;
47
+ constructor(config, libp2p, peerScoring, telemetryClient = getTelemetryClient()){
48
+ this.libp2p = libp2p;
49
+ 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);
56
+ // Connection sampler is used to sample our connected peers
57
+ this.connectionSampler = new ConnectionSampler(libp2p);
58
+ this.snappyTransform = new SnappyTransform();
59
+ this.metrics = new ReqRespMetrics(telemetryClient);
60
+ }
61
+ get tracer() {
62
+ return this.metrics.tracer;
63
+ }
64
+ /**
65
+ * 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)){
71
+ await this.libp2p.handle(subProtocol, (data)=>void this.streamHandler(subProtocol, data).catch((err)=>this.logger.error(`Error on libp2p subprotocol ${subProtocol} handler`, err)));
72
+ }
73
+ this.rateLimiter.start();
74
+ }
75
+ /**
76
+ * Stop the reqresp service
77
+ */ async stop() {
78
+ // Unregister handlers in parallel
79
+ const unregisterPromises = Object.keys(this.subProtocolHandlers).map((protocol)=>this.libp2p.unhandle(protocol));
80
+ await Promise.all(unregisterPromises);
81
+ // Close connection sampler
82
+ await this.connectionSampler.stop();
83
+ this.logger.debug('ReqResp: Connection sampler stopped');
84
+ // Close streams in parallel
85
+ const closeStreamPromises = this.libp2p.getConnections().map((connection)=>connection.close());
86
+ await Promise.all(closeStreamPromises);
87
+ this.logger.debug('ReqResp: All active streams closed');
88
+ this.rateLimiter.stop();
89
+ this.logger.debug('ReqResp: Rate limiter stopped');
90
+ // NOTE: We assume libp2p instance is managed by the caller
91
+ }
92
+ /**
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
+ * Sends a request to a specific peer
294
+ *
295
+ * We first dial a particular protocol for the peer, this ensures that the peer knows
296
+ * what to respond with
297
+ *
298
+ *
299
+ * @param peerId - The peer to send the request to
300
+ * @param subProtocol - The protocol to use to request
301
+ * @param payload - The payload to send
302
+ * @returns If the request is successful, the response is returned, otherwise undefined
303
+ *
304
+ * @description
305
+ * This method attempts to open a stream with the specified peer, send the payload,
306
+ * and await a response.
307
+ * If an error occurs, it penalizes the peer and returns undefined.
308
+ *
309
+ * The method performs the following steps:
310
+ * - Opens a stream with the peer using the specified sub-protocol.
311
+ * - Sends the payload and awaits a response with a timeout.
312
+ *
313
+ * If the stream is not closed by the dialled peer, and a timeout occurs, then
314
+ * the stream is closed on the requester's end and sender (us) updates its peer score
315
+ */ async sendRequestToPeer(peerId, subProtocol, payload) {
316
+ let stream;
317
+ try {
318
+ 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;
325
+ } catch (e) {
326
+ this.metrics.recordRequestError(subProtocol);
327
+ this.handleResponseError(e, peerId, subProtocol);
328
+ } finally{
329
+ // Only close the stream if we created it
330
+ if (stream) {
331
+ try {
332
+ await this.connectionSampler.close(stream.id);
333
+ } catch (closeError) {
334
+ this.logger.error(`Error closing stream: ${closeError instanceof Error ? closeError.message : 'Unknown error'}`);
335
+ }
336
+ }
337
+ }
338
+ }
339
+ /**
340
+ * Handle a response error
341
+ *
342
+ * ReqResp errors are punished differently depending on the severity of the offense
343
+ *
344
+ * @param e - The error
345
+ * @param peerId - The peer id
346
+ * @param subProtocol - The sub protocol
347
+ * @returns If the error is non pubishable, then undefined is returned, otherwise the peer is penalized
348
+ */ handleResponseError(e, peerId, subProtocol) {
349
+ const severity = this.categorizeError(e, peerId, subProtocol);
350
+ if (severity) {
351
+ this.peerScoring.penalizePeer(peerId, severity);
352
+ }
353
+ }
354
+ /**
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
+ * Read a message returned from a stream into a single buffer
398
+ *
399
+ * The message is split into two components
400
+ * - The first chunk should contain a control byte, indicating the status of the response see `ReqRespStatus`
401
+ * - The second chunk should contain the response data
402
+ */ async readMessage(source) {
403
+ let statusBuffer;
404
+ const chunks = [];
405
+ try {
406
+ for await (const chunk of source){
407
+ if (statusBuffer === undefined) {
408
+ const firstChunkBuffer = chunk.subarray();
409
+ statusBuffer = parseStatusChunk(firstChunkBuffer);
410
+ } else {
411
+ chunks.push(chunk.subarray());
412
+ }
413
+ }
414
+ const messageData = Buffer.concat(chunks);
415
+ const message = this.snappyTransform.inboundTransformNoTopic(messageData);
416
+ return {
417
+ status: statusBuffer ?? ReqRespStatus.UNKNOWN,
418
+ data: message
419
+ };
420
+ } catch (e) {
421
+ 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
+ };
430
+ }
431
+ }
432
+ /**
433
+ * Stream Handler
434
+ * Reads the incoming stream, determines the protocol, then triggers the appropriate handler
435
+ *
436
+ * @param param0 - The incoming stream data
437
+ *
438
+ * @description
439
+ * An individual stream handler will be bound to each sub protocol, and handles returning data back
440
+ * to the requesting peer.
441
+ *
442
+ * The sub protocol handler interface is defined within `interface.ts` and will be assigned to the
443
+ * req resp service on start up.
444
+ *
445
+ * We check rate limits for each peer, note the peer will be penalised within the rate limiter implementation
446
+ * if they exceed their peer specific limits.
447
+ */ async streamHandler(protocol, { stream, connection }) {
448
+ this.metrics.recordRequestReceived(protocol);
449
+ try {
450
+ // Store a reference to from this for the async generator
451
+ 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}`);
454
+ throw new ReqRespStatusError(ReqRespStatus.RATE_LIMIT_EXCEEDED);
455
+ }
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);
477
+ 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;
482
+ }
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
+ } finally{
489
+ await stream.close();
490
+ }
491
+ }
492
+ async *sendErrorChunk(error) {
493
+ const errorChunk = Buffer.from([
494
+ error
495
+ ]);
496
+ yield new Uint8Array(errorChunk);
497
+ }
498
+ }
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);
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The error codes for the ReqResp protocol
3
+ */
4
+ export declare enum ReqRespStatus {
5
+ SUCCESS = 0,
6
+ RATE_LIMIT_EXCEEDED = 1,
7
+ BADLY_FORMED_REQUEST = 2,
8
+ UNKNOWN = 127
9
+ }
10
+ export declare class ReqRespStatusError extends Error {
11
+ /**
12
+ * The status code
13
+ */
14
+ status: ReqRespStatus;
15
+ constructor(status: ReqRespStatus);
16
+ }
17
+ /**
18
+ * Parse the status chunk
19
+ * @param chunk
20
+ * @returns
21
+ *
22
+ * @throws ReqRespStatusError if the chunk is not valid
23
+ */
24
+ export declare function parseStatusChunk(chunk: Uint8Array): ReqRespStatus;
25
+ /**
26
+ * Pretty print the ReqResp status
27
+ * @param status
28
+ * @returns
29
+ */
30
+ export declare function prettyPrintReqRespStatus(status: ReqRespStatus): "SUCCESS" | "RATE_LIMIT_EXCEEDED" | "BADLY_FORMED_REQUEST" | "UNKNOWN";
31
+ //# sourceMappingURL=status.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"status.d.ts","sourceRoot":"","sources":["../../../src/services/reqresp/status.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,oBAAY,aAAa;IACvB,OAAO,IAAI;IACX,mBAAmB,IAAI;IACvB,oBAAoB,IAAI;IACxB,OAAO,MAAM;CACd;AAED,qBAAa,kBAAmB,SAAQ,KAAK;IAC3C;;OAEG;IACH,MAAM,EAAE,aAAa,CAAC;gBAEV,MAAM,EAAE,aAAa;CAIlC;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,UAAU,GAAG,aAAa,CAWjE;AAED;;;;GAIG;AACH,wBAAgB,wBAAwB,CAAC,MAAM,EAAE,aAAa,0EAW7D"}
@@ -0,0 +1,51 @@
1
+ /**
2
+ * The error codes for the ReqResp protocol
3
+ */ export var ReqRespStatus = /*#__PURE__*/ function(ReqRespStatus) {
4
+ ReqRespStatus[ReqRespStatus["SUCCESS"] = 0] = "SUCCESS";
5
+ ReqRespStatus[ReqRespStatus["RATE_LIMIT_EXCEEDED"] = 1] = "RATE_LIMIT_EXCEEDED";
6
+ ReqRespStatus[ReqRespStatus["BADLY_FORMED_REQUEST"] = 2] = "BADLY_FORMED_REQUEST";
7
+ ReqRespStatus[ReqRespStatus["UNKNOWN"] = 127] = "UNKNOWN";
8
+ return ReqRespStatus;
9
+ }({});
10
+ export class ReqRespStatusError extends Error {
11
+ /**
12
+ * The status code
13
+ */ status;
14
+ constructor(status){
15
+ super(`ReqResp Error: ${prettyPrintReqRespStatus(status)}`);
16
+ this.status = status;
17
+ }
18
+ }
19
+ /**
20
+ * Parse the status chunk
21
+ * @param chunk
22
+ * @returns
23
+ *
24
+ * @throws ReqRespStatusError if the chunk is not valid
25
+ */ export function parseStatusChunk(chunk) {
26
+ if (chunk.length !== 1) {
27
+ throw new ReqRespStatusError(127);
28
+ }
29
+ const status = chunk[0];
30
+ // Check if status is a valid ReqRespStatus value
31
+ if (!(status in ReqRespStatus)) {
32
+ throw new ReqRespStatusError(127);
33
+ }
34
+ return status;
35
+ }
36
+ /**
37
+ * Pretty print the ReqResp status
38
+ * @param status
39
+ * @returns
40
+ */ export function prettyPrintReqRespStatus(status) {
41
+ switch(status){
42
+ case 0:
43
+ return 'SUCCESS';
44
+ case 1:
45
+ return 'RATE_LIMIT_EXCEEDED';
46
+ case 2:
47
+ return 'BADLY_FORMED_REQUEST';
48
+ case 127:
49
+ return 'UNKNOWN';
50
+ }
51
+ }