holosphere 2.0.0-alpha0 → 2.0.0-alpha10

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 (418) hide show
  1. package/CHANGELOG.md +473 -0
  2. package/FEATURES.md +431 -0
  3. package/LICENSE +29 -42
  4. package/LICENSE-AGPL.md +180 -0
  5. package/README.md +97 -16
  6. package/dist/2019-D2OG2idw.js +6680 -0
  7. package/dist/2019-D2OG2idw.js.map +1 -0
  8. package/dist/2019-EION3wKo.cjs +8 -0
  9. package/dist/2019-EION3wKo.cjs.map +1 -0
  10. package/dist/_commonjsHelpers-C37NGDzP.cjs +2 -0
  11. package/dist/_commonjsHelpers-C37NGDzP.cjs.map +1 -0
  12. package/dist/_commonjsHelpers-CUmg6egw.js +7 -0
  13. package/dist/_commonjsHelpers-CUmg6egw.js.map +1 -0
  14. package/dist/browser-BSniCNqO.js +3058 -0
  15. package/dist/browser-BSniCNqO.js.map +1 -0
  16. package/dist/browser-Cq59Ij19.cjs +2 -0
  17. package/dist/browser-Cq59Ij19.cjs.map +1 -0
  18. package/dist/cdn/holosphere.min.js +55 -0
  19. package/dist/cdn/holosphere.min.js.map +1 -0
  20. package/dist/cjs/holosphere.cjs +2 -0
  21. package/dist/cjs/holosphere.cjs.map +1 -0
  22. package/dist/esm/holosphere.js +53 -0
  23. package/dist/esm/holosphere.js.map +1 -0
  24. package/dist/index-DDGt_V9o.cjs +12 -0
  25. package/dist/index-DDGt_V9o.cjs.map +1 -0
  26. package/dist/index-DJXftyvB.js +39841 -0
  27. package/dist/index-DJXftyvB.js.map +1 -0
  28. package/dist/index-DMbdcMtK.cjs +18 -0
  29. package/dist/index-DMbdcMtK.cjs.map +1 -0
  30. package/dist/index-DeZ1xz_s.js +15104 -0
  31. package/dist/index-DeZ1xz_s.js.map +1 -0
  32. package/dist/indexeddb-storage-BFt6hMeF.js +176 -0
  33. package/dist/indexeddb-storage-BFt6hMeF.js.map +1 -0
  34. package/dist/indexeddb-storage-BK5tv4Sh.cjs +2 -0
  35. package/dist/indexeddb-storage-BK5tv4Sh.cjs.map +1 -0
  36. package/dist/memory-storage-C9HuoL2E.js +91 -0
  37. package/dist/memory-storage-C9HuoL2E.js.map +1 -0
  38. package/dist/memory-storage-Dao7jfYG.cjs +2 -0
  39. package/dist/memory-storage-Dao7jfYG.cjs.map +1 -0
  40. package/dist/secp256k1-BbKzbLtD.cjs +12 -0
  41. package/dist/secp256k1-BbKzbLtD.cjs.map +1 -0
  42. package/dist/secp256k1-CreY7Pcl.js +1890 -0
  43. package/dist/secp256k1-CreY7Pcl.js.map +1 -0
  44. package/docs/CONTRACTS.md +797 -0
  45. package/docs/FOSDEM_PROPOSAL.md +388 -0
  46. package/docs/LOCALFIRST.md +266 -0
  47. package/docs/api/ai_aggregation.js.html +333 -0
  48. package/docs/api/ai_breakdown.js.html +524 -0
  49. package/docs/api/ai_classifier.js.html +231 -0
  50. package/docs/api/ai_council.js.html +246 -0
  51. package/docs/api/ai_embeddings.js.html +304 -0
  52. package/docs/api/ai_federation-ai.js.html +338 -0
  53. package/docs/api/ai_h3-ai.js.html +970 -0
  54. package/docs/api/ai_index.js.html +124 -0
  55. package/docs/api/ai_json-ops.js.html +241 -0
  56. package/docs/api/ai_llm-service.js.html +239 -0
  57. package/docs/api/ai_nl-query.js.html +236 -0
  58. package/docs/api/ai_relationships.js.html +367 -0
  59. package/docs/api/ai_schema-extractor.js.html +235 -0
  60. package/docs/api/ai_spatial.js.html +307 -0
  61. package/docs/api/ai_tts.js.html +214 -0
  62. package/docs/api/content_social-protocols.js.html +180 -0
  63. package/docs/api/core_holosphere.js.html +757 -0
  64. package/docs/api/crypto_nostr-utils.js.html +306 -0
  65. package/docs/api/crypto_secp256k1.js.html +267 -0
  66. package/docs/api/data/search.json +1 -0
  67. package/docs/api/federation_discovery.js.html +337 -0
  68. package/docs/api/federation_handshake.js.html +478 -0
  69. package/docs/api/federation_hologram.js.html +1053 -0
  70. package/docs/api/federation_registry.js.html +389 -0
  71. package/docs/api/fonts/Inconsolata-Regular.ttf +0 -0
  72. package/docs/api/fonts/OpenSans-Regular.ttf +0 -0
  73. package/docs/api/fonts/WorkSans-Bold.ttf +0 -0
  74. package/docs/api/global.html +3 -0
  75. package/docs/api/hierarchical_upcast.js.html +128 -0
  76. package/docs/api/index.html +265 -0
  77. package/docs/api/index.js.html +1868 -0
  78. package/docs/api/lib_ai-methods.js.html +660 -0
  79. package/docs/api/lib_contract-methods.js.html +445 -0
  80. package/docs/api/lib_errors.js.html +56 -0
  81. package/docs/api/lib_federation-methods.js.html +348 -0
  82. package/docs/api/lib_index.js.html +33 -0
  83. package/docs/api/module-ai.html +5 -0
  84. package/docs/api/module-ai_aggregation-SmartAggregation.html +6 -0
  85. package/docs/api/module-ai_aggregation.SmartAggregation.html +3 -0
  86. package/docs/api/module-ai_aggregation.html +3 -0
  87. package/docs/api/module-ai_breakdown-TaskBreakdown.html +5 -0
  88. package/docs/api/module-ai_breakdown.TaskBreakdown.html +3 -0
  89. package/docs/api/module-ai_breakdown.html +3 -0
  90. package/docs/api/module-ai_classifier-Classifier.html +6 -0
  91. package/docs/api/module-ai_classifier.Classifier.html +3 -0
  92. package/docs/api/module-ai_classifier.html +3 -0
  93. package/docs/api/module-ai_council-Council.html +6 -0
  94. package/docs/api/module-ai_council.Council.html +3 -0
  95. package/docs/api/module-ai_council.html +3 -0
  96. package/docs/api/module-ai_embeddings-Embeddings.html +5 -0
  97. package/docs/api/module-ai_embeddings.Embeddings.html +3 -0
  98. package/docs/api/module-ai_embeddings.html +3 -0
  99. package/docs/api/module-ai_federation-ai-FederationAdvisor.html +6 -0
  100. package/docs/api/module-ai_federation-ai.FederationAdvisor.html +3 -0
  101. package/docs/api/module-ai_federation-ai.html +3 -0
  102. package/docs/api/module-ai_h3-ai-H3AI.html +6 -0
  103. package/docs/api/module-ai_h3-ai.H3AI.html +3 -0
  104. package/docs/api/module-ai_h3-ai.html +3 -0
  105. package/docs/api/module-ai_json-ops-JSONOps.html +5 -0
  106. package/docs/api/module-ai_json-ops.JSONOps.html +3 -0
  107. package/docs/api/module-ai_json-ops.html +3 -0
  108. package/docs/api/module-ai_llm-service-LLMService.html +5 -0
  109. package/docs/api/module-ai_llm-service.LLMService.html +3 -0
  110. package/docs/api/module-ai_llm-service.html +3 -0
  111. package/docs/api/module-ai_nl-query-NLQuery.html +5 -0
  112. package/docs/api/module-ai_nl-query.NLQuery.html +3 -0
  113. package/docs/api/module-ai_nl-query.html +3 -0
  114. package/docs/api/module-ai_relationships-RelationshipDiscovery.html +6 -0
  115. package/docs/api/module-ai_relationships.RelationshipDiscovery.html +3 -0
  116. package/docs/api/module-ai_relationships.html +3 -0
  117. package/docs/api/module-ai_schema-extractor-SchemaExtractor.html +5 -0
  118. package/docs/api/module-ai_schema-extractor.SchemaExtractor.html +3 -0
  119. package/docs/api/module-ai_schema-extractor.html +3 -0
  120. package/docs/api/module-ai_spatial-SpatialAnalysis.html +6 -0
  121. package/docs/api/module-ai_spatial.SpatialAnalysis.html +3 -0
  122. package/docs/api/module-ai_spatial.html +3 -0
  123. package/docs/api/module-ai_tts-TTS.html +5 -0
  124. package/docs/api/module-ai_tts.TTS.html +3 -0
  125. package/docs/api/module-ai_tts.html +3 -0
  126. package/docs/api/module-content_social-protocols.html +3 -0
  127. package/docs/api/module-core_holosphere-HoloSphere.html +6 -0
  128. package/docs/api/module-core_holosphere.HoloSphere.html +3 -0
  129. package/docs/api/module-core_holosphere.html +3 -0
  130. package/docs/api/module-crypto_nostr-utils.html +3 -0
  131. package/docs/api/module-crypto_secp256k1.html +3 -0
  132. package/docs/api/module-federation_hologram.html +3 -0
  133. package/docs/api/module-hierarchical_upcast.html +3 -0
  134. package/docs/api/module-holosphere-HoloSphereBase.html +3 -0
  135. package/docs/api/module-holosphere.html +3 -0
  136. package/docs/api/module-lib_ai-methods.html +3 -0
  137. package/docs/api/module-lib_contract-methods.html +3 -0
  138. package/docs/api/module-lib_errors-AuthorizationError.html +3 -0
  139. package/docs/api/module-lib_errors-ValidationError.html +3 -0
  140. package/docs/api/module-lib_errors.AuthorizationError.html +3 -0
  141. package/docs/api/module-lib_errors.ValidationError.html +3 -0
  142. package/docs/api/module-lib_errors.html +3 -0
  143. package/docs/api/module-lib_federation-methods.html +3 -0
  144. package/docs/api/module-lib_index.html +3 -0
  145. package/docs/api/module-schema_validator-ValidationError.html +3 -0
  146. package/docs/api/module-schema_validator.ValidationError.html +3 -0
  147. package/docs/api/module-schema_validator.html +3 -0
  148. package/docs/api/module-spatial_h3-operations.html +4 -0
  149. package/docs/api/module-storage_backend-factory.BackendFactory.html +3 -0
  150. package/docs/api/module-storage_backend-factory.html +3 -0
  151. package/docs/api/module-storage_backend-interface-StorageBackend.html +3 -0
  152. package/docs/api/module-storage_backend-interface.StorageBackend.html +3 -0
  153. package/docs/api/module-storage_backend-interface.html +3 -0
  154. package/docs/api/module-storage_backends_activitypub-backend-ActivityPubBackend.html +7 -0
  155. package/docs/api/module-storage_backends_activitypub-backend.ActivityPubBackend.html +3 -0
  156. package/docs/api/module-storage_backends_activitypub-backend.html +3 -0
  157. package/docs/api/module-storage_backends_activitypub_server-ActivityPubServer.html +8 -0
  158. package/docs/api/module-storage_backends_activitypub_server.ActivityPubServer.html +3 -0
  159. package/docs/api/module-storage_backends_activitypub_server.html +3 -0
  160. package/docs/api/module-storage_backends_gundb-backend-GunDBBackend.html +7 -0
  161. package/docs/api/module-storage_backends_gundb-backend.GunDBBackend.html +3 -0
  162. package/docs/api/module-storage_backends_gundb-backend.html +3 -0
  163. package/docs/api/module-storage_backends_nostr-backend-NostrBackend.html +8 -0
  164. package/docs/api/module-storage_backends_nostr-backend.NostrBackend.html +3 -0
  165. package/docs/api/module-storage_backends_nostr-backend.html +3 -0
  166. package/docs/api/module-storage_filesystem-storage-FileSystemStorage.html +5 -0
  167. package/docs/api/module-storage_filesystem-storage-browser-FileSystemStorage.html +3 -0
  168. package/docs/api/module-storage_filesystem-storage-browser.FileSystemStorage.html +3 -0
  169. package/docs/api/module-storage_filesystem-storage-browser.html +3 -0
  170. package/docs/api/module-storage_filesystem-storage.FileSystemStorage.html +3 -0
  171. package/docs/api/module-storage_filesystem-storage.html +3 -0
  172. package/docs/api/module-storage_global-tables.html +3 -0
  173. package/docs/api/module-storage_gun-async.html +3 -0
  174. package/docs/api/module-storage_gun-auth-GunAuth.html +5 -0
  175. package/docs/api/module-storage_gun-auth.GunAuth.html +3 -0
  176. package/docs/api/module-storage_gun-auth.html +3 -0
  177. package/docs/api/module-storage_gun-federation.html +3 -0
  178. package/docs/api/module-storage_gun-references-GunReferenceHandler.html +5 -0
  179. package/docs/api/module-storage_gun-references.GunReferenceHandler.html +3 -0
  180. package/docs/api/module-storage_gun-references.html +3 -0
  181. package/docs/api/module-storage_gun-schema-GunSchemaValidator.html +5 -0
  182. package/docs/api/module-storage_gun-schema.GunSchemaValidator.html +3 -0
  183. package/docs/api/module-storage_gun-schema.html +3 -0
  184. package/docs/api/module-storage_gun-wrapper.html +11 -0
  185. package/docs/api/module-storage_indexeddb-storage-IndexedDBStorage.html +5 -0
  186. package/docs/api/module-storage_indexeddb-storage.IndexedDBStorage.html +3 -0
  187. package/docs/api/module-storage_indexeddb-storage.html +3 -0
  188. package/docs/api/module-storage_key-storage-simple.html +3 -0
  189. package/docs/api/module-storage_key-storage.html +4 -0
  190. package/docs/api/module-storage_memory-storage-MemoryStorage.html +5 -0
  191. package/docs/api/module-storage_memory-storage.MemoryStorage.html +3 -0
  192. package/docs/api/module-storage_memory-storage.html +3 -0
  193. package/docs/api/module-storage_migration-MigrationTool.html +6 -0
  194. package/docs/api/module-storage_migration.MigrationTool.html +3 -0
  195. package/docs/api/module-storage_migration.html +3 -0
  196. package/docs/api/module-storage_nostr-async.html +18 -0
  197. package/docs/api/module-storage_nostr-client-LRUCache.html +3 -0
  198. package/docs/api/module-storage_nostr-client-NostrClient.html +7 -0
  199. package/docs/api/module-storage_nostr-client.NostrClient.html +15 -0
  200. package/docs/api/module-storage_nostr-client.html +6 -0
  201. package/docs/api/module-storage_nostr-wrapper.html +3 -0
  202. package/docs/api/module-storage_outbox-queue-OutboxQueue.html +4 -0
  203. package/docs/api/module-storage_outbox-queue.OutboxQueue.html +3 -0
  204. package/docs/api/module-storage_outbox-queue.html +3 -0
  205. package/docs/api/module-storage_persistent-storage-PersistentStorage.html +3 -0
  206. package/docs/api/module-storage_persistent-storage.html +4 -0
  207. package/docs/api/module-storage_sync-service-SyncService.html +5 -0
  208. package/docs/api/module-storage_sync-service.SyncService.html +3 -0
  209. package/docs/api/module-storage_sync-service.html +3 -0
  210. package/docs/api/module-storage_unified-storage.html +3 -0
  211. package/docs/api/module-subscriptions_manager.SubscriptionRegistry.html +3 -0
  212. package/docs/api/module-subscriptions_manager.html +3 -0
  213. package/docs/api/schema_validator.js.html +113 -0
  214. package/docs/api/scripts/core.js +726 -0
  215. package/docs/api/scripts/core.min.js +23 -0
  216. package/docs/api/scripts/resize.js +90 -0
  217. package/docs/api/scripts/search.js +265 -0
  218. package/docs/api/scripts/search.min.js +6 -0
  219. package/docs/api/scripts/third-party/Apache-License-2.0.txt +202 -0
  220. package/docs/api/scripts/third-party/fuse.js +9 -0
  221. package/docs/api/scripts/third-party/hljs-line-num-original.js +369 -0
  222. package/docs/api/scripts/third-party/hljs-line-num.js +1 -0
  223. package/docs/api/scripts/third-party/hljs-original.js +5171 -0
  224. package/docs/api/scripts/third-party/hljs.js +1 -0
  225. package/docs/api/scripts/third-party/popper.js +5 -0
  226. package/docs/api/scripts/third-party/tippy.js +1 -0
  227. package/docs/api/scripts/third-party/tocbot.js +672 -0
  228. package/docs/api/scripts/third-party/tocbot.min.js +1 -0
  229. package/docs/api/spatial_h3-operations.js.html +129 -0
  230. package/docs/api/storage_backend-factory.js.html +133 -0
  231. package/docs/api/storage_backend-interface.js.html +164 -0
  232. package/docs/api/storage_backends_activitypub-backend.js.html +298 -0
  233. package/docs/api/storage_backends_activitypub_server.js.html +678 -0
  234. package/docs/api/storage_backends_gundb-backend.js.html +878 -0
  235. package/docs/api/storage_backends_nostr-backend.js.html +254 -0
  236. package/docs/api/storage_filesystem-storage-browser.js.html +83 -0
  237. package/docs/api/storage_filesystem-storage.js.html +207 -0
  238. package/docs/api/storage_global-tables.js.html +116 -0
  239. package/docs/api/storage_gun-async.js.html +344 -0
  240. package/docs/api/storage_gun-auth.js.html +376 -0
  241. package/docs/api/storage_gun-federation.js.html +788 -0
  242. package/docs/api/storage_gun-references.js.html +212 -0
  243. package/docs/api/storage_gun-schema.js.html +309 -0
  244. package/docs/api/storage_gun-wrapper.js.html +645 -0
  245. package/docs/api/storage_indexeddb-storage.js.html +224 -0
  246. package/docs/api/storage_key-storage-simple.js.html +102 -0
  247. package/docs/api/storage_key-storage.js.html +171 -0
  248. package/docs/api/storage_memory-storage.js.html +128 -0
  249. package/docs/api/storage_migration.js.html +354 -0
  250. package/docs/api/storage_nostr-async.js.html +1076 -0
  251. package/docs/api/storage_nostr-client.js.html +1598 -0
  252. package/docs/api/storage_nostr-wrapper.js.html +218 -0
  253. package/docs/api/storage_outbox-queue.js.html +248 -0
  254. package/docs/api/storage_persistent-storage.js.html +160 -0
  255. package/docs/api/storage_sync-service.js.html +201 -0
  256. package/docs/api/storage_unified-storage.js.html +157 -0
  257. package/docs/api/styles/clean-jsdoc-theme-base.css +1159 -0
  258. package/docs/api/styles/clean-jsdoc-theme-dark.css +412 -0
  259. package/docs/api/styles/clean-jsdoc-theme-light.css +482 -0
  260. package/docs/api/styles/clean-jsdoc-theme-scrollbar.css +30 -0
  261. package/docs/api/styles/clean-jsdoc-theme-without-scrollbar.min.css +1 -0
  262. package/docs/api/styles/clean-jsdoc-theme.min.css +1 -0
  263. package/docs/api/subscriptions_manager.js.html +162 -0
  264. package/docs/contracts/api-interface.md +793 -0
  265. package/docs/data-model.md +476 -0
  266. package/docs/gun-async-usage.md +338 -0
  267. package/docs/plan.md +349 -0
  268. package/docs/quickstart.md +674 -0
  269. package/docs/research.md +362 -0
  270. package/docs/spec.md +244 -0
  271. package/docs/storage-backends.md +326 -0
  272. package/docs/tasks.md +947 -0
  273. package/examples/demo.html +47 -0
  274. package/examples/holosphere-widget.js +1242 -0
  275. package/examples/widget-demo.html +274 -0
  276. package/examples/widget.html +703 -0
  277. package/jsdoc.json +26 -0
  278. package/package.json +25 -7
  279. package/src/ai/aggregation.js +13 -2
  280. package/src/ai/breakdown.js +12 -2
  281. package/src/ai/classifier.js +14 -3
  282. package/src/ai/council.js +22 -7
  283. package/src/ai/embeddings.js +37 -15
  284. package/src/ai/federation-ai.js +13 -2
  285. package/src/ai/h3-ai.js +14 -2
  286. package/src/ai/index.js +16 -7
  287. package/src/ai/json-ops.js +18 -5
  288. package/src/ai/llm-service.js +62 -31
  289. package/src/ai/nl-query.js +12 -2
  290. package/src/ai/relationships.js +13 -2
  291. package/src/ai/schema-extractor.js +24 -10
  292. package/src/ai/spatial.js +13 -2
  293. package/src/ai/tts.js +25 -8
  294. package/src/cdn-entry.js +22 -0
  295. package/src/content/social-protocols.js +34 -25
  296. package/src/contracts/abis/Appreciative.json +1280 -0
  297. package/src/contracts/abis/AppreciativeFactory.json +101 -0
  298. package/src/contracts/abis/Bundle.json +1438 -0
  299. package/src/contracts/abis/BundleFactory.json +106 -0
  300. package/src/contracts/abis/Holon.json +881 -0
  301. package/src/contracts/abis/Holons.json +330 -0
  302. package/src/contracts/abis/Managed.json +1262 -0
  303. package/src/contracts/abis/ManagedFactory.json +149 -0
  304. package/src/contracts/abis/Membrane.json +261 -0
  305. package/src/contracts/abis/Splitter.json +1624 -0
  306. package/src/contracts/abis/SplitterFactory.json +220 -0
  307. package/src/contracts/abis/TestToken.json +321 -0
  308. package/src/contracts/abis/Zoned.json +1461 -0
  309. package/src/contracts/abis/ZonedFactory.json +154 -0
  310. package/src/contracts/chain-manager.js +403 -0
  311. package/src/contracts/deployer.js +500 -0
  312. package/src/contracts/event-listener.js +539 -0
  313. package/src/contracts/holon-contracts.js +359 -0
  314. package/src/contracts/index.js +82 -0
  315. package/src/contracts/networks.js +229 -0
  316. package/src/contracts/operations.js +687 -0
  317. package/src/contracts/queries.js +638 -0
  318. package/src/core/holosphere.js +487 -6
  319. package/src/crypto/nostr-utils.js +303 -0
  320. package/src/crypto/secp256k1.js +7 -2
  321. package/src/federation/handshake.js +475 -0
  322. package/src/federation/hologram.js +117 -3
  323. package/src/hierarchical/upcast.js +40 -25
  324. package/src/index.js +1501 -1909
  325. package/src/lib/ai-methods.js +657 -0
  326. package/src/lib/contract-methods.js +442 -0
  327. package/src/lib/errors.js +53 -0
  328. package/src/lib/federation-methods.js +345 -0
  329. package/src/lib/index.js +30 -0
  330. package/src/schema/validator.js +22 -3
  331. package/src/spatial/h3-operations.js +19 -3
  332. package/src/storage/backend-factory.js +7 -2
  333. package/src/storage/backend-interface.js +21 -2
  334. package/src/storage/backends/activitypub/server.js +25 -3
  335. package/src/storage/backends/activitypub-backend.js +25 -2
  336. package/src/storage/backends/gundb-backend.js +692 -50
  337. package/src/storage/backends/nostr-backend.js +116 -1
  338. package/src/storage/filesystem-storage-browser.js +42 -2
  339. package/src/storage/filesystem-storage.js +72 -5
  340. package/src/storage/global-tables.js +35 -3
  341. package/src/storage/gun-async.js +75 -15
  342. package/src/storage/gun-auth.js +373 -0
  343. package/src/storage/gun-federation.js +785 -0
  344. package/src/storage/gun-references.js +209 -0
  345. package/src/storage/gun-schema.js +306 -0
  346. package/src/storage/gun-wrapper.js +475 -54
  347. package/src/storage/indexeddb-storage.js +112 -13
  348. package/src/storage/key-storage-simple.js +32 -9
  349. package/src/storage/key-storage.js +45 -13
  350. package/src/storage/memory-storage.js +68 -2
  351. package/src/storage/migration.js +20 -7
  352. package/src/storage/nostr-async.js +412 -122
  353. package/src/storage/nostr-client.js +749 -76
  354. package/src/storage/nostr-wrapper.js +6 -2
  355. package/src/storage/outbox-queue.js +55 -18
  356. package/src/storage/persistent-storage.js +62 -14
  357. package/src/storage/sync-service.js +51 -17
  358. package/src/storage/unified-storage.js +154 -0
  359. package/src/subscriptions/manager.js +34 -17
  360. package/types/index.d.ts +133 -0
  361. package/vite.config.cdn.js +60 -0
  362. package/tests/unit/ai/aggregation.test.js +0 -295
  363. package/tests/unit/ai/breakdown.test.js +0 -446
  364. package/tests/unit/ai/classifier.test.js +0 -294
  365. package/tests/unit/ai/council.test.js +0 -262
  366. package/tests/unit/ai/embeddings.test.js +0 -384
  367. package/tests/unit/ai/federation-ai.test.js +0 -344
  368. package/tests/unit/ai/h3-ai.test.js +0 -458
  369. package/tests/unit/ai/index.test.js +0 -304
  370. package/tests/unit/ai/json-ops.test.js +0 -307
  371. package/tests/unit/ai/llm-service.test.js +0 -390
  372. package/tests/unit/ai/nl-query.test.js +0 -383
  373. package/tests/unit/ai/relationships.test.js +0 -311
  374. package/tests/unit/ai/schema-extractor.test.js +0 -384
  375. package/tests/unit/ai/spatial.test.js +0 -279
  376. package/tests/unit/ai/tts.test.js +0 -279
  377. package/tests/unit/content.test.js +0 -332
  378. package/tests/unit/contract/core.test.js +0 -88
  379. package/tests/unit/contract/crypto.test.js +0 -198
  380. package/tests/unit/contract/data.test.js +0 -223
  381. package/tests/unit/contract/federation.test.js +0 -181
  382. package/tests/unit/contract/hierarchical.test.js +0 -113
  383. package/tests/unit/contract/schema.test.js +0 -114
  384. package/tests/unit/contract/social.test.js +0 -217
  385. package/tests/unit/contract/spatial.test.js +0 -110
  386. package/tests/unit/contract/subscriptions.test.js +0 -128
  387. package/tests/unit/contract/utils.test.js +0 -159
  388. package/tests/unit/core.test.js +0 -152
  389. package/tests/unit/crypto.test.js +0 -328
  390. package/tests/unit/federation.test.js +0 -234
  391. package/tests/unit/gun-async.test.js +0 -252
  392. package/tests/unit/hierarchical.test.js +0 -399
  393. package/tests/unit/integration/scenario-01-geographic-storage.test.js +0 -74
  394. package/tests/unit/integration/scenario-02-federation.test.js +0 -76
  395. package/tests/unit/integration/scenario-03-subscriptions.test.js +0 -102
  396. package/tests/unit/integration/scenario-04-validation.test.js +0 -129
  397. package/tests/unit/integration/scenario-05-hierarchy.test.js +0 -125
  398. package/tests/unit/integration/scenario-06-social.test.js +0 -135
  399. package/tests/unit/integration/scenario-07-persistence.test.js +0 -130
  400. package/tests/unit/integration/scenario-08-authorization.test.js +0 -161
  401. package/tests/unit/integration/scenario-09-cross-dimensional.test.js +0 -139
  402. package/tests/unit/integration/scenario-10-cross-holosphere-capabilities.test.js +0 -357
  403. package/tests/unit/integration/scenario-11-cross-holosphere-federation.test.js +0 -410
  404. package/tests/unit/integration/scenario-12-capability-federated-read.test.js +0 -719
  405. package/tests/unit/performance/benchmark.test.js +0 -85
  406. package/tests/unit/schema.test.js +0 -213
  407. package/tests/unit/spatial.test.js +0 -158
  408. package/tests/unit/storage.test.js +0 -195
  409. package/tests/unit/subscriptions.test.js +0 -328
  410. package/tests/unit/test-data-permanence-debug.js +0 -197
  411. package/tests/unit/test-data-permanence.js +0 -340
  412. package/tests/unit/test-key-persistence-fixed.js +0 -148
  413. package/tests/unit/test-key-persistence.js +0 -172
  414. package/tests/unit/test-relay-permanence.js +0 -376
  415. package/tests/unit/test-second-node.js +0 -95
  416. package/tests/unit/test-simple-write.js +0 -89
  417. /package/{cleanup-test-data.js → scripts/cleanup-test-data.js} +0 -0
  418. /package/{test-ai-real-api.js → scripts/test-ai-real-api.js} +0 -0
@@ -0,0 +1,1890 @@
1
+ import { H as Hash, a as ahash, t as toBytes, c as clean, b as aexists, d as abytes, e as bytesToHex, i as isBytes, h as hexToBytes, f as concatBytes, g as anumber, r as randomBytes, s as sha256 } from "./index-DJXftyvB.js";
2
+ class HMAC extends Hash {
3
+ constructor(hash, _key) {
4
+ super();
5
+ this.finished = false;
6
+ this.destroyed = false;
7
+ ahash(hash);
8
+ const key = toBytes(_key);
9
+ this.iHash = hash.create();
10
+ if (typeof this.iHash.update !== "function")
11
+ throw new Error("Expected instance of class which extends utils.Hash");
12
+ this.blockLen = this.iHash.blockLen;
13
+ this.outputLen = this.iHash.outputLen;
14
+ const blockLen = this.blockLen;
15
+ const pad = new Uint8Array(blockLen);
16
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
17
+ for (let i = 0; i < pad.length; i++)
18
+ pad[i] ^= 54;
19
+ this.iHash.update(pad);
20
+ this.oHash = hash.create();
21
+ for (let i = 0; i < pad.length; i++)
22
+ pad[i] ^= 54 ^ 92;
23
+ this.oHash.update(pad);
24
+ clean(pad);
25
+ }
26
+ update(buf) {
27
+ aexists(this);
28
+ this.iHash.update(buf);
29
+ return this;
30
+ }
31
+ digestInto(out) {
32
+ aexists(this);
33
+ abytes(out, this.outputLen);
34
+ this.finished = true;
35
+ this.iHash.digestInto(out);
36
+ this.oHash.update(out);
37
+ this.oHash.digestInto(out);
38
+ this.destroy();
39
+ }
40
+ digest() {
41
+ const out = new Uint8Array(this.oHash.outputLen);
42
+ this.digestInto(out);
43
+ return out;
44
+ }
45
+ _cloneInto(to) {
46
+ to || (to = Object.create(Object.getPrototypeOf(this), {}));
47
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
48
+ to = to;
49
+ to.finished = finished;
50
+ to.destroyed = destroyed;
51
+ to.blockLen = blockLen;
52
+ to.outputLen = outputLen;
53
+ to.oHash = oHash._cloneInto(to.oHash);
54
+ to.iHash = iHash._cloneInto(to.iHash);
55
+ return to;
56
+ }
57
+ clone() {
58
+ return this._cloneInto();
59
+ }
60
+ destroy() {
61
+ this.destroyed = true;
62
+ this.oHash.destroy();
63
+ this.iHash.destroy();
64
+ }
65
+ }
66
+ const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
67
+ hmac.create = (hash, key) => new HMAC(hash, key);
68
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
69
+ const _0n$3 = /* @__PURE__ */ BigInt(0);
70
+ const _1n$3 = /* @__PURE__ */ BigInt(1);
71
+ function _abool2(value, title = "") {
72
+ if (typeof value !== "boolean") {
73
+ const prefix = title && `"${title}"`;
74
+ throw new Error(prefix + "expected boolean, got type=" + typeof value);
75
+ }
76
+ return value;
77
+ }
78
+ function _abytes2(value, length, title = "") {
79
+ const bytes = isBytes(value);
80
+ const len = value?.length;
81
+ const needsLen = length !== void 0;
82
+ if (!bytes || needsLen && len !== length) {
83
+ const prefix = title && `"${title}" `;
84
+ const ofLen = needsLen ? ` of length ${length}` : "";
85
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
86
+ throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
87
+ }
88
+ return value;
89
+ }
90
+ function numberToHexUnpadded(num) {
91
+ const hex = num.toString(16);
92
+ return hex.length & 1 ? "0" + hex : hex;
93
+ }
94
+ function hexToNumber(hex) {
95
+ if (typeof hex !== "string")
96
+ throw new Error("hex string expected, got " + typeof hex);
97
+ return hex === "" ? _0n$3 : BigInt("0x" + hex);
98
+ }
99
+ function bytesToNumberBE(bytes) {
100
+ return hexToNumber(bytesToHex(bytes));
101
+ }
102
+ function bytesToNumberLE(bytes) {
103
+ abytes(bytes);
104
+ return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
105
+ }
106
+ function numberToBytesBE(n, len) {
107
+ return hexToBytes(n.toString(16).padStart(len * 2, "0"));
108
+ }
109
+ function numberToBytesLE(n, len) {
110
+ return numberToBytesBE(n, len).reverse();
111
+ }
112
+ function ensureBytes(title, hex, expectedLength) {
113
+ let res;
114
+ if (typeof hex === "string") {
115
+ try {
116
+ res = hexToBytes(hex);
117
+ } catch (e) {
118
+ throw new Error(title + " must be hex string or Uint8Array, cause: " + e);
119
+ }
120
+ } else if (isBytes(hex)) {
121
+ res = Uint8Array.from(hex);
122
+ } else {
123
+ throw new Error(title + " must be hex string or Uint8Array");
124
+ }
125
+ res.length;
126
+ return res;
127
+ }
128
+ const isPosBig = (n) => typeof n === "bigint" && _0n$3 <= n;
129
+ function inRange(n, min, max) {
130
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
131
+ }
132
+ function aInRange(title, n, min, max) {
133
+ if (!inRange(n, min, max))
134
+ throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
135
+ }
136
+ function bitLen(n) {
137
+ let len;
138
+ for (len = 0; n > _0n$3; n >>= _1n$3, len += 1)
139
+ ;
140
+ return len;
141
+ }
142
+ const bitMask = (n) => (_1n$3 << BigInt(n)) - _1n$3;
143
+ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
144
+ if (typeof hashLen !== "number" || hashLen < 2)
145
+ throw new Error("hashLen must be a number");
146
+ if (typeof qByteLen !== "number" || qByteLen < 2)
147
+ throw new Error("qByteLen must be a number");
148
+ if (typeof hmacFn !== "function")
149
+ throw new Error("hmacFn must be a function");
150
+ const u8n = (len) => new Uint8Array(len);
151
+ const u8of = (byte) => Uint8Array.of(byte);
152
+ let v = u8n(hashLen);
153
+ let k = u8n(hashLen);
154
+ let i = 0;
155
+ const reset = () => {
156
+ v.fill(1);
157
+ k.fill(0);
158
+ i = 0;
159
+ };
160
+ const h = (...b) => hmacFn(k, v, ...b);
161
+ const reseed = (seed = u8n(0)) => {
162
+ k = h(u8of(0), seed);
163
+ v = h();
164
+ if (seed.length === 0)
165
+ return;
166
+ k = h(u8of(1), seed);
167
+ v = h();
168
+ };
169
+ const gen = () => {
170
+ if (i++ >= 1e3)
171
+ throw new Error("drbg: tried 1000 values");
172
+ let len = 0;
173
+ const out = [];
174
+ while (len < qByteLen) {
175
+ v = h();
176
+ const sl = v.slice();
177
+ out.push(sl);
178
+ len += v.length;
179
+ }
180
+ return concatBytes(...out);
181
+ };
182
+ const genUntil = (seed, pred) => {
183
+ reset();
184
+ reseed(seed);
185
+ let res = void 0;
186
+ while (!(res = pred(gen())))
187
+ reseed();
188
+ reset();
189
+ return res;
190
+ };
191
+ return genUntil;
192
+ }
193
+ function _validateObject(object, fields, optFields = {}) {
194
+ if (!object || typeof object !== "object")
195
+ throw new Error("expected valid options object");
196
+ function checkField(fieldName, expectedType, isOpt) {
197
+ const val = object[fieldName];
198
+ if (isOpt && val === void 0)
199
+ return;
200
+ const current = typeof val;
201
+ if (current !== expectedType || val === null)
202
+ throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
203
+ }
204
+ Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
205
+ Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
206
+ }
207
+ function memoized(fn) {
208
+ const map = /* @__PURE__ */ new WeakMap();
209
+ return (arg, ...args) => {
210
+ const val = map.get(arg);
211
+ if (val !== void 0)
212
+ return val;
213
+ const computed = fn(arg, ...args);
214
+ map.set(arg, computed);
215
+ return computed;
216
+ };
217
+ }
218
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
219
+ const _0n$2 = BigInt(0), _1n$2 = BigInt(1), _2n$2 = /* @__PURE__ */ BigInt(2), _3n$1 = /* @__PURE__ */ BigInt(3);
220
+ const _4n$1 = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _7n = /* @__PURE__ */ BigInt(7);
221
+ const _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);
222
+ function mod(a, b) {
223
+ const result = a % b;
224
+ return result >= _0n$2 ? result : b + result;
225
+ }
226
+ function pow2(x, power, modulo) {
227
+ let res = x;
228
+ while (power-- > _0n$2) {
229
+ res *= res;
230
+ res %= modulo;
231
+ }
232
+ return res;
233
+ }
234
+ function invert(number, modulo) {
235
+ if (number === _0n$2)
236
+ throw new Error("invert: expected non-zero number");
237
+ if (modulo <= _0n$2)
238
+ throw new Error("invert: expected positive modulus, got " + modulo);
239
+ let a = mod(number, modulo);
240
+ let b = modulo;
241
+ let x = _0n$2, u = _1n$2;
242
+ while (a !== _0n$2) {
243
+ const q = b / a;
244
+ const r = b % a;
245
+ const m = x - u * q;
246
+ b = a, a = r, x = u, u = m;
247
+ }
248
+ const gcd = b;
249
+ if (gcd !== _1n$2)
250
+ throw new Error("invert: does not exist");
251
+ return mod(x, modulo);
252
+ }
253
+ function assertIsSquare(Fp, root, n) {
254
+ if (!Fp.eql(Fp.sqr(root), n))
255
+ throw new Error("Cannot find square root");
256
+ }
257
+ function sqrt3mod4(Fp, n) {
258
+ const p1div4 = (Fp.ORDER + _1n$2) / _4n$1;
259
+ const root = Fp.pow(n, p1div4);
260
+ assertIsSquare(Fp, root, n);
261
+ return root;
262
+ }
263
+ function sqrt5mod8(Fp, n) {
264
+ const p5div8 = (Fp.ORDER - _5n) / _8n;
265
+ const n2 = Fp.mul(n, _2n$2);
266
+ const v = Fp.pow(n2, p5div8);
267
+ const nv = Fp.mul(n, v);
268
+ const i = Fp.mul(Fp.mul(nv, _2n$2), v);
269
+ const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
270
+ assertIsSquare(Fp, root, n);
271
+ return root;
272
+ }
273
+ function sqrt9mod16(P) {
274
+ const Fp_ = Field(P);
275
+ const tn = tonelliShanks(P);
276
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
277
+ const c2 = tn(Fp_, c1);
278
+ const c3 = tn(Fp_, Fp_.neg(c1));
279
+ const c4 = (P + _7n) / _16n;
280
+ return (Fp, n) => {
281
+ let tv1 = Fp.pow(n, c4);
282
+ let tv2 = Fp.mul(tv1, c1);
283
+ const tv3 = Fp.mul(tv1, c2);
284
+ const tv4 = Fp.mul(tv1, c3);
285
+ const e1 = Fp.eql(Fp.sqr(tv2), n);
286
+ const e2 = Fp.eql(Fp.sqr(tv3), n);
287
+ tv1 = Fp.cmov(tv1, tv2, e1);
288
+ tv2 = Fp.cmov(tv4, tv3, e2);
289
+ const e3 = Fp.eql(Fp.sqr(tv2), n);
290
+ const root = Fp.cmov(tv1, tv2, e3);
291
+ assertIsSquare(Fp, root, n);
292
+ return root;
293
+ };
294
+ }
295
+ function tonelliShanks(P) {
296
+ if (P < _3n$1)
297
+ throw new Error("sqrt is not defined for small field");
298
+ let Q = P - _1n$2;
299
+ let S = 0;
300
+ while (Q % _2n$2 === _0n$2) {
301
+ Q /= _2n$2;
302
+ S++;
303
+ }
304
+ let Z = _2n$2;
305
+ const _Fp = Field(P);
306
+ while (FpLegendre(_Fp, Z) === 1) {
307
+ if (Z++ > 1e3)
308
+ throw new Error("Cannot find square root: probably non-prime P");
309
+ }
310
+ if (S === 1)
311
+ return sqrt3mod4;
312
+ let cc = _Fp.pow(Z, Q);
313
+ const Q1div2 = (Q + _1n$2) / _2n$2;
314
+ return function tonelliSlow(Fp, n) {
315
+ if (Fp.is0(n))
316
+ return n;
317
+ if (FpLegendre(Fp, n) !== 1)
318
+ throw new Error("Cannot find square root");
319
+ let M = S;
320
+ let c = Fp.mul(Fp.ONE, cc);
321
+ let t = Fp.pow(n, Q);
322
+ let R = Fp.pow(n, Q1div2);
323
+ while (!Fp.eql(t, Fp.ONE)) {
324
+ if (Fp.is0(t))
325
+ return Fp.ZERO;
326
+ let i = 1;
327
+ let t_tmp = Fp.sqr(t);
328
+ while (!Fp.eql(t_tmp, Fp.ONE)) {
329
+ i++;
330
+ t_tmp = Fp.sqr(t_tmp);
331
+ if (i === M)
332
+ throw new Error("Cannot find square root");
333
+ }
334
+ const exponent = _1n$2 << BigInt(M - i - 1);
335
+ const b = Fp.pow(c, exponent);
336
+ M = i;
337
+ c = Fp.sqr(b);
338
+ t = Fp.mul(t, c);
339
+ R = Fp.mul(R, b);
340
+ }
341
+ return R;
342
+ };
343
+ }
344
+ function FpSqrt(P) {
345
+ if (P % _4n$1 === _3n$1)
346
+ return sqrt3mod4;
347
+ if (P % _8n === _5n)
348
+ return sqrt5mod8;
349
+ if (P % _16n === _9n)
350
+ return sqrt9mod16(P);
351
+ return tonelliShanks(P);
352
+ }
353
+ const FIELD_FIELDS = [
354
+ "create",
355
+ "isValid",
356
+ "is0",
357
+ "neg",
358
+ "inv",
359
+ "sqrt",
360
+ "sqr",
361
+ "eql",
362
+ "add",
363
+ "sub",
364
+ "mul",
365
+ "pow",
366
+ "div",
367
+ "addN",
368
+ "subN",
369
+ "mulN",
370
+ "sqrN"
371
+ ];
372
+ function validateField(field) {
373
+ const initial = {
374
+ ORDER: "bigint",
375
+ MASK: "bigint",
376
+ BYTES: "number",
377
+ BITS: "number"
378
+ };
379
+ const opts = FIELD_FIELDS.reduce((map, val) => {
380
+ map[val] = "function";
381
+ return map;
382
+ }, initial);
383
+ _validateObject(field, opts);
384
+ return field;
385
+ }
386
+ function FpPow(Fp, num, power) {
387
+ if (power < _0n$2)
388
+ throw new Error("invalid exponent, negatives unsupported");
389
+ if (power === _0n$2)
390
+ return Fp.ONE;
391
+ if (power === _1n$2)
392
+ return num;
393
+ let p = Fp.ONE;
394
+ let d = num;
395
+ while (power > _0n$2) {
396
+ if (power & _1n$2)
397
+ p = Fp.mul(p, d);
398
+ d = Fp.sqr(d);
399
+ power >>= _1n$2;
400
+ }
401
+ return p;
402
+ }
403
+ function FpInvertBatch(Fp, nums, passZero = false) {
404
+ const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
405
+ const multipliedAcc = nums.reduce((acc, num, i) => {
406
+ if (Fp.is0(num))
407
+ return acc;
408
+ inverted[i] = acc;
409
+ return Fp.mul(acc, num);
410
+ }, Fp.ONE);
411
+ const invertedAcc = Fp.inv(multipliedAcc);
412
+ nums.reduceRight((acc, num, i) => {
413
+ if (Fp.is0(num))
414
+ return acc;
415
+ inverted[i] = Fp.mul(acc, inverted[i]);
416
+ return Fp.mul(acc, num);
417
+ }, invertedAcc);
418
+ return inverted;
419
+ }
420
+ function FpLegendre(Fp, n) {
421
+ const p1mod2 = (Fp.ORDER - _1n$2) / _2n$2;
422
+ const powered = Fp.pow(n, p1mod2);
423
+ const yes = Fp.eql(powered, Fp.ONE);
424
+ const zero = Fp.eql(powered, Fp.ZERO);
425
+ const no = Fp.eql(powered, Fp.neg(Fp.ONE));
426
+ if (!yes && !zero && !no)
427
+ throw new Error("invalid Legendre symbol result");
428
+ return yes ? 1 : zero ? 0 : -1;
429
+ }
430
+ function nLength(n, nBitLength) {
431
+ if (nBitLength !== void 0)
432
+ anumber(nBitLength);
433
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
434
+ const nByteLength = Math.ceil(_nBitLength / 8);
435
+ return { nBitLength: _nBitLength, nByteLength };
436
+ }
437
+ function Field(ORDER, bitLenOrOpts, isLE = false, opts = {}) {
438
+ if (ORDER <= _0n$2)
439
+ throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
440
+ let _nbitLength = void 0;
441
+ let _sqrt = void 0;
442
+ let modFromBytes = false;
443
+ let allowedLengths = void 0;
444
+ if (typeof bitLenOrOpts === "object" && bitLenOrOpts != null) {
445
+ if (opts.sqrt || isLE)
446
+ throw new Error("cannot specify opts in two arguments");
447
+ const _opts = bitLenOrOpts;
448
+ if (_opts.BITS)
449
+ _nbitLength = _opts.BITS;
450
+ if (_opts.sqrt)
451
+ _sqrt = _opts.sqrt;
452
+ if (typeof _opts.isLE === "boolean")
453
+ isLE = _opts.isLE;
454
+ if (typeof _opts.modFromBytes === "boolean")
455
+ modFromBytes = _opts.modFromBytes;
456
+ allowedLengths = _opts.allowedLengths;
457
+ } else {
458
+ if (typeof bitLenOrOpts === "number")
459
+ _nbitLength = bitLenOrOpts;
460
+ if (opts.sqrt)
461
+ _sqrt = opts.sqrt;
462
+ }
463
+ const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);
464
+ if (BYTES > 2048)
465
+ throw new Error("invalid field: expected ORDER of <= 2048 bytes");
466
+ let sqrtP;
467
+ const f = Object.freeze({
468
+ ORDER,
469
+ isLE,
470
+ BITS,
471
+ BYTES,
472
+ MASK: bitMask(BITS),
473
+ ZERO: _0n$2,
474
+ ONE: _1n$2,
475
+ allowedLengths,
476
+ create: (num) => mod(num, ORDER),
477
+ isValid: (num) => {
478
+ if (typeof num !== "bigint")
479
+ throw new Error("invalid field element: expected bigint, got " + typeof num);
480
+ return _0n$2 <= num && num < ORDER;
481
+ },
482
+ is0: (num) => num === _0n$2,
483
+ // is valid and invertible
484
+ isValidNot0: (num) => !f.is0(num) && f.isValid(num),
485
+ isOdd: (num) => (num & _1n$2) === _1n$2,
486
+ neg: (num) => mod(-num, ORDER),
487
+ eql: (lhs, rhs) => lhs === rhs,
488
+ sqr: (num) => mod(num * num, ORDER),
489
+ add: (lhs, rhs) => mod(lhs + rhs, ORDER),
490
+ sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
491
+ mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
492
+ pow: (num, power) => FpPow(f, num, power),
493
+ div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
494
+ // Same as above, but doesn't normalize
495
+ sqrN: (num) => num * num,
496
+ addN: (lhs, rhs) => lhs + rhs,
497
+ subN: (lhs, rhs) => lhs - rhs,
498
+ mulN: (lhs, rhs) => lhs * rhs,
499
+ inv: (num) => invert(num, ORDER),
500
+ sqrt: _sqrt || ((n) => {
501
+ if (!sqrtP)
502
+ sqrtP = FpSqrt(ORDER);
503
+ return sqrtP(f, n);
504
+ }),
505
+ toBytes: (num) => isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES),
506
+ fromBytes: (bytes, skipValidation = true) => {
507
+ if (allowedLengths) {
508
+ if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
509
+ throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
510
+ }
511
+ const padded = new Uint8Array(BYTES);
512
+ padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
513
+ bytes = padded;
514
+ }
515
+ if (bytes.length !== BYTES)
516
+ throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
517
+ let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
518
+ if (modFromBytes)
519
+ scalar = mod(scalar, ORDER);
520
+ if (!skipValidation) {
521
+ if (!f.isValid(scalar))
522
+ throw new Error("invalid field element: outside of range 0..ORDER");
523
+ }
524
+ return scalar;
525
+ },
526
+ // TODO: we don't need it here, move out to separate fn
527
+ invertBatch: (lst) => FpInvertBatch(f, lst),
528
+ // We can't move this out because Fp6, Fp12 implement it
529
+ // and it's unclear what to return in there.
530
+ cmov: (a, b, c) => c ? b : a
531
+ });
532
+ return Object.freeze(f);
533
+ }
534
+ function getFieldBytesLength(fieldOrder) {
535
+ if (typeof fieldOrder !== "bigint")
536
+ throw new Error("field order must be bigint");
537
+ const bitLength = fieldOrder.toString(2).length;
538
+ return Math.ceil(bitLength / 8);
539
+ }
540
+ function getMinHashLength(fieldOrder) {
541
+ const length = getFieldBytesLength(fieldOrder);
542
+ return length + Math.ceil(length / 2);
543
+ }
544
+ function mapHashToField(key, fieldOrder, isLE = false) {
545
+ const len = key.length;
546
+ const fieldLen = getFieldBytesLength(fieldOrder);
547
+ const minLen = getMinHashLength(fieldOrder);
548
+ if (len < 16 || len < minLen || len > 1024)
549
+ throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
550
+ const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
551
+ const reduced = mod(num, fieldOrder - _1n$2) + _1n$2;
552
+ return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
553
+ }
554
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
555
+ const _0n$1 = BigInt(0);
556
+ const _1n$1 = BigInt(1);
557
+ function negateCt(condition, item) {
558
+ const neg = item.negate();
559
+ return condition ? neg : item;
560
+ }
561
+ function normalizeZ(c, points) {
562
+ const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
563
+ return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
564
+ }
565
+ function validateW(W, bits) {
566
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
567
+ throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
568
+ }
569
+ function calcWOpts(W, scalarBits) {
570
+ validateW(W, scalarBits);
571
+ const windows = Math.ceil(scalarBits / W) + 1;
572
+ const windowSize = 2 ** (W - 1);
573
+ const maxNumber = 2 ** W;
574
+ const mask = bitMask(W);
575
+ const shiftBy = BigInt(W);
576
+ return { windows, windowSize, mask, maxNumber, shiftBy };
577
+ }
578
+ function calcOffsets(n, window, wOpts) {
579
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
580
+ let wbits = Number(n & mask);
581
+ let nextN = n >> shiftBy;
582
+ if (wbits > windowSize) {
583
+ wbits -= maxNumber;
584
+ nextN += _1n$1;
585
+ }
586
+ const offsetStart = window * windowSize;
587
+ const offset = offsetStart + Math.abs(wbits) - 1;
588
+ const isZero = wbits === 0;
589
+ const isNeg = wbits < 0;
590
+ const isNegF = window % 2 !== 0;
591
+ const offsetF = offsetStart;
592
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
593
+ }
594
+ function validateMSMPoints(points, c) {
595
+ if (!Array.isArray(points))
596
+ throw new Error("array expected");
597
+ points.forEach((p, i) => {
598
+ if (!(p instanceof c))
599
+ throw new Error("invalid point at index " + i);
600
+ });
601
+ }
602
+ function validateMSMScalars(scalars, field) {
603
+ if (!Array.isArray(scalars))
604
+ throw new Error("array of scalars expected");
605
+ scalars.forEach((s, i) => {
606
+ if (!field.isValid(s))
607
+ throw new Error("invalid scalar at index " + i);
608
+ });
609
+ }
610
+ const pointPrecomputes = /* @__PURE__ */ new WeakMap();
611
+ const pointWindowSizes = /* @__PURE__ */ new WeakMap();
612
+ function getW(P) {
613
+ return pointWindowSizes.get(P) || 1;
614
+ }
615
+ function assert0(n) {
616
+ if (n !== _0n$1)
617
+ throw new Error("invalid wNAF");
618
+ }
619
+ class wNAF {
620
+ // Parametrized with a given Point class (not individual point)
621
+ constructor(Point, bits) {
622
+ this.BASE = Point.BASE;
623
+ this.ZERO = Point.ZERO;
624
+ this.Fn = Point.Fn;
625
+ this.bits = bits;
626
+ }
627
+ // non-const time multiplication ladder
628
+ _unsafeLadder(elm, n, p = this.ZERO) {
629
+ let d = elm;
630
+ while (n > _0n$1) {
631
+ if (n & _1n$1)
632
+ p = p.add(d);
633
+ d = d.double();
634
+ n >>= _1n$1;
635
+ }
636
+ return p;
637
+ }
638
+ /**
639
+ * Creates a wNAF precomputation window. Used for caching.
640
+ * Default window size is set by `utils.precompute()` and is equal to 8.
641
+ * Number of precomputed points depends on the curve size:
642
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
643
+ * - 𝑊 is the window size
644
+ * - 𝑛 is the bitlength of the curve order.
645
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
646
+ * @param point Point instance
647
+ * @param W window size
648
+ * @returns precomputed point tables flattened to a single array
649
+ */
650
+ precomputeWindow(point, W) {
651
+ const { windows, windowSize } = calcWOpts(W, this.bits);
652
+ const points = [];
653
+ let p = point;
654
+ let base = p;
655
+ for (let window = 0; window < windows; window++) {
656
+ base = p;
657
+ points.push(base);
658
+ for (let i = 1; i < windowSize; i++) {
659
+ base = base.add(p);
660
+ points.push(base);
661
+ }
662
+ p = base.double();
663
+ }
664
+ return points;
665
+ }
666
+ /**
667
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
668
+ * More compact implementation:
669
+ * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
670
+ * @returns real and fake (for const-time) points
671
+ */
672
+ wNAF(W, precomputes, n) {
673
+ if (!this.Fn.isValid(n))
674
+ throw new Error("invalid scalar");
675
+ let p = this.ZERO;
676
+ let f = this.BASE;
677
+ const wo = calcWOpts(W, this.bits);
678
+ for (let window = 0; window < wo.windows; window++) {
679
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
680
+ n = nextN;
681
+ if (isZero) {
682
+ f = f.add(negateCt(isNegF, precomputes[offsetF]));
683
+ } else {
684
+ p = p.add(negateCt(isNeg, precomputes[offset]));
685
+ }
686
+ }
687
+ assert0(n);
688
+ return { p, f };
689
+ }
690
+ /**
691
+ * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
692
+ * @param acc accumulator point to add result of multiplication
693
+ * @returns point
694
+ */
695
+ wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
696
+ const wo = calcWOpts(W, this.bits);
697
+ for (let window = 0; window < wo.windows; window++) {
698
+ if (n === _0n$1)
699
+ break;
700
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
701
+ n = nextN;
702
+ if (isZero) {
703
+ continue;
704
+ } else {
705
+ const item = precomputes[offset];
706
+ acc = acc.add(isNeg ? item.negate() : item);
707
+ }
708
+ }
709
+ assert0(n);
710
+ return acc;
711
+ }
712
+ getPrecomputes(W, point, transform) {
713
+ let comp = pointPrecomputes.get(point);
714
+ if (!comp) {
715
+ comp = this.precomputeWindow(point, W);
716
+ if (W !== 1) {
717
+ if (typeof transform === "function")
718
+ comp = transform(comp);
719
+ pointPrecomputes.set(point, comp);
720
+ }
721
+ }
722
+ return comp;
723
+ }
724
+ cached(point, scalar, transform) {
725
+ const W = getW(point);
726
+ return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
727
+ }
728
+ unsafe(point, scalar, transform, prev) {
729
+ const W = getW(point);
730
+ if (W === 1)
731
+ return this._unsafeLadder(point, scalar, prev);
732
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
733
+ }
734
+ // We calculate precomputes for elliptic curve point multiplication
735
+ // using windowed method. This specifies window size and
736
+ // stores precomputed values. Usually only base point would be precomputed.
737
+ createCache(P, W) {
738
+ validateW(W, this.bits);
739
+ pointWindowSizes.set(P, W);
740
+ pointPrecomputes.delete(P);
741
+ }
742
+ hasCache(elm) {
743
+ return getW(elm) !== 1;
744
+ }
745
+ }
746
+ function mulEndoUnsafe(Point, point, k1, k2) {
747
+ let acc = point;
748
+ let p1 = Point.ZERO;
749
+ let p2 = Point.ZERO;
750
+ while (k1 > _0n$1 || k2 > _0n$1) {
751
+ if (k1 & _1n$1)
752
+ p1 = p1.add(acc);
753
+ if (k2 & _1n$1)
754
+ p2 = p2.add(acc);
755
+ acc = acc.double();
756
+ k1 >>= _1n$1;
757
+ k2 >>= _1n$1;
758
+ }
759
+ return { p1, p2 };
760
+ }
761
+ function pippenger(c, fieldN, points, scalars) {
762
+ validateMSMPoints(points, c);
763
+ validateMSMScalars(scalars, fieldN);
764
+ const plength = points.length;
765
+ const slength = scalars.length;
766
+ if (plength !== slength)
767
+ throw new Error("arrays of points and scalars must have equal length");
768
+ const zero = c.ZERO;
769
+ const wbits = bitLen(BigInt(plength));
770
+ let windowSize = 1;
771
+ if (wbits > 12)
772
+ windowSize = wbits - 3;
773
+ else if (wbits > 4)
774
+ windowSize = wbits - 2;
775
+ else if (wbits > 0)
776
+ windowSize = 2;
777
+ const MASK = bitMask(windowSize);
778
+ const buckets = new Array(Number(MASK) + 1).fill(zero);
779
+ const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
780
+ let sum = zero;
781
+ for (let i = lastBits; i >= 0; i -= windowSize) {
782
+ buckets.fill(zero);
783
+ for (let j = 0; j < slength; j++) {
784
+ const scalar = scalars[j];
785
+ const wbits2 = Number(scalar >> BigInt(i) & MASK);
786
+ buckets[wbits2] = buckets[wbits2].add(points[j]);
787
+ }
788
+ let resI = zero;
789
+ for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
790
+ sumI = sumI.add(buckets[j]);
791
+ resI = resI.add(sumI);
792
+ }
793
+ sum = sum.add(resI);
794
+ if (i !== 0)
795
+ for (let j = 0; j < windowSize; j++)
796
+ sum = sum.double();
797
+ }
798
+ return sum;
799
+ }
800
+ function createField(order, field, isLE) {
801
+ if (field) {
802
+ if (field.ORDER !== order)
803
+ throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
804
+ validateField(field);
805
+ return field;
806
+ } else {
807
+ return Field(order, { isLE });
808
+ }
809
+ }
810
+ function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
811
+ if (FpFnLE === void 0)
812
+ FpFnLE = type === "edwards";
813
+ if (!CURVE || typeof CURVE !== "object")
814
+ throw new Error(`expected valid ${type} CURVE object`);
815
+ for (const p of ["p", "n", "h"]) {
816
+ const val = CURVE[p];
817
+ if (!(typeof val === "bigint" && val > _0n$1))
818
+ throw new Error(`CURVE.${p} must be positive bigint`);
819
+ }
820
+ const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
821
+ const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
822
+ const _b = "b";
823
+ const params = ["Gx", "Gy", "a", _b];
824
+ for (const p of params) {
825
+ if (!Fp.isValid(CURVE[p]))
826
+ throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
827
+ }
828
+ CURVE = Object.freeze(Object.assign({}, CURVE));
829
+ return { CURVE, Fp, Fn };
830
+ }
831
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
832
+ const divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n$1) / den;
833
+ function _splitEndoScalar(k, basis, n) {
834
+ const [[a1, b1], [a2, b2]] = basis;
835
+ const c1 = divNearest(b2 * k, n);
836
+ const c2 = divNearest(-b1 * k, n);
837
+ let k1 = k - c1 * a1 - c2 * a2;
838
+ let k2 = -c1 * b1 - c2 * b2;
839
+ const k1neg = k1 < _0n;
840
+ const k2neg = k2 < _0n;
841
+ if (k1neg)
842
+ k1 = -k1;
843
+ if (k2neg)
844
+ k2 = -k2;
845
+ const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n;
846
+ if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {
847
+ throw new Error("splitScalar (endomorphism): failed, k=" + k);
848
+ }
849
+ return { k1neg, k1, k2neg, k2 };
850
+ }
851
+ function validateSigFormat(format) {
852
+ if (!["compact", "recovered", "der"].includes(format))
853
+ throw new Error('Signature format must be "compact", "recovered", or "der"');
854
+ return format;
855
+ }
856
+ function validateSigOpts(opts, def) {
857
+ const optsn = {};
858
+ for (let optName of Object.keys(def)) {
859
+ optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
860
+ }
861
+ _abool2(optsn.lowS, "lowS");
862
+ _abool2(optsn.prehash, "prehash");
863
+ if (optsn.format !== void 0)
864
+ validateSigFormat(optsn.format);
865
+ return optsn;
866
+ }
867
+ class DERErr extends Error {
868
+ constructor(m = "") {
869
+ super(m);
870
+ }
871
+ }
872
+ const DER = {
873
+ // asn.1 DER encoding utils
874
+ Err: DERErr,
875
+ // Basic building block is TLV (Tag-Length-Value)
876
+ _tlv: {
877
+ encode: (tag, data) => {
878
+ const { Err: E } = DER;
879
+ if (tag < 0 || tag > 256)
880
+ throw new E("tlv.encode: wrong tag");
881
+ if (data.length & 1)
882
+ throw new E("tlv.encode: unpadded data");
883
+ const dataLen = data.length / 2;
884
+ const len = numberToHexUnpadded(dataLen);
885
+ if (len.length / 2 & 128)
886
+ throw new E("tlv.encode: long form length too big");
887
+ const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
888
+ const t = numberToHexUnpadded(tag);
889
+ return t + lenLen + len + data;
890
+ },
891
+ // v - value, l - left bytes (unparsed)
892
+ decode(tag, data) {
893
+ const { Err: E } = DER;
894
+ let pos = 0;
895
+ if (tag < 0 || tag > 256)
896
+ throw new E("tlv.encode: wrong tag");
897
+ if (data.length < 2 || data[pos++] !== tag)
898
+ throw new E("tlv.decode: wrong tlv");
899
+ const first = data[pos++];
900
+ const isLong = !!(first & 128);
901
+ let length = 0;
902
+ if (!isLong)
903
+ length = first;
904
+ else {
905
+ const lenLen = first & 127;
906
+ if (!lenLen)
907
+ throw new E("tlv.decode(long): indefinite length not supported");
908
+ if (lenLen > 4)
909
+ throw new E("tlv.decode(long): byte length is too big");
910
+ const lengthBytes = data.subarray(pos, pos + lenLen);
911
+ if (lengthBytes.length !== lenLen)
912
+ throw new E("tlv.decode: length bytes not complete");
913
+ if (lengthBytes[0] === 0)
914
+ throw new E("tlv.decode(long): zero leftmost byte");
915
+ for (const b of lengthBytes)
916
+ length = length << 8 | b;
917
+ pos += lenLen;
918
+ if (length < 128)
919
+ throw new E("tlv.decode(long): not minimal encoding");
920
+ }
921
+ const v = data.subarray(pos, pos + length);
922
+ if (v.length !== length)
923
+ throw new E("tlv.decode: wrong value length");
924
+ return { v, l: data.subarray(pos + length) };
925
+ }
926
+ },
927
+ // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
928
+ // since we always use positive integers here. It must always be empty:
929
+ // - add zero byte if exists
930
+ // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
931
+ _int: {
932
+ encode(num) {
933
+ const { Err: E } = DER;
934
+ if (num < _0n)
935
+ throw new E("integer: negative integers are not allowed");
936
+ let hex = numberToHexUnpadded(num);
937
+ if (Number.parseInt(hex[0], 16) & 8)
938
+ hex = "00" + hex;
939
+ if (hex.length & 1)
940
+ throw new E("unexpected DER parsing assertion: unpadded hex");
941
+ return hex;
942
+ },
943
+ decode(data) {
944
+ const { Err: E } = DER;
945
+ if (data[0] & 128)
946
+ throw new E("invalid signature integer: negative");
947
+ if (data[0] === 0 && !(data[1] & 128))
948
+ throw new E("invalid signature integer: unnecessary leading zero");
949
+ return bytesToNumberBE(data);
950
+ }
951
+ },
952
+ toSig(hex) {
953
+ const { Err: E, _int: int, _tlv: tlv } = DER;
954
+ const data = ensureBytes("signature", hex);
955
+ const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
956
+ if (seqLeftBytes.length)
957
+ throw new E("invalid signature: left bytes after parsing");
958
+ const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
959
+ const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
960
+ if (sLeftBytes.length)
961
+ throw new E("invalid signature: left bytes after parsing");
962
+ return { r: int.decode(rBytes), s: int.decode(sBytes) };
963
+ },
964
+ hexFromSig(sig) {
965
+ const { _tlv: tlv, _int: int } = DER;
966
+ const rs = tlv.encode(2, int.encode(sig.r));
967
+ const ss = tlv.encode(2, int.encode(sig.s));
968
+ const seq = rs + ss;
969
+ return tlv.encode(48, seq);
970
+ }
971
+ };
972
+ const _0n = BigInt(0), _1n = BigInt(1), _2n$1 = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);
973
+ function _normFnElement(Fn, key) {
974
+ const { BYTES: expected } = Fn;
975
+ let num;
976
+ if (typeof key === "bigint") {
977
+ num = key;
978
+ } else {
979
+ let bytes = ensureBytes("private key", key);
980
+ try {
981
+ num = Fn.fromBytes(bytes);
982
+ } catch (error) {
983
+ throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);
984
+ }
985
+ }
986
+ if (!Fn.isValidNot0(num))
987
+ throw new Error("invalid private key: out of range [1..N-1]");
988
+ return num;
989
+ }
990
+ function weierstrassN(params, extraOpts = {}) {
991
+ const validated = _createCurveFields("weierstrass", params, extraOpts);
992
+ const { Fp, Fn } = validated;
993
+ let CURVE = validated.CURVE;
994
+ const { h: cofactor, n: CURVE_ORDER } = CURVE;
995
+ _validateObject(extraOpts, {}, {
996
+ allowInfinityPoint: "boolean",
997
+ clearCofactor: "function",
998
+ isTorsionFree: "function",
999
+ fromBytes: "function",
1000
+ toBytes: "function",
1001
+ endo: "object",
1002
+ wrapPrivateKey: "boolean"
1003
+ });
1004
+ const { endo } = extraOpts;
1005
+ if (endo) {
1006
+ if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
1007
+ throw new Error('invalid endo: expected "beta": bigint and "basises": array');
1008
+ }
1009
+ }
1010
+ const lengths = getWLengths(Fp, Fn);
1011
+ function assertCompressionIsSupported() {
1012
+ if (!Fp.isOdd)
1013
+ throw new Error("compression is not supported: Field does not have .isOdd()");
1014
+ }
1015
+ function pointToBytes(_c, point, isCompressed) {
1016
+ const { x, y } = point.toAffine();
1017
+ const bx = Fp.toBytes(x);
1018
+ _abool2(isCompressed, "isCompressed");
1019
+ if (isCompressed) {
1020
+ assertCompressionIsSupported();
1021
+ const hasEvenY = !Fp.isOdd(y);
1022
+ return concatBytes(pprefix(hasEvenY), bx);
1023
+ } else {
1024
+ return concatBytes(Uint8Array.of(4), bx, Fp.toBytes(y));
1025
+ }
1026
+ }
1027
+ function pointFromBytes(bytes) {
1028
+ _abytes2(bytes, void 0, "Point");
1029
+ const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
1030
+ const length = bytes.length;
1031
+ const head = bytes[0];
1032
+ const tail = bytes.subarray(1);
1033
+ if (length === comp && (head === 2 || head === 3)) {
1034
+ const x = Fp.fromBytes(tail);
1035
+ if (!Fp.isValid(x))
1036
+ throw new Error("bad point: is not on curve, wrong x");
1037
+ const y2 = weierstrassEquation(x);
1038
+ let y;
1039
+ try {
1040
+ y = Fp.sqrt(y2);
1041
+ } catch (sqrtError) {
1042
+ const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
1043
+ throw new Error("bad point: is not on curve, sqrt error" + err);
1044
+ }
1045
+ assertCompressionIsSupported();
1046
+ const isYOdd = Fp.isOdd(y);
1047
+ const isHeadOdd = (head & 1) === 1;
1048
+ if (isHeadOdd !== isYOdd)
1049
+ y = Fp.neg(y);
1050
+ return { x, y };
1051
+ } else if (length === uncomp && head === 4) {
1052
+ const L = Fp.BYTES;
1053
+ const x = Fp.fromBytes(tail.subarray(0, L));
1054
+ const y = Fp.fromBytes(tail.subarray(L, L * 2));
1055
+ if (!isValidXY(x, y))
1056
+ throw new Error("bad point: is not on curve");
1057
+ return { x, y };
1058
+ } else {
1059
+ throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
1060
+ }
1061
+ }
1062
+ const encodePoint = extraOpts.toBytes || pointToBytes;
1063
+ const decodePoint = extraOpts.fromBytes || pointFromBytes;
1064
+ function weierstrassEquation(x) {
1065
+ const x2 = Fp.sqr(x);
1066
+ const x3 = Fp.mul(x2, x);
1067
+ return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
1068
+ }
1069
+ function isValidXY(x, y) {
1070
+ const left = Fp.sqr(y);
1071
+ const right = weierstrassEquation(x);
1072
+ return Fp.eql(left, right);
1073
+ }
1074
+ if (!isValidXY(CURVE.Gx, CURVE.Gy))
1075
+ throw new Error("bad curve params: generator point");
1076
+ const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);
1077
+ const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
1078
+ if (Fp.is0(Fp.add(_4a3, _27b2)))
1079
+ throw new Error("bad curve params: a or b");
1080
+ function acoord(title, n, banZero = false) {
1081
+ if (!Fp.isValid(n) || banZero && Fp.is0(n))
1082
+ throw new Error(`bad point coordinate ${title}`);
1083
+ return n;
1084
+ }
1085
+ function aprjpoint(other) {
1086
+ if (!(other instanceof Point))
1087
+ throw new Error("ProjectivePoint expected");
1088
+ }
1089
+ function splitEndoScalarN(k) {
1090
+ if (!endo || !endo.basises)
1091
+ throw new Error("no endo");
1092
+ return _splitEndoScalar(k, endo.basises, Fn.ORDER);
1093
+ }
1094
+ const toAffineMemo = memoized((p, iz) => {
1095
+ const { X, Y, Z } = p;
1096
+ if (Fp.eql(Z, Fp.ONE))
1097
+ return { x: X, y: Y };
1098
+ const is0 = p.is0();
1099
+ if (iz == null)
1100
+ iz = is0 ? Fp.ONE : Fp.inv(Z);
1101
+ const x = Fp.mul(X, iz);
1102
+ const y = Fp.mul(Y, iz);
1103
+ const zz = Fp.mul(Z, iz);
1104
+ if (is0)
1105
+ return { x: Fp.ZERO, y: Fp.ZERO };
1106
+ if (!Fp.eql(zz, Fp.ONE))
1107
+ throw new Error("invZ was invalid");
1108
+ return { x, y };
1109
+ });
1110
+ const assertValidMemo = memoized((p) => {
1111
+ if (p.is0()) {
1112
+ if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
1113
+ return;
1114
+ throw new Error("bad point: ZERO");
1115
+ }
1116
+ const { x, y } = p.toAffine();
1117
+ if (!Fp.isValid(x) || !Fp.isValid(y))
1118
+ throw new Error("bad point: x or y not field elements");
1119
+ if (!isValidXY(x, y))
1120
+ throw new Error("bad point: equation left != right");
1121
+ if (!p.isTorsionFree())
1122
+ throw new Error("bad point: not in prime-order subgroup");
1123
+ return true;
1124
+ });
1125
+ function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
1126
+ k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
1127
+ k1p = negateCt(k1neg, k1p);
1128
+ k2p = negateCt(k2neg, k2p);
1129
+ return k1p.add(k2p);
1130
+ }
1131
+ class Point {
1132
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
1133
+ constructor(X, Y, Z) {
1134
+ this.X = acoord("x", X);
1135
+ this.Y = acoord("y", Y, true);
1136
+ this.Z = acoord("z", Z);
1137
+ Object.freeze(this);
1138
+ }
1139
+ static CURVE() {
1140
+ return CURVE;
1141
+ }
1142
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
1143
+ static fromAffine(p) {
1144
+ const { x, y } = p || {};
1145
+ if (!p || !Fp.isValid(x) || !Fp.isValid(y))
1146
+ throw new Error("invalid affine point");
1147
+ if (p instanceof Point)
1148
+ throw new Error("projective point not allowed");
1149
+ if (Fp.is0(x) && Fp.is0(y))
1150
+ return Point.ZERO;
1151
+ return new Point(x, y, Fp.ONE);
1152
+ }
1153
+ static fromBytes(bytes) {
1154
+ const P = Point.fromAffine(decodePoint(_abytes2(bytes, void 0, "point")));
1155
+ P.assertValidity();
1156
+ return P;
1157
+ }
1158
+ static fromHex(hex) {
1159
+ return Point.fromBytes(ensureBytes("pointHex", hex));
1160
+ }
1161
+ get x() {
1162
+ return this.toAffine().x;
1163
+ }
1164
+ get y() {
1165
+ return this.toAffine().y;
1166
+ }
1167
+ /**
1168
+ *
1169
+ * @param windowSize
1170
+ * @param isLazy true will defer table computation until the first multiplication
1171
+ * @returns
1172
+ */
1173
+ precompute(windowSize = 8, isLazy = true) {
1174
+ wnaf.createCache(this, windowSize);
1175
+ if (!isLazy)
1176
+ this.multiply(_3n);
1177
+ return this;
1178
+ }
1179
+ // TODO: return `this`
1180
+ /** A point on curve is valid if it conforms to equation. */
1181
+ assertValidity() {
1182
+ assertValidMemo(this);
1183
+ }
1184
+ hasEvenY() {
1185
+ const { y } = this.toAffine();
1186
+ if (!Fp.isOdd)
1187
+ throw new Error("Field doesn't support isOdd");
1188
+ return !Fp.isOdd(y);
1189
+ }
1190
+ /** Compare one point to another. */
1191
+ equals(other) {
1192
+ aprjpoint(other);
1193
+ const { X: X1, Y: Y1, Z: Z1 } = this;
1194
+ const { X: X2, Y: Y2, Z: Z2 } = other;
1195
+ const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
1196
+ const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
1197
+ return U1 && U2;
1198
+ }
1199
+ /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
1200
+ negate() {
1201
+ return new Point(this.X, Fp.neg(this.Y), this.Z);
1202
+ }
1203
+ // Renes-Costello-Batina exception-free doubling formula.
1204
+ // There is 30% faster Jacobian formula, but it is not complete.
1205
+ // https://eprint.iacr.org/2015/1060, algorithm 3
1206
+ // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
1207
+ double() {
1208
+ const { a, b } = CURVE;
1209
+ const b3 = Fp.mul(b, _3n);
1210
+ const { X: X1, Y: Y1, Z: Z1 } = this;
1211
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
1212
+ let t0 = Fp.mul(X1, X1);
1213
+ let t1 = Fp.mul(Y1, Y1);
1214
+ let t2 = Fp.mul(Z1, Z1);
1215
+ let t3 = Fp.mul(X1, Y1);
1216
+ t3 = Fp.add(t3, t3);
1217
+ Z3 = Fp.mul(X1, Z1);
1218
+ Z3 = Fp.add(Z3, Z3);
1219
+ X3 = Fp.mul(a, Z3);
1220
+ Y3 = Fp.mul(b3, t2);
1221
+ Y3 = Fp.add(X3, Y3);
1222
+ X3 = Fp.sub(t1, Y3);
1223
+ Y3 = Fp.add(t1, Y3);
1224
+ Y3 = Fp.mul(X3, Y3);
1225
+ X3 = Fp.mul(t3, X3);
1226
+ Z3 = Fp.mul(b3, Z3);
1227
+ t2 = Fp.mul(a, t2);
1228
+ t3 = Fp.sub(t0, t2);
1229
+ t3 = Fp.mul(a, t3);
1230
+ t3 = Fp.add(t3, Z3);
1231
+ Z3 = Fp.add(t0, t0);
1232
+ t0 = Fp.add(Z3, t0);
1233
+ t0 = Fp.add(t0, t2);
1234
+ t0 = Fp.mul(t0, t3);
1235
+ Y3 = Fp.add(Y3, t0);
1236
+ t2 = Fp.mul(Y1, Z1);
1237
+ t2 = Fp.add(t2, t2);
1238
+ t0 = Fp.mul(t2, t3);
1239
+ X3 = Fp.sub(X3, t0);
1240
+ Z3 = Fp.mul(t2, t1);
1241
+ Z3 = Fp.add(Z3, Z3);
1242
+ Z3 = Fp.add(Z3, Z3);
1243
+ return new Point(X3, Y3, Z3);
1244
+ }
1245
+ // Renes-Costello-Batina exception-free addition formula.
1246
+ // There is 30% faster Jacobian formula, but it is not complete.
1247
+ // https://eprint.iacr.org/2015/1060, algorithm 1
1248
+ // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
1249
+ add(other) {
1250
+ aprjpoint(other);
1251
+ const { X: X1, Y: Y1, Z: Z1 } = this;
1252
+ const { X: X2, Y: Y2, Z: Z2 } = other;
1253
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
1254
+ const a = CURVE.a;
1255
+ const b3 = Fp.mul(CURVE.b, _3n);
1256
+ let t0 = Fp.mul(X1, X2);
1257
+ let t1 = Fp.mul(Y1, Y2);
1258
+ let t2 = Fp.mul(Z1, Z2);
1259
+ let t3 = Fp.add(X1, Y1);
1260
+ let t4 = Fp.add(X2, Y2);
1261
+ t3 = Fp.mul(t3, t4);
1262
+ t4 = Fp.add(t0, t1);
1263
+ t3 = Fp.sub(t3, t4);
1264
+ t4 = Fp.add(X1, Z1);
1265
+ let t5 = Fp.add(X2, Z2);
1266
+ t4 = Fp.mul(t4, t5);
1267
+ t5 = Fp.add(t0, t2);
1268
+ t4 = Fp.sub(t4, t5);
1269
+ t5 = Fp.add(Y1, Z1);
1270
+ X3 = Fp.add(Y2, Z2);
1271
+ t5 = Fp.mul(t5, X3);
1272
+ X3 = Fp.add(t1, t2);
1273
+ t5 = Fp.sub(t5, X3);
1274
+ Z3 = Fp.mul(a, t4);
1275
+ X3 = Fp.mul(b3, t2);
1276
+ Z3 = Fp.add(X3, Z3);
1277
+ X3 = Fp.sub(t1, Z3);
1278
+ Z3 = Fp.add(t1, Z3);
1279
+ Y3 = Fp.mul(X3, Z3);
1280
+ t1 = Fp.add(t0, t0);
1281
+ t1 = Fp.add(t1, t0);
1282
+ t2 = Fp.mul(a, t2);
1283
+ t4 = Fp.mul(b3, t4);
1284
+ t1 = Fp.add(t1, t2);
1285
+ t2 = Fp.sub(t0, t2);
1286
+ t2 = Fp.mul(a, t2);
1287
+ t4 = Fp.add(t4, t2);
1288
+ t0 = Fp.mul(t1, t4);
1289
+ Y3 = Fp.add(Y3, t0);
1290
+ t0 = Fp.mul(t5, t4);
1291
+ X3 = Fp.mul(t3, X3);
1292
+ X3 = Fp.sub(X3, t0);
1293
+ t0 = Fp.mul(t3, t1);
1294
+ Z3 = Fp.mul(t5, Z3);
1295
+ Z3 = Fp.add(Z3, t0);
1296
+ return new Point(X3, Y3, Z3);
1297
+ }
1298
+ subtract(other) {
1299
+ return this.add(other.negate());
1300
+ }
1301
+ is0() {
1302
+ return this.equals(Point.ZERO);
1303
+ }
1304
+ /**
1305
+ * Constant time multiplication.
1306
+ * Uses wNAF method. Windowed method may be 10% faster,
1307
+ * but takes 2x longer to generate and consumes 2x memory.
1308
+ * Uses precomputes when available.
1309
+ * Uses endomorphism for Koblitz curves.
1310
+ * @param scalar by which the point would be multiplied
1311
+ * @returns New point
1312
+ */
1313
+ multiply(scalar) {
1314
+ const { endo: endo2 } = extraOpts;
1315
+ if (!Fn.isValidNot0(scalar))
1316
+ throw new Error("invalid scalar: out of range");
1317
+ let point, fake;
1318
+ const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
1319
+ if (endo2) {
1320
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
1321
+ const { p: k1p, f: k1f } = mul(k1);
1322
+ const { p: k2p, f: k2f } = mul(k2);
1323
+ fake = k1f.add(k2f);
1324
+ point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
1325
+ } else {
1326
+ const { p, f } = mul(scalar);
1327
+ point = p;
1328
+ fake = f;
1329
+ }
1330
+ return normalizeZ(Point, [point, fake])[0];
1331
+ }
1332
+ /**
1333
+ * Non-constant-time multiplication. Uses double-and-add algorithm.
1334
+ * It's faster, but should only be used when you don't care about
1335
+ * an exposed secret key e.g. sig verification, which works over *public* keys.
1336
+ */
1337
+ multiplyUnsafe(sc) {
1338
+ const { endo: endo2 } = extraOpts;
1339
+ const p = this;
1340
+ if (!Fn.isValid(sc))
1341
+ throw new Error("invalid scalar: out of range");
1342
+ if (sc === _0n || p.is0())
1343
+ return Point.ZERO;
1344
+ if (sc === _1n)
1345
+ return p;
1346
+ if (wnaf.hasCache(this))
1347
+ return this.multiply(sc);
1348
+ if (endo2) {
1349
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
1350
+ const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
1351
+ return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
1352
+ } else {
1353
+ return wnaf.unsafe(p, sc);
1354
+ }
1355
+ }
1356
+ multiplyAndAddUnsafe(Q, a, b) {
1357
+ const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));
1358
+ return sum.is0() ? void 0 : sum;
1359
+ }
1360
+ /**
1361
+ * Converts Projective point to affine (x, y) coordinates.
1362
+ * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
1363
+ */
1364
+ toAffine(invertedZ) {
1365
+ return toAffineMemo(this, invertedZ);
1366
+ }
1367
+ /**
1368
+ * Checks whether Point is free of torsion elements (is in prime subgroup).
1369
+ * Always torsion-free for cofactor=1 curves.
1370
+ */
1371
+ isTorsionFree() {
1372
+ const { isTorsionFree } = extraOpts;
1373
+ if (cofactor === _1n)
1374
+ return true;
1375
+ if (isTorsionFree)
1376
+ return isTorsionFree(Point, this);
1377
+ return wnaf.unsafe(this, CURVE_ORDER).is0();
1378
+ }
1379
+ clearCofactor() {
1380
+ const { clearCofactor } = extraOpts;
1381
+ if (cofactor === _1n)
1382
+ return this;
1383
+ if (clearCofactor)
1384
+ return clearCofactor(Point, this);
1385
+ return this.multiplyUnsafe(cofactor);
1386
+ }
1387
+ isSmallOrder() {
1388
+ return this.multiplyUnsafe(cofactor).is0();
1389
+ }
1390
+ toBytes(isCompressed = true) {
1391
+ _abool2(isCompressed, "isCompressed");
1392
+ this.assertValidity();
1393
+ return encodePoint(Point, this, isCompressed);
1394
+ }
1395
+ toHex(isCompressed = true) {
1396
+ return bytesToHex(this.toBytes(isCompressed));
1397
+ }
1398
+ toString() {
1399
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
1400
+ }
1401
+ // TODO: remove
1402
+ get px() {
1403
+ return this.X;
1404
+ }
1405
+ get py() {
1406
+ return this.X;
1407
+ }
1408
+ get pz() {
1409
+ return this.Z;
1410
+ }
1411
+ toRawBytes(isCompressed = true) {
1412
+ return this.toBytes(isCompressed);
1413
+ }
1414
+ _setWindowSize(windowSize) {
1415
+ this.precompute(windowSize);
1416
+ }
1417
+ static normalizeZ(points) {
1418
+ return normalizeZ(Point, points);
1419
+ }
1420
+ static msm(points, scalars) {
1421
+ return pippenger(Point, Fn, points, scalars);
1422
+ }
1423
+ static fromPrivateKey(privateKey) {
1424
+ return Point.BASE.multiply(_normFnElement(Fn, privateKey));
1425
+ }
1426
+ }
1427
+ Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
1428
+ Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
1429
+ Point.Fp = Fp;
1430
+ Point.Fn = Fn;
1431
+ const bits = Fn.BITS;
1432
+ const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
1433
+ Point.BASE.precompute(8);
1434
+ return Point;
1435
+ }
1436
+ function pprefix(hasEvenY) {
1437
+ return Uint8Array.of(hasEvenY ? 2 : 3);
1438
+ }
1439
+ function getWLengths(Fp, Fn) {
1440
+ return {
1441
+ secretKey: Fn.BYTES,
1442
+ publicKey: 1 + Fp.BYTES,
1443
+ publicKeyUncompressed: 1 + 2 * Fp.BYTES,
1444
+ publicKeyHasPrefix: true,
1445
+ signature: 2 * Fn.BYTES
1446
+ };
1447
+ }
1448
+ function ecdh(Point, ecdhOpts = {}) {
1449
+ const { Fn } = Point;
1450
+ const randomBytes_ = ecdhOpts.randomBytes || randomBytes;
1451
+ const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
1452
+ function isValidSecretKey(secretKey) {
1453
+ try {
1454
+ return !!_normFnElement(Fn, secretKey);
1455
+ } catch (error) {
1456
+ return false;
1457
+ }
1458
+ }
1459
+ function isValidPublicKey(publicKey, isCompressed) {
1460
+ const { publicKey: comp, publicKeyUncompressed } = lengths;
1461
+ try {
1462
+ const l = publicKey.length;
1463
+ if (isCompressed === true && l !== comp)
1464
+ return false;
1465
+ if (isCompressed === false && l !== publicKeyUncompressed)
1466
+ return false;
1467
+ return !!Point.fromBytes(publicKey);
1468
+ } catch (error) {
1469
+ return false;
1470
+ }
1471
+ }
1472
+ function randomSecretKey(seed = randomBytes_(lengths.seed)) {
1473
+ return mapHashToField(_abytes2(seed, lengths.seed, "seed"), Fn.ORDER);
1474
+ }
1475
+ function getPublicKey(secretKey, isCompressed = true) {
1476
+ return Point.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed);
1477
+ }
1478
+ function keygen(seed) {
1479
+ const secretKey = randomSecretKey(seed);
1480
+ return { secretKey, publicKey: getPublicKey(secretKey) };
1481
+ }
1482
+ function isProbPub(item) {
1483
+ if (typeof item === "bigint")
1484
+ return false;
1485
+ if (item instanceof Point)
1486
+ return true;
1487
+ const { secretKey, publicKey, publicKeyUncompressed } = lengths;
1488
+ if (Fn.allowedLengths || secretKey === publicKey)
1489
+ return void 0;
1490
+ const l = ensureBytes("key", item).length;
1491
+ return l === publicKey || l === publicKeyUncompressed;
1492
+ }
1493
+ function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
1494
+ if (isProbPub(secretKeyA) === true)
1495
+ throw new Error("first arg must be private key");
1496
+ if (isProbPub(publicKeyB) === false)
1497
+ throw new Error("second arg must be public key");
1498
+ const s = _normFnElement(Fn, secretKeyA);
1499
+ const b = Point.fromHex(publicKeyB);
1500
+ return b.multiply(s).toBytes(isCompressed);
1501
+ }
1502
+ const utils = {
1503
+ isValidSecretKey,
1504
+ isValidPublicKey,
1505
+ randomSecretKey,
1506
+ // TODO: remove
1507
+ isValidPrivateKey: isValidSecretKey,
1508
+ randomPrivateKey: randomSecretKey,
1509
+ normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
1510
+ precompute(windowSize = 8, point = Point.BASE) {
1511
+ return point.precompute(windowSize, false);
1512
+ }
1513
+ };
1514
+ return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });
1515
+ }
1516
+ function ecdsa(Point, hash, ecdsaOpts = {}) {
1517
+ ahash(hash);
1518
+ _validateObject(ecdsaOpts, {}, {
1519
+ hmac: "function",
1520
+ lowS: "boolean",
1521
+ randomBytes: "function",
1522
+ bits2int: "function",
1523
+ bits2int_modN: "function"
1524
+ });
1525
+ const randomBytes$1 = ecdsaOpts.randomBytes || randomBytes;
1526
+ const hmac$1 = ecdsaOpts.hmac || ((key, ...msgs) => hmac(hash, key, concatBytes(...msgs)));
1527
+ const { Fp, Fn } = Point;
1528
+ const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
1529
+ const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
1530
+ const defaultSigOpts = {
1531
+ prehash: false,
1532
+ lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : false,
1533
+ format: void 0,
1534
+ //'compact' as ECDSASigFormat,
1535
+ extraEntropy: false
1536
+ };
1537
+ const defaultSigOpts_format = "compact";
1538
+ function isBiggerThanHalfOrder(number) {
1539
+ const HALF = CURVE_ORDER >> _1n;
1540
+ return number > HALF;
1541
+ }
1542
+ function validateRS(title, num) {
1543
+ if (!Fn.isValidNot0(num))
1544
+ throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
1545
+ return num;
1546
+ }
1547
+ function validateSigLength(bytes, format) {
1548
+ validateSigFormat(format);
1549
+ const size = lengths.signature;
1550
+ const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
1551
+ return _abytes2(bytes, sizer, `${format} signature`);
1552
+ }
1553
+ class Signature {
1554
+ constructor(r, s, recovery) {
1555
+ this.r = validateRS("r", r);
1556
+ this.s = validateRS("s", s);
1557
+ if (recovery != null)
1558
+ this.recovery = recovery;
1559
+ Object.freeze(this);
1560
+ }
1561
+ static fromBytes(bytes, format = defaultSigOpts_format) {
1562
+ validateSigLength(bytes, format);
1563
+ let recid;
1564
+ if (format === "der") {
1565
+ const { r: r2, s: s2 } = DER.toSig(_abytes2(bytes));
1566
+ return new Signature(r2, s2);
1567
+ }
1568
+ if (format === "recovered") {
1569
+ recid = bytes[0];
1570
+ format = "compact";
1571
+ bytes = bytes.subarray(1);
1572
+ }
1573
+ const L = Fn.BYTES;
1574
+ const r = bytes.subarray(0, L);
1575
+ const s = bytes.subarray(L, L * 2);
1576
+ return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
1577
+ }
1578
+ static fromHex(hex, format) {
1579
+ return this.fromBytes(hexToBytes(hex), format);
1580
+ }
1581
+ addRecoveryBit(recovery) {
1582
+ return new Signature(this.r, this.s, recovery);
1583
+ }
1584
+ recoverPublicKey(messageHash) {
1585
+ const FIELD_ORDER = Fp.ORDER;
1586
+ const { r, s, recovery: rec } = this;
1587
+ if (rec == null || ![0, 1, 2, 3].includes(rec))
1588
+ throw new Error("recovery id invalid");
1589
+ const hasCofactor = CURVE_ORDER * _2n$1 < FIELD_ORDER;
1590
+ if (hasCofactor && rec > 1)
1591
+ throw new Error("recovery id is ambiguous for h>1 curve");
1592
+ const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;
1593
+ if (!Fp.isValid(radj))
1594
+ throw new Error("recovery id 2 or 3 invalid");
1595
+ const x = Fp.toBytes(radj);
1596
+ const R = Point.fromBytes(concatBytes(pprefix((rec & 1) === 0), x));
1597
+ const ir = Fn.inv(radj);
1598
+ const h = bits2int_modN(ensureBytes("msgHash", messageHash));
1599
+ const u1 = Fn.create(-h * ir);
1600
+ const u2 = Fn.create(s * ir);
1601
+ const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
1602
+ if (Q.is0())
1603
+ throw new Error("point at infinify");
1604
+ Q.assertValidity();
1605
+ return Q;
1606
+ }
1607
+ // Signatures should be low-s, to prevent malleability.
1608
+ hasHighS() {
1609
+ return isBiggerThanHalfOrder(this.s);
1610
+ }
1611
+ toBytes(format = defaultSigOpts_format) {
1612
+ validateSigFormat(format);
1613
+ if (format === "der")
1614
+ return hexToBytes(DER.hexFromSig(this));
1615
+ const r = Fn.toBytes(this.r);
1616
+ const s = Fn.toBytes(this.s);
1617
+ if (format === "recovered") {
1618
+ if (this.recovery == null)
1619
+ throw new Error("recovery bit must be present");
1620
+ return concatBytes(Uint8Array.of(this.recovery), r, s);
1621
+ }
1622
+ return concatBytes(r, s);
1623
+ }
1624
+ toHex(format) {
1625
+ return bytesToHex(this.toBytes(format));
1626
+ }
1627
+ // TODO: remove
1628
+ assertValidity() {
1629
+ }
1630
+ static fromCompact(hex) {
1631
+ return Signature.fromBytes(ensureBytes("sig", hex), "compact");
1632
+ }
1633
+ static fromDER(hex) {
1634
+ return Signature.fromBytes(ensureBytes("sig", hex), "der");
1635
+ }
1636
+ normalizeS() {
1637
+ return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this;
1638
+ }
1639
+ toDERRawBytes() {
1640
+ return this.toBytes("der");
1641
+ }
1642
+ toDERHex() {
1643
+ return bytesToHex(this.toBytes("der"));
1644
+ }
1645
+ toCompactRawBytes() {
1646
+ return this.toBytes("compact");
1647
+ }
1648
+ toCompactHex() {
1649
+ return bytesToHex(this.toBytes("compact"));
1650
+ }
1651
+ }
1652
+ const bits2int = ecdsaOpts.bits2int || function bits2int_def(bytes) {
1653
+ if (bytes.length > 8192)
1654
+ throw new Error("input is too large");
1655
+ const num = bytesToNumberBE(bytes);
1656
+ const delta = bytes.length * 8 - fnBits;
1657
+ return delta > 0 ? num >> BigInt(delta) : num;
1658
+ };
1659
+ const bits2int_modN = ecdsaOpts.bits2int_modN || function bits2int_modN_def(bytes) {
1660
+ return Fn.create(bits2int(bytes));
1661
+ };
1662
+ const ORDER_MASK = bitMask(fnBits);
1663
+ function int2octets(num) {
1664
+ aInRange("num < 2^" + fnBits, num, _0n, ORDER_MASK);
1665
+ return Fn.toBytes(num);
1666
+ }
1667
+ function validateMsgAndHash(message, prehash) {
1668
+ _abytes2(message, void 0, "message");
1669
+ return prehash ? _abytes2(hash(message), void 0, "prehashed message") : message;
1670
+ }
1671
+ function prepSig(message, privateKey, opts) {
1672
+ if (["recovered", "canonical"].some((k) => k in opts))
1673
+ throw new Error("sign() legacy options not supported");
1674
+ const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
1675
+ message = validateMsgAndHash(message, prehash);
1676
+ const h1int = bits2int_modN(message);
1677
+ const d = _normFnElement(Fn, privateKey);
1678
+ const seedArgs = [int2octets(d), int2octets(h1int)];
1679
+ if (extraEntropy != null && extraEntropy !== false) {
1680
+ const e = extraEntropy === true ? randomBytes$1(lengths.secretKey) : extraEntropy;
1681
+ seedArgs.push(ensureBytes("extraEntropy", e));
1682
+ }
1683
+ const seed = concatBytes(...seedArgs);
1684
+ const m = h1int;
1685
+ function k2sig(kBytes) {
1686
+ const k = bits2int(kBytes);
1687
+ if (!Fn.isValidNot0(k))
1688
+ return;
1689
+ const ik = Fn.inv(k);
1690
+ const q = Point.BASE.multiply(k).toAffine();
1691
+ const r = Fn.create(q.x);
1692
+ if (r === _0n)
1693
+ return;
1694
+ const s = Fn.create(ik * Fn.create(m + r * d));
1695
+ if (s === _0n)
1696
+ return;
1697
+ let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n);
1698
+ let normS = s;
1699
+ if (lowS && isBiggerThanHalfOrder(s)) {
1700
+ normS = Fn.neg(s);
1701
+ recovery ^= 1;
1702
+ }
1703
+ return new Signature(r, normS, recovery);
1704
+ }
1705
+ return { seed, k2sig };
1706
+ }
1707
+ function sign(message, secretKey, opts = {}) {
1708
+ message = ensureBytes("message", message);
1709
+ const { seed, k2sig } = prepSig(message, secretKey, opts);
1710
+ const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac$1);
1711
+ const sig = drbg(seed, k2sig);
1712
+ return sig;
1713
+ }
1714
+ function tryParsingSig(sg) {
1715
+ let sig = void 0;
1716
+ const isHex = typeof sg === "string" || isBytes(sg);
1717
+ const isObj = !isHex && sg !== null && typeof sg === "object" && typeof sg.r === "bigint" && typeof sg.s === "bigint";
1718
+ if (!isHex && !isObj)
1719
+ throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");
1720
+ if (isObj) {
1721
+ sig = new Signature(sg.r, sg.s);
1722
+ } else if (isHex) {
1723
+ try {
1724
+ sig = Signature.fromBytes(ensureBytes("sig", sg), "der");
1725
+ } catch (derError) {
1726
+ if (!(derError instanceof DER.Err))
1727
+ throw derError;
1728
+ }
1729
+ if (!sig) {
1730
+ try {
1731
+ sig = Signature.fromBytes(ensureBytes("sig", sg), "compact");
1732
+ } catch (error) {
1733
+ return false;
1734
+ }
1735
+ }
1736
+ }
1737
+ if (!sig)
1738
+ return false;
1739
+ return sig;
1740
+ }
1741
+ function verify(signature, message, publicKey, opts = {}) {
1742
+ const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
1743
+ publicKey = ensureBytes("publicKey", publicKey);
1744
+ message = validateMsgAndHash(ensureBytes("message", message), prehash);
1745
+ if ("strict" in opts)
1746
+ throw new Error("options.strict was renamed to lowS");
1747
+ const sig = format === void 0 ? tryParsingSig(signature) : Signature.fromBytes(ensureBytes("sig", signature), format);
1748
+ if (sig === false)
1749
+ return false;
1750
+ try {
1751
+ const P = Point.fromBytes(publicKey);
1752
+ if (lowS && sig.hasHighS())
1753
+ return false;
1754
+ const { r, s } = sig;
1755
+ const h = bits2int_modN(message);
1756
+ const is = Fn.inv(s);
1757
+ const u1 = Fn.create(h * is);
1758
+ const u2 = Fn.create(r * is);
1759
+ const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
1760
+ if (R.is0())
1761
+ return false;
1762
+ const v = Fn.create(R.x);
1763
+ return v === r;
1764
+ } catch (e) {
1765
+ return false;
1766
+ }
1767
+ }
1768
+ function recoverPublicKey(signature, message, opts = {}) {
1769
+ const { prehash } = validateSigOpts(opts, defaultSigOpts);
1770
+ message = validateMsgAndHash(message, prehash);
1771
+ return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
1772
+ }
1773
+ return Object.freeze({
1774
+ keygen,
1775
+ getPublicKey,
1776
+ getSharedSecret,
1777
+ utils,
1778
+ lengths,
1779
+ Point,
1780
+ sign,
1781
+ verify,
1782
+ recoverPublicKey,
1783
+ Signature,
1784
+ hash
1785
+ });
1786
+ }
1787
+ function _weierstrass_legacy_opts_to_new(c) {
1788
+ const CURVE = {
1789
+ a: c.a,
1790
+ b: c.b,
1791
+ p: c.Fp.ORDER,
1792
+ n: c.n,
1793
+ h: c.h,
1794
+ Gx: c.Gx,
1795
+ Gy: c.Gy
1796
+ };
1797
+ const Fp = c.Fp;
1798
+ let allowedLengths = c.allowedPrivateKeyLengths ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2)))) : void 0;
1799
+ const Fn = Field(CURVE.n, {
1800
+ BITS: c.nBitLength,
1801
+ allowedLengths,
1802
+ modFromBytes: c.wrapPrivateKey
1803
+ });
1804
+ const curveOpts = {
1805
+ Fp,
1806
+ Fn,
1807
+ allowInfinityPoint: c.allowInfinityPoint,
1808
+ endo: c.endo,
1809
+ isTorsionFree: c.isTorsionFree,
1810
+ clearCofactor: c.clearCofactor,
1811
+ fromBytes: c.fromBytes,
1812
+ toBytes: c.toBytes
1813
+ };
1814
+ return { CURVE, curveOpts };
1815
+ }
1816
+ function _ecdsa_legacy_opts_to_new(c) {
1817
+ const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
1818
+ const ecdsaOpts = {
1819
+ hmac: c.hmac,
1820
+ randomBytes: c.randomBytes,
1821
+ lowS: c.lowS,
1822
+ bits2int: c.bits2int,
1823
+ bits2int_modN: c.bits2int_modN
1824
+ };
1825
+ return { CURVE, curveOpts, hash: c.hash, ecdsaOpts };
1826
+ }
1827
+ function _ecdsa_new_output_to_legacy(c, _ecdsa) {
1828
+ const Point = _ecdsa.Point;
1829
+ return Object.assign({}, _ecdsa, {
1830
+ ProjectivePoint: Point,
1831
+ CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS))
1832
+ });
1833
+ }
1834
+ function weierstrass(c) {
1835
+ const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);
1836
+ const Point = weierstrassN(CURVE, curveOpts);
1837
+ const signs = ecdsa(Point, hash, ecdsaOpts);
1838
+ return _ecdsa_new_output_to_legacy(c, signs);
1839
+ }
1840
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1841
+ function createCurve(curveDef, defHash) {
1842
+ const create = (hash) => weierstrass({ ...curveDef, hash });
1843
+ return { ...create(defHash), create };
1844
+ }
1845
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1846
+ const secp256k1_CURVE = {
1847
+ p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
1848
+ n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
1849
+ h: BigInt(1),
1850
+ a: BigInt(0),
1851
+ b: BigInt(7),
1852
+ Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
1853
+ Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
1854
+ };
1855
+ const secp256k1_ENDO = {
1856
+ beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
1857
+ basises: [
1858
+ [BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],
1859
+ [BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]
1860
+ ]
1861
+ };
1862
+ const _2n = /* @__PURE__ */ BigInt(2);
1863
+ function sqrtMod(y) {
1864
+ const P = secp256k1_CURVE.p;
1865
+ const _3n2 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
1866
+ const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
1867
+ const b2 = y * y * y % P;
1868
+ const b3 = b2 * b2 * y % P;
1869
+ const b6 = pow2(b3, _3n2, P) * b3 % P;
1870
+ const b9 = pow2(b6, _3n2, P) * b3 % P;
1871
+ const b11 = pow2(b9, _2n, P) * b2 % P;
1872
+ const b22 = pow2(b11, _11n, P) * b11 % P;
1873
+ const b44 = pow2(b22, _22n, P) * b22 % P;
1874
+ const b88 = pow2(b44, _44n, P) * b44 % P;
1875
+ const b176 = pow2(b88, _88n, P) * b88 % P;
1876
+ const b220 = pow2(b176, _44n, P) * b44 % P;
1877
+ const b223 = pow2(b220, _3n2, P) * b3 % P;
1878
+ const t1 = pow2(b223, _23n, P) * b22 % P;
1879
+ const t2 = pow2(t1, _6n, P) * b2 % P;
1880
+ const root = pow2(t2, _2n, P);
1881
+ if (!Fpk1.eql(Fpk1.sqr(root), y))
1882
+ throw new Error("Cannot find square root");
1883
+ return root;
1884
+ }
1885
+ const Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
1886
+ const secp256k1 = createCurve({ ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO }, sha256);
1887
+ export {
1888
+ secp256k1
1889
+ };
1890
+ //# sourceMappingURL=secp256k1-CreY7Pcl.js.map