@enbox/crypto 0.0.3 → 0.0.5

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 (116) hide show
  1. package/dist/browser.mjs +1 -1
  2. package/dist/browser.mjs.map +4 -4
  3. package/dist/esm/algorithms/aes-ctr.js +1 -1
  4. package/dist/esm/algorithms/aes-gcm.js +34 -1
  5. package/dist/esm/algorithms/aes-gcm.js.map +1 -1
  6. package/dist/esm/algorithms/aes-kw.js +154 -0
  7. package/dist/esm/algorithms/aes-kw.js.map +1 -0
  8. package/dist/esm/algorithms/ecdsa.js +110 -1
  9. package/dist/esm/algorithms/ecdsa.js.map +1 -1
  10. package/dist/esm/algorithms/eddsa.js +90 -1
  11. package/dist/esm/algorithms/eddsa.js.map +1 -1
  12. package/dist/esm/algorithms/hkdf.js +53 -0
  13. package/dist/esm/algorithms/hkdf.js.map +1 -0
  14. package/dist/esm/algorithms/pbkdf2.js +55 -0
  15. package/dist/esm/algorithms/pbkdf2.js.map +1 -0
  16. package/dist/esm/algorithms/sha-2.js +1 -1
  17. package/dist/esm/algorithms/x25519.js +125 -0
  18. package/dist/esm/algorithms/x25519.js.map +1 -0
  19. package/dist/esm/cose/cbor.js +35 -0
  20. package/dist/esm/cose/cbor.js.map +1 -0
  21. package/dist/esm/cose/cose-key.js +312 -0
  22. package/dist/esm/cose/cose-key.js.map +1 -0
  23. package/dist/esm/cose/cose-sign1.js +283 -0
  24. package/dist/esm/cose/cose-sign1.js.map +1 -0
  25. package/dist/esm/cose/eat.js +254 -0
  26. package/dist/esm/cose/eat.js.map +1 -0
  27. package/dist/esm/crypto-error.js +4 -0
  28. package/dist/esm/crypto-error.js.map +1 -1
  29. package/dist/esm/index.js +9 -0
  30. package/dist/esm/index.js.map +1 -1
  31. package/dist/esm/local-key-manager.js +6 -1
  32. package/dist/esm/local-key-manager.js.map +1 -1
  33. package/dist/esm/primitives/ecies-secp256k1.js +79 -0
  34. package/dist/esm/primitives/ecies-secp256k1.js.map +1 -0
  35. package/dist/esm/primitives/x25519.js +9 -16
  36. package/dist/esm/primitives/x25519.js.map +1 -1
  37. package/dist/esm/utils.js +30 -0
  38. package/dist/esm/utils.js.map +1 -1
  39. package/dist/types/algorithms/aes-ctr.d.ts +1 -1
  40. package/dist/types/algorithms/aes-gcm.d.ts +23 -3
  41. package/dist/types/algorithms/aes-gcm.d.ts.map +1 -1
  42. package/dist/types/algorithms/aes-kw.d.ts +129 -0
  43. package/dist/types/algorithms/aes-kw.d.ts.map +1 -0
  44. package/dist/types/algorithms/ecdsa.d.ts +48 -3
  45. package/dist/types/algorithms/ecdsa.d.ts.map +1 -1
  46. package/dist/types/algorithms/eddsa.d.ts +48 -3
  47. package/dist/types/algorithms/eddsa.d.ts.map +1 -1
  48. package/dist/types/algorithms/hkdf.d.ts +35 -0
  49. package/dist/types/algorithms/hkdf.d.ts.map +1 -0
  50. package/dist/types/algorithms/pbkdf2.d.ts +35 -0
  51. package/dist/types/algorithms/pbkdf2.d.ts.map +1 -0
  52. package/dist/types/algorithms/sha-2.d.ts +1 -1
  53. package/dist/types/algorithms/x25519.d.ts +76 -0
  54. package/dist/types/algorithms/x25519.d.ts.map +1 -0
  55. package/dist/types/cose/cbor.d.ts +30 -0
  56. package/dist/types/cose/cbor.d.ts.map +1 -0
  57. package/dist/types/cose/cose-key.d.ts +106 -0
  58. package/dist/types/cose/cose-key.d.ts.map +1 -0
  59. package/dist/types/cose/cose-sign1.d.ts +195 -0
  60. package/dist/types/cose/cose-sign1.d.ts.map +1 -0
  61. package/dist/types/cose/eat.d.ts +203 -0
  62. package/dist/types/cose/eat.d.ts.map +1 -0
  63. package/dist/types/crypto-error.d.ts +4 -0
  64. package/dist/types/crypto-error.d.ts.map +1 -1
  65. package/dist/types/index.d.ts +9 -0
  66. package/dist/types/index.d.ts.map +1 -1
  67. package/dist/types/local-key-manager.d.ts +4 -4
  68. package/dist/types/local-key-manager.d.ts.map +1 -1
  69. package/dist/types/primitives/ecies-secp256k1.d.ts +53 -0
  70. package/dist/types/primitives/ecies-secp256k1.d.ts.map +1 -0
  71. package/dist/types/primitives/x25519.d.ts +9 -16
  72. package/dist/types/primitives/x25519.d.ts.map +1 -1
  73. package/dist/types/types/crypto-api.d.ts +52 -4
  74. package/dist/types/types/crypto-api.d.ts.map +1 -1
  75. package/dist/types/types/key-converter.d.ts +37 -15
  76. package/dist/types/types/key-converter.d.ts.map +1 -1
  77. package/dist/types/types/key-deriver.d.ts +41 -0
  78. package/dist/types/types/key-deriver.d.ts.map +1 -1
  79. package/dist/types/types/key-io.d.ts +37 -0
  80. package/dist/types/types/key-io.d.ts.map +1 -1
  81. package/dist/types/types/params-direct.d.ts +17 -0
  82. package/dist/types/types/params-direct.d.ts.map +1 -1
  83. package/dist/types/types/params-kms.d.ts +55 -0
  84. package/dist/types/types/params-kms.d.ts.map +1 -1
  85. package/dist/types/utils.d.ts +19 -0
  86. package/dist/types/utils.d.ts.map +1 -1
  87. package/dist/utils.js +1 -1
  88. package/dist/utils.js.map +3 -3
  89. package/package.json +12 -14
  90. package/src/algorithms/aes-ctr.ts +1 -1
  91. package/src/algorithms/aes-gcm.ts +38 -2
  92. package/src/algorithms/aes-kw.ts +182 -0
  93. package/src/algorithms/ecdsa.ts +132 -1
  94. package/src/algorithms/eddsa.ts +108 -1
  95. package/src/algorithms/hkdf.ts +54 -0
  96. package/src/algorithms/pbkdf2.ts +57 -0
  97. package/src/algorithms/sha-2.ts +1 -1
  98. package/src/algorithms/x25519.ts +153 -0
  99. package/src/cose/cbor.ts +36 -0
  100. package/src/cose/cose-key.ts +344 -0
  101. package/src/cose/cose-sign1.ts +473 -0
  102. package/src/cose/eat.ts +368 -0
  103. package/src/crypto-error.ts +6 -0
  104. package/src/index.ts +10 -0
  105. package/src/local-key-manager.ts +9 -4
  106. package/src/primitives/ecies-secp256k1.ts +113 -0
  107. package/src/primitives/x25519.ts +9 -16
  108. package/src/types/crypto-api.ts +124 -6
  109. package/src/types/key-converter.ts +33 -7
  110. package/src/types/key-deriver.ts +49 -0
  111. package/src/types/key-io.ts +40 -0
  112. package/src/types/params-direct.ts +21 -0
  113. package/src/types/params-kms.ts +67 -0
  114. package/src/utils.ts +53 -0
  115. package/dist/browser.js +0 -60
  116. package/dist/browser.js.map +0 -7
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../node_modules/.bun/@isaacs+ttlcache@1.4.1/node_modules/@isaacs/ttlcache/index.js", "../../../node_modules/.bun/level-supports@4.0.1/node_modules/level-supports/index.js", "../../../node_modules/.bun/module-error@1.0.2/node_modules/module-error/index.js", "../../../node_modules/.bun/base64-js@1.5.1/node_modules/base64-js/index.js", "../../../node_modules/.bun/ieee754@1.2.1/node_modules/ieee754/index.js", "../../../node_modules/.bun/buffer@6.0.3/node_modules/buffer/index.js", "../../../node_modules/.bun/level-transcoder@1.0.1/node_modules/level-transcoder/lib/text-endec.js", "../../../node_modules/.bun/level-transcoder@1.0.1/node_modules/level-transcoder/lib/encoding.js", "../../../node_modules/.bun/level-transcoder@1.0.1/node_modules/level-transcoder/lib/formats.js", "../../../node_modules/.bun/level-transcoder@1.0.1/node_modules/level-transcoder/lib/encodings.js", "../../../node_modules/.bun/level-transcoder@1.0.1/node_modules/level-transcoder/index.js", "../../../node_modules/.bun/events@3.3.0/node_modules/events/events.js", "../../../node_modules/.bun/catering@2.1.1/node_modules/catering/next-tick-browser.js", "../../../node_modules/.bun/catering@2.1.1/node_modules/catering/index.js", "../../../node_modules/.bun/abstract-level@1.0.4/node_modules/abstract-level/lib/common.js", "../../../node_modules/.bun/abstract-level@1.0.4/node_modules/abstract-level/abstract-iterator.js", "../../../node_modules/.bun/abstract-level@1.0.4/node_modules/abstract-level/lib/default-kv-iterator.js", "../../../node_modules/.bun/abstract-level@1.0.4/node_modules/abstract-level/lib/deferred-iterator.js", "../../../node_modules/.bun/abstract-level@1.0.4/node_modules/abstract-level/abstract-chained-batch.js", "../../../node_modules/.bun/abstract-level@1.0.4/node_modules/abstract-level/lib/default-chained-batch.js", "../../../node_modules/.bun/abstract-level@1.0.4/node_modules/abstract-level/lib/range-options.js", "../../../node_modules/.bun/queue-microtask@1.2.3/node_modules/queue-microtask/index.js", "../../../node_modules/.bun/abstract-level@1.0.4/node_modules/abstract-level/lib/next-tick-browser.js", "../../../node_modules/.bun/abstract-level@1.0.4/node_modules/abstract-level/lib/abstract-sublevel-iterator.js", "../../../node_modules/.bun/abstract-level@1.0.4/node_modules/abstract-level/lib/abstract-sublevel.js", "../../../node_modules/.bun/abstract-level@1.0.4/node_modules/abstract-level/abstract-level.js", "../../../node_modules/.bun/abstract-level@1.0.4/node_modules/abstract-level/index.js", "../../../node_modules/.bun/run-parallel-limit@1.1.0/node_modules/run-parallel-limit/index.js", "../../../node_modules/.bun/browser-level@1.0.1/node_modules/browser-level/util/key-range.js", "../../../node_modules/.bun/browser-level@1.0.1/node_modules/browser-level/util/deserialize.js", "../../../node_modules/.bun/browser-level@1.0.1/node_modules/browser-level/iterator.js", "../../../node_modules/.bun/browser-level@1.0.1/node_modules/browser-level/util/clear.js", "../../../node_modules/.bun/browser-level@1.0.1/node_modules/browser-level/index.js", "../../../node_modules/.bun/level@8.0.1/node_modules/level/browser.js", "../src/index.ts", "../src/crypto-error.ts", "../../common/src/cache.ts", "../../../node_modules/.bun/multiformats@13.1.0/node_modules/multiformats/src/bytes.ts", "../../../node_modules/.bun/multiformats@13.1.0/node_modules/multiformats/src/vendor/base-x.js", "../../../node_modules/.bun/multiformats@13.1.0/node_modules/multiformats/src/bases/base.ts", "../../../node_modules/.bun/multiformats@13.1.0/node_modules/multiformats/src/bases/base32.ts", "../../../node_modules/.bun/multiformats@13.1.0/node_modules/multiformats/src/bases/base58.ts", "../../../node_modules/.bun/multiformats@13.1.0/node_modules/multiformats/src/bases/base64.ts", "../../common/src/type-utils.ts", "../../common/src/convert.ts", "../../common/src/logger.ts", "../../../node_modules/.bun/multiformats@13.1.0/node_modules/multiformats/src/varint.ts", "../../../node_modules/.bun/multiformats@13.1.0/node_modules/multiformats/src/vendor/varint.js", "../../../node_modules/.bun/multiformats@13.1.0/node_modules/multiformats/src/hashes/digest.ts", "../../../node_modules/.bun/multiformats@13.1.0/node_modules/multiformats/src/cid.ts", "../../common/src/multicodec.ts", "../../common/src/object.ts", "../../common/src/stores.ts", "../src/algorithms/crypto-algorithm.ts", "../../../node_modules/.bun/@noble+curves@1.3.0/node_modules/@noble/curves/src/abstract/utils.ts", "../../../node_modules/.bun/@noble+hashes@1.3.3/node_modules/@noble/hashes/src/_assert.ts", "../../../node_modules/.bun/@noble+hashes@1.3.3/node_modules/@noble/hashes/src/crypto.ts", "../../../node_modules/.bun/@noble+hashes@1.3.3/node_modules/@noble/hashes/src/utils.ts", "../../../node_modules/.bun/@noble+hashes@1.3.3/node_modules/@noble/hashes/src/_sha2.ts", "../../../node_modules/.bun/@noble+hashes@1.3.3/node_modules/@noble/hashes/src/sha256.ts", "../../../node_modules/.bun/@noble+curves@1.3.0/node_modules/@noble/curves/src/abstract/modular.ts", "../../../node_modules/.bun/@noble+curves@1.3.0/node_modules/@noble/curves/src/abstract/curve.ts", "../../../node_modules/.bun/@noble+curves@1.3.0/node_modules/@noble/curves/src/abstract/weierstrass.ts", "../../../node_modules/.bun/@noble+hashes@1.3.3/node_modules/@noble/hashes/src/hmac.ts", "../../../node_modules/.bun/@noble+curves@1.3.0/node_modules/@noble/curves/src/_shortw_utils.ts", "../../../node_modules/.bun/@noble+curves@1.3.0/node_modules/@noble/curves/src/secp256k1.ts", "../../../node_modules/.bun/@noble+hashes@1.4.0/node_modules/@noble/hashes/src/_assert.ts", "../../../node_modules/.bun/@noble+hashes@1.4.0/node_modules/@noble/hashes/src/crypto.ts", "../../../node_modules/.bun/@noble+hashes@1.4.0/node_modules/@noble/hashes/src/utils.ts", "../../../node_modules/.bun/@noble+hashes@1.4.0/node_modules/@noble/hashes/src/_md.ts", "../../../node_modules/.bun/@noble+hashes@1.4.0/node_modules/@noble/hashes/src/sha256.ts", "../src/jose/utils.ts", "../src/primitives/sha256.ts", "../src/jose/jwk.ts", "../src/primitives/secp256k1.ts", "../../../node_modules/.bun/@noble+curves@1.3.0/node_modules/@noble/curves/src/p256.ts", "../src/primitives/secp256r1.ts", "../src/algorithms/ecdsa.ts", "../../../node_modules/.bun/@noble+hashes@1.3.3/node_modules/@noble/hashes/src/_u64.ts", "../../../node_modules/.bun/@noble+hashes@1.3.3/node_modules/@noble/hashes/src/sha512.ts", "../../../node_modules/.bun/@noble+curves@1.3.0/node_modules/@noble/curves/src/abstract/edwards.ts", "../../../node_modules/.bun/@noble+curves@1.3.0/node_modules/@noble/curves/src/abstract/montgomery.ts", "../../../node_modules/.bun/@noble+curves@1.3.0/node_modules/@noble/curves/src/ed25519.ts", "../src/primitives/ed25519.ts", "../src/algorithms/eddsa.ts", "../src/algorithms/sha-2.ts", "../src/local-key-manager.ts", "../src/utils.ts", "../../../node_modules/.bun/@noble+ciphers@0.5.3/node_modules/@noble/ciphers/src/crypto.ts", "../src/primitives/aes-ctr.ts", "../src/algorithms/aes-ctr.ts", "../../../node_modules/.bun/@noble+ciphers@0.5.3/node_modules/@noble/ciphers/src/_assert.ts", "../../../node_modules/.bun/@noble+ciphers@0.5.3/node_modules/@noble/ciphers/src/utils.ts", "../../../node_modules/.bun/@noble+ciphers@0.5.3/node_modules/@noble/ciphers/src/webcrypto.ts", "../src/primitives/aes-gcm.ts", "../src/algorithms/aes-gcm.ts", "../src/primitives/aes-kw.ts", "../src/primitives/concat-kdf.ts", "../src/primitives/hkdf.ts", "../src/primitives/pbkdf2.ts", "../src/primitives/x25519.ts", "../../../node_modules/.bun/@noble+ciphers@0.5.3/node_modules/@noble/ciphers/src/_poly1305.ts", "../../../node_modules/.bun/@noble+ciphers@0.5.3/node_modules/@noble/ciphers/src/_arx.ts", "../../../node_modules/.bun/@noble+ciphers@0.5.3/node_modules/@noble/ciphers/src/chacha.ts", "../src/primitives/xchacha20.ts", "../src/primitives/xchacha20-poly1305.ts"],
4
- "sourcesContent": ["// A simple TTL cache with max capacity option, ms resolution,\n// autopurge, and reasonably optimized performance\n// Relies on the fact that integer Object keys are kept sorted,\n// and managed very efficiently by V8.\n\n/* istanbul ignore next */\nconst perf =\n typeof performance === 'object' &&\n performance &&\n typeof performance.now === 'function'\n ? performance\n : Date\n\nconst now = () => perf.now()\nconst isPosInt = n => n && n === Math.floor(n) && n > 0 && isFinite(n)\nconst isPosIntOrInf = n => n === Infinity || isPosInt(n)\n\nclass TTLCache {\n constructor({\n max = Infinity,\n ttl,\n updateAgeOnGet = false,\n checkAgeOnGet = false,\n noUpdateTTL = false,\n dispose,\n noDisposeOnSet = false,\n } = {}) {\n // {[expirationTime]: [keys]}\n this.expirations = Object.create(null)\n // {key=>val}\n this.data = new Map()\n // {key=>expiration}\n this.expirationMap = new Map()\n if (ttl !== undefined && !isPosIntOrInf(ttl)) {\n throw new TypeError(\n 'ttl must be positive integer or Infinity if set'\n )\n }\n if (!isPosIntOrInf(max)) {\n throw new TypeError('max must be positive integer or Infinity')\n }\n this.ttl = ttl\n this.max = max\n this.updateAgeOnGet = !!updateAgeOnGet\n this.checkAgeOnGet = !!checkAgeOnGet\n this.noUpdateTTL = !!noUpdateTTL\n this.noDisposeOnSet = !!noDisposeOnSet\n if (dispose !== undefined) {\n if (typeof dispose !== 'function') {\n throw new TypeError('dispose must be function if set')\n }\n this.dispose = dispose\n }\n\n this.timer = undefined\n this.timerExpiration = undefined\n }\n\n setTimer(expiration, ttl) {\n if (this.timerExpiration < expiration) {\n return\n }\n\n if (this.timer) {\n clearTimeout(this.timer)\n }\n\n const t = setTimeout(() => {\n this.timer = undefined\n this.timerExpiration = undefined\n this.purgeStale()\n for (const exp in this.expirations) {\n this.setTimer(exp, exp - now())\n break\n }\n }, ttl)\n\n /* istanbul ignore else - affordance for non-node envs */\n if (t.unref) t.unref()\n\n this.timerExpiration = expiration\n this.timer = t\n }\n\n // hang onto the timer so we can clearTimeout if all items\n // are deleted. Deno doesn't have Timer.unref(), so it\n // hangs otherwise.\n cancelTimer() {\n if (this.timer) {\n clearTimeout(this.timer)\n this.timerExpiration = undefined\n this.timer = undefined\n }\n }\n\n /* istanbul ignore next */\n cancelTimers() {\n process.emitWarning(\n 'TTLCache.cancelTimers has been renamed to ' +\n 'TTLCache.cancelTimer (no \"s\"), and will be removed in the next ' +\n 'major version update'\n )\n return this.cancelTimer()\n }\n\n clear() {\n const entries =\n this.dispose !== TTLCache.prototype.dispose ? [...this] : []\n this.data.clear()\n this.expirationMap.clear()\n // no need for any purging now\n this.cancelTimer()\n this.expirations = Object.create(null)\n for (const [key, val] of entries) {\n this.dispose(val, key, 'delete')\n }\n }\n\n setTTL(key, ttl = this.ttl) {\n const current = this.expirationMap.get(key)\n if (current !== undefined) {\n // remove from the expirations list, so it isn't purged\n const exp = this.expirations[current]\n if (!exp || exp.length <= 1) {\n delete this.expirations[current]\n } else {\n this.expirations[current] = exp.filter(k => k !== key)\n }\n }\n\n if (ttl !== Infinity) {\n const expiration = Math.floor(now() + ttl)\n this.expirationMap.set(key, expiration)\n if (!this.expirations[expiration]) {\n this.expirations[expiration] = []\n this.setTimer(expiration, ttl)\n }\n this.expirations[expiration].push(key)\n } else {\n this.expirationMap.set(key, Infinity)\n }\n }\n\n set(\n key,\n val,\n {\n ttl = this.ttl,\n noUpdateTTL = this.noUpdateTTL,\n noDisposeOnSet = this.noDisposeOnSet,\n } = {}\n ) {\n if (!isPosIntOrInf(ttl)) {\n throw new TypeError('ttl must be positive integer or Infinity')\n }\n if (this.expirationMap.has(key)) {\n if (!noUpdateTTL) {\n this.setTTL(key, ttl)\n }\n // has old value\n const oldValue = this.data.get(key)\n if (oldValue !== val) {\n this.data.set(key, val)\n if (!noDisposeOnSet) {\n this.dispose(oldValue, key, 'set')\n }\n }\n } else {\n this.setTTL(key, ttl)\n this.data.set(key, val)\n }\n\n while (this.size > this.max) {\n this.purgeToCapacity()\n }\n\n return this\n }\n\n has(key) {\n return this.data.has(key)\n }\n\n getRemainingTTL(key) {\n const expiration = this.expirationMap.get(key)\n return expiration === Infinity\n ? expiration\n : expiration !== undefined\n ? Math.max(0, Math.ceil(expiration - now()))\n : 0\n }\n\n get(\n key,\n {\n updateAgeOnGet = this.updateAgeOnGet,\n ttl = this.ttl,\n checkAgeOnGet = this.checkAgeOnGet,\n } = {}\n ) {\n const val = this.data.get(key)\n if (checkAgeOnGet && this.getRemainingTTL(key) === 0) {\n this.delete(key)\n return undefined\n }\n if (updateAgeOnGet) {\n this.setTTL(key, ttl)\n }\n return val\n }\n\n dispose(_, __) {}\n\n delete(key) {\n const current = this.expirationMap.get(key)\n if (current !== undefined) {\n const value = this.data.get(key)\n this.data.delete(key)\n this.expirationMap.delete(key)\n const exp = this.expirations[current]\n if (exp) {\n if (exp.length <= 1) {\n delete this.expirations[current]\n } else {\n this.expirations[current] = exp.filter(k => k !== key)\n }\n }\n this.dispose(value, key, 'delete')\n if (this.size === 0) {\n this.cancelTimer()\n }\n return true\n }\n return false\n }\n\n purgeToCapacity() {\n for (const exp in this.expirations) {\n const keys = this.expirations[exp]\n if (this.size - keys.length >= this.max) {\n delete this.expirations[exp]\n const entries = []\n for (const key of keys) {\n entries.push([key, this.data.get(key)])\n this.data.delete(key)\n this.expirationMap.delete(key)\n }\n for (const [key, val] of entries) {\n this.dispose(val, key, 'evict')\n }\n } else {\n const s = this.size - this.max\n const entries = []\n for (const key of keys.splice(0, s)) {\n entries.push([key, this.data.get(key)])\n this.data.delete(key)\n this.expirationMap.delete(key)\n }\n for (const [key, val] of entries) {\n this.dispose(val, key, 'evict')\n }\n return\n }\n }\n }\n\n get size() {\n return this.data.size\n }\n\n purgeStale() {\n const n = Math.ceil(now())\n for (const exp in this.expirations) {\n if (exp === 'Infinity' || exp > n) {\n return\n }\n\n /* istanbul ignore next\n * mysterious need for a guard here?\n * https://github.com/isaacs/ttlcache/issues/26 */\n const keys = [...(this.expirations[exp] || [])]\n const entries = []\n delete this.expirations[exp]\n for (const key of keys) {\n entries.push([key, this.data.get(key)])\n this.data.delete(key)\n this.expirationMap.delete(key)\n }\n for (const [key, val] of entries) {\n this.dispose(val, key, 'stale')\n }\n }\n if (this.size === 0) {\n this.cancelTimer()\n }\n }\n\n *entries() {\n for (const exp in this.expirations) {\n for (const key of this.expirations[exp]) {\n yield [key, this.data.get(key)]\n }\n }\n }\n *keys() {\n for (const exp in this.expirations) {\n for (const key of this.expirations[exp]) {\n yield key\n }\n }\n }\n *values() {\n for (const exp in this.expirations) {\n for (const key of this.expirations[exp]) {\n yield this.data.get(key)\n }\n }\n }\n [Symbol.iterator]() {\n return this.entries()\n }\n}\n\nmodule.exports = TTLCache\n", "'use strict'\n\nexports.supports = function supports (...manifests) {\n const manifest = manifests.reduce((acc, m) => Object.assign(acc, m), {})\n\n return Object.assign(manifest, {\n snapshots: manifest.snapshots || false,\n permanence: manifest.permanence || false,\n seek: manifest.seek || false,\n clear: manifest.clear || false,\n getMany: manifest.getMany || false,\n keyIterator: manifest.keyIterator || false,\n valueIterator: manifest.valueIterator || false,\n iteratorNextv: manifest.iteratorNextv || false,\n iteratorAll: manifest.iteratorAll || false,\n status: manifest.status || false,\n createIfMissing: manifest.createIfMissing || false,\n errorIfExists: manifest.errorIfExists || false,\n deferredOpen: manifest.deferredOpen || false,\n promises: manifest.promises || false,\n streams: manifest.streams || false,\n encodings: Object.assign({}, manifest.encodings),\n events: Object.assign({}, manifest.events),\n additionalMethods: Object.assign({}, manifest.additionalMethods)\n })\n}\n", "'use strict'\n\nmodule.exports = class ModuleError extends Error {\n /**\n * @param {string} message Error message\n * @param {{ code?: string, cause?: Error, expected?: boolean, transient?: boolean }} [options]\n */\n constructor (message, options) {\n super(message || '')\n\n if (typeof options === 'object' && options !== null) {\n if (options.code) this.code = String(options.code)\n if (options.expected) this.expected = true\n if (options.transient) this.transient = true\n if (options.cause) this.cause = options.cause\n }\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor)\n }\n }\n}\n", "'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n", "/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n", "/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh <https://feross.org>\n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nconst base64 = require('base64-js')\nconst ieee754 = require('ieee754')\nconst customInspectSymbol =\n (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation\n ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation\n : null\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\nconst K_MAX_LENGTH = 0x7fffffff\nexports.kMaxLength = K_MAX_LENGTH\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Print warning and recommend using `buffer` v4.x which has an Object\n * implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * We report that the browser does not support typed arrays if the are not subclassable\n * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`\n * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support\n * for __proto__ and has a buggy typed array implementation.\n */\nBuffer.TYPED_ARRAY_SUPPORT = typedArraySupport()\n\nif (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&\n typeof console.error === 'function') {\n console.error(\n 'This browser lacks typed array (Uint8Array) support which is required by ' +\n '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'\n )\n}\n\nfunction typedArraySupport () {\n // Can typed array instances can be augmented?\n try {\n const arr = new Uint8Array(1)\n const proto = { foo: function () { return 42 } }\n Object.setPrototypeOf(proto, Uint8Array.prototype)\n Object.setPrototypeOf(arr, proto)\n return arr.foo() === 42\n } catch (e) {\n return false\n }\n}\n\nObject.defineProperty(Buffer.prototype, 'parent', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.buffer\n }\n})\n\nObject.defineProperty(Buffer.prototype, 'offset', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.byteOffset\n }\n})\n\nfunction createBuffer (length) {\n if (length > K_MAX_LENGTH) {\n throw new RangeError('The value \"' + length + '\" is invalid for option \"size\"')\n }\n // Return an augmented `Uint8Array` instance\n const buf = new Uint8Array(length)\n Object.setPrototypeOf(buf, Buffer.prototype)\n return buf\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new TypeError(\n 'The \"string\" argument must be of type string. Received type number'\n )\n }\n return allocUnsafe(arg)\n }\n return from(arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\nfunction from (value, encodingOrOffset, length) {\n if (typeof value === 'string') {\n return fromString(value, encodingOrOffset)\n }\n\n if (ArrayBuffer.isView(value)) {\n return fromArrayView(value)\n }\n\n if (value == null) {\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n }\n\n if (isInstance(value, ArrayBuffer) ||\n (value && isInstance(value.buffer, ArrayBuffer))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof SharedArrayBuffer !== 'undefined' &&\n (isInstance(value, SharedArrayBuffer) ||\n (value && isInstance(value.buffer, SharedArrayBuffer)))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof value === 'number') {\n throw new TypeError(\n 'The \"value\" argument must not be of type number. Received type number'\n )\n }\n\n const valueOf = value.valueOf && value.valueOf()\n if (valueOf != null && valueOf !== value) {\n return Buffer.from(valueOf, encodingOrOffset, length)\n }\n\n const b = fromObject(value)\n if (b) return b\n\n if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&\n typeof value[Symbol.toPrimitive] === 'function') {\n return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length)\n }\n\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(value, encodingOrOffset, length)\n}\n\n// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:\n// https://github.com/feross/buffer/pull/148\nObject.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)\nObject.setPrototypeOf(Buffer, Uint8Array)\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be of type number')\n } else if (size < 0) {\n throw new RangeError('The value \"' + size + '\" is invalid for option \"size\"')\n }\n}\n\nfunction alloc (size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpreted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(size).fill(fill, encoding)\n : createBuffer(size).fill(fill)\n }\n return createBuffer(size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(size, fill, encoding)\n}\n\nfunction allocUnsafe (size) {\n assertSize(size)\n return createBuffer(size < 0 ? 0 : checked(size) | 0)\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(size)\n}\n\nfunction fromString (string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n\n const length = byteLength(string, encoding) | 0\n let buf = createBuffer(length)\n\n const actual = buf.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n buf = buf.slice(0, actual)\n }\n\n return buf\n}\n\nfunction fromArrayLike (array) {\n const length = array.length < 0 ? 0 : checked(array.length) | 0\n const buf = createBuffer(length)\n for (let i = 0; i < length; i += 1) {\n buf[i] = array[i] & 255\n }\n return buf\n}\n\nfunction fromArrayView (arrayView) {\n if (isInstance(arrayView, Uint8Array)) {\n const copy = new Uint8Array(arrayView)\n return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)\n }\n return fromArrayLike(arrayView)\n}\n\nfunction fromArrayBuffer (array, byteOffset, length) {\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\"offset\" is outside of buffer bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\"length\" is outside of buffer bounds')\n }\n\n let buf\n if (byteOffset === undefined && length === undefined) {\n buf = new Uint8Array(array)\n } else if (length === undefined) {\n buf = new Uint8Array(array, byteOffset)\n } else {\n buf = new Uint8Array(array, byteOffset, length)\n }\n\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(buf, Buffer.prototype)\n\n return buf\n}\n\nfunction fromObject (obj) {\n if (Buffer.isBuffer(obj)) {\n const len = checked(obj.length) | 0\n const buf = createBuffer(len)\n\n if (buf.length === 0) {\n return buf\n }\n\n obj.copy(buf, 0, 0, len)\n return buf\n }\n\n if (obj.length !== undefined) {\n if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {\n return createBuffer(0)\n }\n return fromArrayLike(obj)\n }\n\n if (obj.type === 'Buffer' && Array.isArray(obj.data)) {\n return fromArrayLike(obj.data)\n }\n}\n\nfunction checked (length) {\n // Note: cannot use `length < K_MAX_LENGTH` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= K_MAX_LENGTH) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return b != null && b._isBuffer === true &&\n b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false\n}\n\nBuffer.compare = function compare (a, b) {\n if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)\n if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError(\n 'The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array'\n )\n }\n\n if (a === b) return 0\n\n let x = a.length\n let y = b.length\n\n for (let i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!Array.isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n let i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n const buffer = Buffer.allocUnsafe(length)\n let pos = 0\n for (i = 0; i < list.length; ++i) {\n let buf = list[i]\n if (isInstance(buf, Uint8Array)) {\n if (pos + buf.length > buffer.length) {\n if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)\n buf.copy(buffer, pos)\n } else {\n Uint8Array.prototype.set.call(\n buffer,\n buf,\n pos\n )\n }\n } else if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n } else {\n buf.copy(buffer, pos)\n }\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n throw new TypeError(\n 'The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. ' +\n 'Received type ' + typeof string\n )\n }\n\n const len = string.length\n const mustMatch = (arguments.length > 2 && arguments[2] === true)\n if (!mustMatch && len === 0) return 0\n\n // Use a for loop to avoid recursion\n let loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) {\n return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8\n }\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n let loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coercion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)\n// to detect a Buffer instance. It's not possible to use `instanceof Buffer`\n// reliably in a browserify context because there could be multiple different\n// copies of the 'buffer' package in use. This method works even for Buffer\n// instances that were created from another copy of the `buffer` package.\n// See: https://github.com/feross/buffer/issues/154\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n const i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n const len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (let i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n const len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (let i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n const len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (let i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n const length = this.length\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.toLocaleString = Buffer.prototype.toString\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n let str = ''\n const max = exports.INSPECT_MAX_BYTES\n str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()\n if (this.length > max) str += ' ... '\n return '<Buffer ' + str + '>'\n}\nif (customInspectSymbol) {\n Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (isInstance(target, Uint8Array)) {\n target = Buffer.from(target, target.offset, target.byteLength)\n }\n if (!Buffer.isBuffer(target)) {\n throw new TypeError(\n 'The \"target\" argument must be one of type Buffer or Uint8Array. ' +\n 'Received type ' + (typeof target)\n )\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n let x = thisEnd - thisStart\n let y = end - start\n const len = Math.min(x, y)\n\n const thisCopy = this.slice(thisStart, thisEnd)\n const targetCopy = target.slice(start, end)\n\n for (let i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (numberIsNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n let indexSize = 1\n let arrLength = arr.length\n let valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n let i\n if (dir) {\n let foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n let found = true\n for (let j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n const remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n const strLen = string.length\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n let i\n for (i = 0; i < length; ++i) {\n const parsed = parseInt(string.substr(i * 2, 2), 16)\n if (numberIsNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset >>> 0\n if (isFinite(length)) {\n length = length >>> 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n const remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n let loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n case 'latin1':\n case 'binary':\n return asciiWrite(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n const res = []\n\n let i = start\n while (i < end) {\n const firstByte = buf[i]\n let codePoint = null\n let bytesPerSequence = (firstByte > 0xEF)\n ? 4\n : (firstByte > 0xDF)\n ? 3\n : (firstByte > 0xBF)\n ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n let secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nconst MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n const len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n let res = ''\n let i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n let ret = ''\n end = Math.min(buf.length, end)\n\n for (let i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n let ret = ''\n end = Math.min(buf.length, end)\n\n for (let i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n const len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n let out = ''\n for (let i = start; i < end; ++i) {\n out += hexSliceLookupTable[buf[i]]\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n const bytes = buf.slice(start, end)\n let res = ''\n // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)\n for (let i = 0; i < bytes.length - 1; i += 2) {\n res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n const len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n const newBuf = this.subarray(start, end)\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(newBuf, Buffer.prototype)\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUintLE =\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let val = this[offset]\n let mul = 1\n let i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUintBE =\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n let val = this[offset + --byteLength]\n let mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUint8 =\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUint16LE =\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUint16BE =\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUint32LE =\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUint32BE =\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const lo = first +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 24\n\n const hi = this[++offset] +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n last * 2 ** 24\n\n return BigInt(lo) + (BigInt(hi) << BigInt(32))\n})\n\nBuffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const hi = first * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n this[++offset]\n\n const lo = this[++offset] * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n last\n\n return (BigInt(hi) << BigInt(32)) + BigInt(lo)\n})\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let val = this[offset]\n let mul = 1\n let i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let i = byteLength\n let mul = 1\n let val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n const val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n const val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const val = this[offset + 4] +\n this[offset + 5] * 2 ** 8 +\n this[offset + 6] * 2 ** 16 +\n (last << 24) // Overflow\n\n return (BigInt(val) << BigInt(32)) +\n BigInt(first +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 24)\n})\n\nBuffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const val = (first << 24) + // Overflow\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n this[++offset]\n\n return (BigInt(val) << BigInt(32)) +\n BigInt(this[++offset] * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n last)\n})\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUintLE =\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n const maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n let mul = 1\n let i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUintBE =\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n const maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n let i = byteLength - 1\n let mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUint8 =\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeUint16LE =\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeUint16BE =\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeUint32LE =\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeUint32BE =\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nfunction wrtBigUInt64LE (buf, value, offset, min, max) {\n checkIntBI(value, min, max, buf, offset, 7)\n\n let lo = Number(value & BigInt(0xffffffff))\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n let hi = Number(value >> BigInt(32) & BigInt(0xffffffff))\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n return offset\n}\n\nfunction wrtBigUInt64BE (buf, value, offset, min, max) {\n checkIntBI(value, min, max, buf, offset, 7)\n\n let lo = Number(value & BigInt(0xffffffff))\n buf[offset + 7] = lo\n lo = lo >> 8\n buf[offset + 6] = lo\n lo = lo >> 8\n buf[offset + 5] = lo\n lo = lo >> 8\n buf[offset + 4] = lo\n let hi = Number(value >> BigInt(32) & BigInt(0xffffffff))\n buf[offset + 3] = hi\n hi = hi >> 8\n buf[offset + 2] = hi\n hi = hi >> 8\n buf[offset + 1] = hi\n hi = hi >> 8\n buf[offset] = hi\n return offset + 8\n}\n\nBuffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) {\n return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))\n})\n\nBuffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) {\n return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))\n})\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n const limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n let i = 0\n let mul = 1\n let sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n const limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n let i = byteLength - 1\n let mul = 1\n let sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) {\n return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))\n})\n\nBuffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) {\n return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))\n})\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('Index out of range')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n const len = end - start\n\n if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {\n // Use built-in when available, missing from IE11\n this.copyWithin(targetStart, start, end)\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, end),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n if (val.length === 1) {\n const code = val.charCodeAt(0)\n if ((encoding === 'utf8' && code < 128) ||\n encoding === 'latin1') {\n // Fast path: If `val` fits into a single byte, use that numeric value.\n val = code\n }\n }\n } else if (typeof val === 'number') {\n val = val & 255\n } else if (typeof val === 'boolean') {\n val = Number(val)\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n let i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n const bytes = Buffer.isBuffer(val)\n ? val\n : Buffer.from(val, encoding)\n const len = bytes.length\n if (len === 0) {\n throw new TypeError('The value \"' + val +\n '\" is invalid for argument \"value\"')\n }\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// CUSTOM ERRORS\n// =============\n\n// Simplified versions from Node, changed for Buffer-only usage\nconst errors = {}\nfunction E (sym, getMessage, Base) {\n errors[sym] = class NodeError extends Base {\n constructor () {\n super()\n\n Object.defineProperty(this, 'message', {\n value: getMessage.apply(this, arguments),\n writable: true,\n configurable: true\n })\n\n // Add the error code to the name to include it in the stack trace.\n this.name = `${this.name} [${sym}]`\n // Access the stack to generate the error message including the error code\n // from the name.\n this.stack // eslint-disable-line no-unused-expressions\n // Reset the name to the actual name.\n delete this.name\n }\n\n get code () {\n return sym\n }\n\n set code (value) {\n Object.defineProperty(this, 'code', {\n configurable: true,\n enumerable: true,\n value,\n writable: true\n })\n }\n\n toString () {\n return `${this.name} [${sym}]: ${this.message}`\n }\n }\n}\n\nE('ERR_BUFFER_OUT_OF_BOUNDS',\n function (name) {\n if (name) {\n return `${name} is outside of buffer bounds`\n }\n\n return 'Attempt to access memory outside buffer bounds'\n }, RangeError)\nE('ERR_INVALID_ARG_TYPE',\n function (name, actual) {\n return `The \"${name}\" argument must be of type number. Received type ${typeof actual}`\n }, TypeError)\nE('ERR_OUT_OF_RANGE',\n function (str, range, input) {\n let msg = `The value of \"${str}\" is out of range.`\n let received = input\n if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {\n received = addNumericalSeparator(String(input))\n } else if (typeof input === 'bigint') {\n received = String(input)\n if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {\n received = addNumericalSeparator(received)\n }\n received += 'n'\n }\n msg += ` It must be ${range}. Received ${received}`\n return msg\n }, RangeError)\n\nfunction addNumericalSeparator (val) {\n let res = ''\n let i = val.length\n const start = val[0] === '-' ? 1 : 0\n for (; i >= start + 4; i -= 3) {\n res = `_${val.slice(i - 3, i)}${res}`\n }\n return `${val.slice(0, i)}${res}`\n}\n\n// CHECK FUNCTIONS\n// ===============\n\nfunction checkBounds (buf, offset, byteLength) {\n validateNumber(offset, 'offset')\n if (buf[offset] === undefined || buf[offset + byteLength] === undefined) {\n boundsError(offset, buf.length - (byteLength + 1))\n }\n}\n\nfunction checkIntBI (value, min, max, buf, offset, byteLength) {\n if (value > max || value < min) {\n const n = typeof min === 'bigint' ? 'n' : ''\n let range\n if (byteLength > 3) {\n if (min === 0 || min === BigInt(0)) {\n range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}`\n } else {\n range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` +\n `${(byteLength + 1) * 8 - 1}${n}`\n }\n } else {\n range = `>= ${min}${n} and <= ${max}${n}`\n }\n throw new errors.ERR_OUT_OF_RANGE('value', range, value)\n }\n checkBounds(buf, offset, byteLength)\n}\n\nfunction validateNumber (value, name) {\n if (typeof value !== 'number') {\n throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value)\n }\n}\n\nfunction boundsError (value, length, type) {\n if (Math.floor(value) !== value) {\n validateNumber(value, type)\n throw new errors.ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value)\n }\n\n if (length < 0) {\n throw new errors.ERR_BUFFER_OUT_OF_BOUNDS()\n }\n\n throw new errors.ERR_OUT_OF_RANGE(type || 'offset',\n `>= ${type ? 1 : 0} and <= ${length}`,\n value)\n}\n\n// HELPER FUNCTIONS\n// ================\n\nconst INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node takes equal signs as end of the Base64 encoding\n str = str.split('=')[0]\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = str.trim().replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n let codePoint\n const length = string.length\n let leadSurrogate = null\n const bytes = []\n\n for (let i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n const byteArray = []\n for (let i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n let c, hi, lo\n const byteArray = []\n for (let i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n let i\n for (i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\n// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass\n// the `instanceof` check but they should be treated as of that type.\n// See: https://github.com/feross/buffer/issues/166\nfunction isInstance (obj, type) {\n return obj instanceof type ||\n (obj != null && obj.constructor != null && obj.constructor.name != null &&\n obj.constructor.name === type.name)\n}\nfunction numberIsNaN (obj) {\n // For IE11 support\n return obj !== obj // eslint-disable-line no-self-compare\n}\n\n// Create lookup table for `toString('hex')`\n// See: https://github.com/feross/buffer/issues/219\nconst hexSliceLookupTable = (function () {\n const alphabet = '0123456789abcdef'\n const table = new Array(256)\n for (let i = 0; i < 16; ++i) {\n const i16 = i * 16\n for (let j = 0; j < 16; ++j) {\n table[i16 + j] = alphabet[i] + alphabet[j]\n }\n }\n return table\n})()\n\n// Return not function with Error if BigInt not supported\nfunction defineBigIntMethod (fn) {\n return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn\n}\n\nfunction BufferBigIntNotDefined () {\n throw new Error('BigInt not supported')\n}\n", "'use strict'\n\n/** @type {{ textEncoder: TextEncoder, textDecoder: TextDecoder }|null} */\nlet lazy = null\n\n/**\n * Get semi-global instances of TextEncoder and TextDecoder.\n * @returns {{ textEncoder: TextEncoder, textDecoder: TextDecoder }}\n */\nmodule.exports = function () {\n if (lazy === null) {\n lazy = {\n textEncoder: new TextEncoder(),\n textDecoder: new TextDecoder()\n }\n }\n\n return lazy\n}\n", "'use strict'\n\nconst ModuleError = require('module-error')\nconst formats = new Set(['buffer', 'view', 'utf8'])\n\n/**\n * @template TIn, TFormat, TOut\n * @abstract\n */\nclass Encoding {\n /**\n * @param {IEncoding<TIn,TFormat,TOut>} options\n */\n constructor (options) {\n /** @type {(data: TIn) => TFormat} */\n this.encode = options.encode || this.encode\n\n /** @type {(data: TFormat) => TOut} */\n this.decode = options.decode || this.decode\n\n /** @type {string} */\n this.name = options.name || this.name\n\n /** @type {string} */\n this.format = options.format || this.format\n\n if (typeof this.encode !== 'function') {\n throw new TypeError(\"The 'encode' property must be a function\")\n }\n\n if (typeof this.decode !== 'function') {\n throw new TypeError(\"The 'decode' property must be a function\")\n }\n\n this.encode = this.encode.bind(this)\n this.decode = this.decode.bind(this)\n\n if (typeof this.name !== 'string' || this.name === '') {\n throw new TypeError(\"The 'name' property must be a string\")\n }\n\n if (typeof this.format !== 'string' || !formats.has(this.format)) {\n throw new TypeError(\"The 'format' property must be one of 'buffer', 'view', 'utf8'\")\n }\n\n if (options.createViewTranscoder) {\n this.createViewTranscoder = options.createViewTranscoder\n }\n\n if (options.createBufferTranscoder) {\n this.createBufferTranscoder = options.createBufferTranscoder\n }\n\n if (options.createUTF8Transcoder) {\n this.createUTF8Transcoder = options.createUTF8Transcoder\n }\n }\n\n get commonName () {\n return /** @type {string} */ (this.name.split('+')[0])\n }\n\n /** @return {BufferFormat<TIn,TOut>} */\n createBufferTranscoder () {\n throw new ModuleError(`Encoding '${this.name}' cannot be transcoded to 'buffer'`, {\n code: 'LEVEL_ENCODING_NOT_SUPPORTED'\n })\n }\n\n /** @return {ViewFormat<TIn,TOut>} */\n createViewTranscoder () {\n throw new ModuleError(`Encoding '${this.name}' cannot be transcoded to 'view'`, {\n code: 'LEVEL_ENCODING_NOT_SUPPORTED'\n })\n }\n\n /** @return {UTF8Format<TIn,TOut>} */\n createUTF8Transcoder () {\n throw new ModuleError(`Encoding '${this.name}' cannot be transcoded to 'utf8'`, {\n code: 'LEVEL_ENCODING_NOT_SUPPORTED'\n })\n }\n}\n\nexports.Encoding = Encoding\n\n/**\n * @typedef {import('./encoding').IEncoding<TIn,TFormat,TOut>} IEncoding\n * @template TIn, TFormat, TOut\n */\n\n/**\n * @typedef {import('./formats').BufferFormat<TIn,TOut>} BufferFormat\n * @template TIn, TOut\n */\n\n/**\n * @typedef {import('./formats').ViewFormat<TIn,TOut>} ViewFormat\n * @template TIn, TOut\n */\n\n/**\n * @typedef {import('./formats').UTF8Format<TIn,TOut>} UTF8Format\n * @template TIn, TOut\n */\n", "'use strict'\n\nconst { Buffer } = require('buffer') || {}\nconst { Encoding } = require('./encoding')\nconst textEndec = require('./text-endec')\n\n/**\n * @template TIn, TOut\n * @extends {Encoding<TIn,Buffer,TOut>}\n */\nclass BufferFormat extends Encoding {\n /**\n * @param {Omit<IEncoding<TIn, Buffer, TOut>, 'format'>} options\n */\n constructor (options) {\n super({ ...options, format: 'buffer' })\n }\n\n /** @override */\n createViewTranscoder () {\n return new ViewFormat({\n encode: this.encode, // Buffer is a view (UInt8Array)\n decode: (data) => this.decode(\n Buffer.from(data.buffer, data.byteOffset, data.byteLength)\n ),\n name: `${this.name}+view`\n })\n }\n\n /** @override */\n createBufferTranscoder () {\n return this\n }\n}\n\n/**\n * @extends {Encoding<TIn,Uint8Array,TOut>}\n * @template TIn, TOut\n */\nclass ViewFormat extends Encoding {\n /**\n * @param {Omit<IEncoding<TIn, Uint8Array, TOut>, 'format'>} options\n */\n constructor (options) {\n super({ ...options, format: 'view' })\n }\n\n /** @override */\n createBufferTranscoder () {\n return new BufferFormat({\n encode: (data) => {\n const view = this.encode(data)\n return Buffer.from(view.buffer, view.byteOffset, view.byteLength)\n },\n decode: this.decode, // Buffer is a view (UInt8Array)\n name: `${this.name}+buffer`\n })\n }\n\n /** @override */\n createViewTranscoder () {\n return this\n }\n}\n\n/**\n * @extends {Encoding<TIn,string,TOut>}\n * @template TIn, TOut\n */\nclass UTF8Format extends Encoding {\n /**\n * @param {Omit<IEncoding<TIn, string, TOut>, 'format'>} options\n */\n constructor (options) {\n super({ ...options, format: 'utf8' })\n }\n\n /** @override */\n createBufferTranscoder () {\n return new BufferFormat({\n encode: (data) => Buffer.from(this.encode(data), 'utf8'),\n decode: (data) => this.decode(data.toString('utf8')),\n name: `${this.name}+buffer`\n })\n }\n\n /** @override */\n createViewTranscoder () {\n const { textEncoder, textDecoder } = textEndec()\n\n return new ViewFormat({\n encode: (data) => textEncoder.encode(this.encode(data)),\n decode: (data) => this.decode(textDecoder.decode(data)),\n name: `${this.name}+view`\n })\n }\n\n /** @override */\n createUTF8Transcoder () {\n return this\n }\n}\n\nexports.BufferFormat = BufferFormat\nexports.ViewFormat = ViewFormat\nexports.UTF8Format = UTF8Format\n\n/**\n * @typedef {import('./encoding').IEncoding<TIn,TFormat,TOut>} IEncoding\n * @template TIn, TFormat, TOut\n */\n", "'use strict'\n\nconst { Buffer } = require('buffer') || { Buffer: { isBuffer: () => false } }\nconst { textEncoder, textDecoder } = require('./text-endec')()\nconst { BufferFormat, ViewFormat, UTF8Format } = require('./formats')\n\n/** @type {<T>(v: T) => v} */\nconst identity = (v) => v\n\n/**\n * @type {typeof import('./encodings').utf8}\n */\nexports.utf8 = new UTF8Format({\n encode: function (data) {\n // On node 16.9.1 buffer.toString() is 5x faster than TextDecoder\n return Buffer.isBuffer(data)\n ? data.toString('utf8')\n : ArrayBuffer.isView(data)\n ? textDecoder.decode(data)\n : String(data)\n },\n decode: identity,\n name: 'utf8',\n createViewTranscoder () {\n return new ViewFormat({\n encode: function (data) {\n return ArrayBuffer.isView(data) ? data : textEncoder.encode(data)\n },\n decode: function (data) {\n return textDecoder.decode(data)\n },\n name: `${this.name}+view`\n })\n },\n createBufferTranscoder () {\n return new BufferFormat({\n encode: function (data) {\n return Buffer.isBuffer(data)\n ? data\n : ArrayBuffer.isView(data)\n ? Buffer.from(data.buffer, data.byteOffset, data.byteLength)\n : Buffer.from(String(data), 'utf8')\n },\n decode: function (data) {\n return data.toString('utf8')\n },\n name: `${this.name}+buffer`\n })\n }\n})\n\n/**\n * @type {typeof import('./encodings').json}\n */\nexports.json = new UTF8Format({\n encode: JSON.stringify,\n decode: JSON.parse,\n name: 'json'\n})\n\n/**\n * @type {typeof import('./encodings').buffer}\n */\nexports.buffer = new BufferFormat({\n encode: function (data) {\n return Buffer.isBuffer(data)\n ? data\n : ArrayBuffer.isView(data)\n ? Buffer.from(data.buffer, data.byteOffset, data.byteLength)\n : Buffer.from(String(data), 'utf8')\n },\n decode: identity,\n name: 'buffer',\n createViewTranscoder () {\n return new ViewFormat({\n encode: function (data) {\n return ArrayBuffer.isView(data) ? data : Buffer.from(String(data), 'utf8')\n },\n decode: function (data) {\n return Buffer.from(data.buffer, data.byteOffset, data.byteLength)\n },\n name: `${this.name}+view`\n })\n }\n})\n\n/**\n * @type {typeof import('./encodings').view}\n */\nexports.view = new ViewFormat({\n encode: function (data) {\n return ArrayBuffer.isView(data) ? data : textEncoder.encode(data)\n },\n decode: identity,\n name: 'view',\n createBufferTranscoder () {\n return new BufferFormat({\n encode: function (data) {\n return Buffer.isBuffer(data)\n ? data\n : ArrayBuffer.isView(data)\n ? Buffer.from(data.buffer, data.byteOffset, data.byteLength)\n : Buffer.from(String(data), 'utf8')\n },\n decode: identity,\n name: `${this.name}+buffer`\n })\n }\n})\n\n/**\n * @type {typeof import('./encodings').hex}\n */\nexports.hex = new BufferFormat({\n encode: function (data) {\n return Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'hex')\n },\n decode: function (buffer) {\n return buffer.toString('hex')\n },\n name: 'hex'\n})\n\n/**\n * @type {typeof import('./encodings').base64}\n */\nexports.base64 = new BufferFormat({\n encode: function (data) {\n return Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'base64')\n },\n decode: function (buffer) {\n return buffer.toString('base64')\n },\n name: 'base64'\n})\n", "'use strict'\n\nconst ModuleError = require('module-error')\nconst encodings = require('./lib/encodings')\nconst { Encoding } = require('./lib/encoding')\nconst { BufferFormat, ViewFormat, UTF8Format } = require('./lib/formats')\n\nconst kFormats = Symbol('formats')\nconst kEncodings = Symbol('encodings')\nconst validFormats = new Set(['buffer', 'view', 'utf8'])\n\n/** @template T */\nclass Transcoder {\n /**\n * @param {Array<'buffer'|'view'|'utf8'>} formats\n */\n constructor (formats) {\n if (!Array.isArray(formats)) {\n throw new TypeError(\"The first argument 'formats' must be an array\")\n } else if (!formats.every(f => validFormats.has(f))) {\n // Note: we only only support aliases in key- and valueEncoding options (where we already did)\n throw new TypeError(\"Format must be one of 'buffer', 'view', 'utf8'\")\n }\n\n /** @type {Map<string|MixedEncoding<any, any, any>, Encoding<any, any, any>>} */\n this[kEncodings] = new Map()\n this[kFormats] = new Set(formats)\n\n // Register encodings (done early in order to populate encodings())\n for (const k in encodings) {\n try {\n this.encoding(k)\n } catch (err) {\n /* istanbul ignore if: assertion */\n if (err.code !== 'LEVEL_ENCODING_NOT_SUPPORTED') throw err\n }\n }\n }\n\n /**\n * @returns {Array<Encoding<any,T,any>>}\n */\n encodings () {\n return Array.from(new Set(this[kEncodings].values()))\n }\n\n /**\n * @param {string|MixedEncoding<any, any, any>} encoding\n * @returns {Encoding<any, T, any>}\n */\n encoding (encoding) {\n let resolved = this[kEncodings].get(encoding)\n\n if (resolved === undefined) {\n if (typeof encoding === 'string' && encoding !== '') {\n resolved = lookup[encoding]\n\n if (!resolved) {\n throw new ModuleError(`Encoding '${encoding}' is not found`, {\n code: 'LEVEL_ENCODING_NOT_FOUND'\n })\n }\n } else if (typeof encoding !== 'object' || encoding === null) {\n throw new TypeError(\"First argument 'encoding' must be a string or object\")\n } else {\n resolved = from(encoding)\n }\n\n const { name, format } = resolved\n\n if (!this[kFormats].has(format)) {\n if (this[kFormats].has('view')) {\n resolved = resolved.createViewTranscoder()\n } else if (this[kFormats].has('buffer')) {\n resolved = resolved.createBufferTranscoder()\n } else if (this[kFormats].has('utf8')) {\n resolved = resolved.createUTF8Transcoder()\n } else {\n throw new ModuleError(`Encoding '${name}' cannot be transcoded`, {\n code: 'LEVEL_ENCODING_NOT_SUPPORTED'\n })\n }\n }\n\n for (const k of [encoding, name, resolved.name, resolved.commonName]) {\n this[kEncodings].set(k, resolved)\n }\n }\n\n return resolved\n }\n}\n\nexports.Transcoder = Transcoder\n\n/**\n * @param {MixedEncoding<any, any, any>} options\n * @returns {Encoding<any, any, any>}\n */\nfunction from (options) {\n if (options instanceof Encoding) {\n return options\n }\n\n // Loosely typed for ecosystem compatibility\n const maybeType = 'type' in options && typeof options.type === 'string' ? options.type : undefined\n const name = options.name || maybeType || `anonymous-${anonymousCount++}`\n\n switch (detectFormat(options)) {\n case 'view': return new ViewFormat({ ...options, name })\n case 'utf8': return new UTF8Format({ ...options, name })\n case 'buffer': return new BufferFormat({ ...options, name })\n default: {\n throw new TypeError(\"Format must be one of 'buffer', 'view', 'utf8'\")\n }\n }\n}\n\n/**\n * If format is not provided, fallback to detecting `level-codec`\n * or `multiformats` encodings, else assume a format of buffer.\n * @param {MixedEncoding<any, any, any>} options\n * @returns {string}\n */\nfunction detectFormat (options) {\n if ('format' in options && options.format !== undefined) {\n return options.format\n } else if ('buffer' in options && typeof options.buffer === 'boolean') {\n return options.buffer ? 'buffer' : 'utf8' // level-codec\n } else if ('code' in options && Number.isInteger(options.code)) {\n return 'view' // multiformats\n } else {\n return 'buffer'\n }\n}\n\n/**\n * @typedef {import('./lib/encoding').MixedEncoding<TIn,TFormat,TOut>} MixedEncoding\n * @template TIn, TFormat, TOut\n */\n\n/**\n * @type {Object.<string, Encoding<any, any, any>>}\n */\nconst aliases = {\n binary: encodings.buffer,\n 'utf-8': encodings.utf8\n}\n\n/**\n * @type {Object.<string, Encoding<any, any, any>>}\n */\nconst lookup = {\n ...encodings,\n ...aliases\n}\n\nlet anonymousCount = 0\n", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar R = typeof Reflect === 'object' ? Reflect : null\nvar ReflectApply = R && typeof R.apply === 'function'\n ? R.apply\n : function ReflectApply(target, receiver, args) {\n return Function.prototype.apply.call(target, receiver, args);\n }\n\nvar ReflectOwnKeys\nif (R && typeof R.ownKeys === 'function') {\n ReflectOwnKeys = R.ownKeys\n} else if (Object.getOwnPropertySymbols) {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target)\n .concat(Object.getOwnPropertySymbols(target));\n };\n} else {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target);\n };\n}\n\nfunction ProcessEmitWarning(warning) {\n if (console && console.warn) console.warn(warning);\n}\n\nvar NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {\n return value !== value;\n}\n\nfunction EventEmitter() {\n EventEmitter.init.call(this);\n}\nmodule.exports = EventEmitter;\nmodule.exports.once = once;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._eventsCount = 0;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nvar defaultMaxListeners = 10;\n\nfunction checkListener(listener) {\n if (typeof listener !== 'function') {\n throw new TypeError('The \"listener\" argument must be of type Function. Received type ' + typeof listener);\n }\n}\n\nObject.defineProperty(EventEmitter, 'defaultMaxListeners', {\n enumerable: true,\n get: function() {\n return defaultMaxListeners;\n },\n set: function(arg) {\n if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {\n throw new RangeError('The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received ' + arg + '.');\n }\n defaultMaxListeners = arg;\n }\n});\n\nEventEmitter.init = function() {\n\n if (this._events === undefined ||\n this._events === Object.getPrototypeOf(this)._events) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n }\n\n this._maxListeners = this._maxListeners || undefined;\n};\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {\n if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {\n throw new RangeError('The value of \"n\" is out of range. It must be a non-negative number. Received ' + n + '.');\n }\n this._maxListeners = n;\n return this;\n};\n\nfunction _getMaxListeners(that) {\n if (that._maxListeners === undefined)\n return EventEmitter.defaultMaxListeners;\n return that._maxListeners;\n}\n\nEventEmitter.prototype.getMaxListeners = function getMaxListeners() {\n return _getMaxListeners(this);\n};\n\nEventEmitter.prototype.emit = function emit(type) {\n var args = [];\n for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);\n var doError = (type === 'error');\n\n var events = this._events;\n if (events !== undefined)\n doError = (doError && events.error === undefined);\n else if (!doError)\n return false;\n\n // If there is no 'error' event listener then throw.\n if (doError) {\n var er;\n if (args.length > 0)\n er = args[0];\n if (er instanceof Error) {\n // Note: The comments on the `throw` lines are intentional, they show\n // up in Node's output if this results in an unhandled exception.\n throw er; // Unhandled 'error' event\n }\n // At least give some kind of context to the user\n var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));\n err.context = er;\n throw err; // Unhandled 'error' event\n }\n\n var handler = events[type];\n\n if (handler === undefined)\n return false;\n\n if (typeof handler === 'function') {\n ReflectApply(handler, this, args);\n } else {\n var len = handler.length;\n var listeners = arrayClone(handler, len);\n for (var i = 0; i < len; ++i)\n ReflectApply(listeners[i], this, args);\n }\n\n return true;\n};\n\nfunction _addListener(target, type, listener, prepend) {\n var m;\n var events;\n var existing;\n\n checkListener(listener);\n\n events = target._events;\n if (events === undefined) {\n events = target._events = Object.create(null);\n target._eventsCount = 0;\n } else {\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (events.newListener !== undefined) {\n target.emit('newListener', type,\n listener.listener ? listener.listener : listener);\n\n // Re-assign `events` because a newListener handler could have caused the\n // this._events to be assigned to a new object\n events = target._events;\n }\n existing = events[type];\n }\n\n if (existing === undefined) {\n // Optimize the case of one listener. Don't need the extra array object.\n existing = events[type] = listener;\n ++target._eventsCount;\n } else {\n if (typeof existing === 'function') {\n // Adding the second element, need to change to array.\n existing = events[type] =\n prepend ? [listener, existing] : [existing, listener];\n // If we've already got an array, just append.\n } else if (prepend) {\n existing.unshift(listener);\n } else {\n existing.push(listener);\n }\n\n // Check for listener leak\n m = _getMaxListeners(target);\n if (m > 0 && existing.length > m && !existing.warned) {\n existing.warned = true;\n // No error code for this since it is a Warning\n // eslint-disable-next-line no-restricted-syntax\n var w = new Error('Possible EventEmitter memory leak detected. ' +\n existing.length + ' ' + String(type) + ' listeners ' +\n 'added. Use emitter.setMaxListeners() to ' +\n 'increase limit');\n w.name = 'MaxListenersExceededWarning';\n w.emitter = target;\n w.type = type;\n w.count = existing.length;\n ProcessEmitWarning(w);\n }\n }\n\n return target;\n}\n\nEventEmitter.prototype.addListener = function addListener(type, listener) {\n return _addListener(this, type, listener, false);\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.prependListener =\n function prependListener(type, listener) {\n return _addListener(this, type, listener, true);\n };\n\nfunction onceWrapper() {\n if (!this.fired) {\n this.target.removeListener(this.type, this.wrapFn);\n this.fired = true;\n if (arguments.length === 0)\n return this.listener.call(this.target);\n return this.listener.apply(this.target, arguments);\n }\n}\n\nfunction _onceWrap(target, type, listener) {\n var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };\n var wrapped = onceWrapper.bind(state);\n wrapped.listener = listener;\n state.wrapFn = wrapped;\n return wrapped;\n}\n\nEventEmitter.prototype.once = function once(type, listener) {\n checkListener(listener);\n this.on(type, _onceWrap(this, type, listener));\n return this;\n};\n\nEventEmitter.prototype.prependOnceListener =\n function prependOnceListener(type, listener) {\n checkListener(listener);\n this.prependListener(type, _onceWrap(this, type, listener));\n return this;\n };\n\n// Emits a 'removeListener' event if and only if the listener was removed.\nEventEmitter.prototype.removeListener =\n function removeListener(type, listener) {\n var list, events, position, i, originalListener;\n\n checkListener(listener);\n\n events = this._events;\n if (events === undefined)\n return this;\n\n list = events[type];\n if (list === undefined)\n return this;\n\n if (list === listener || list.listener === listener) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else {\n delete events[type];\n if (events.removeListener)\n this.emit('removeListener', type, list.listener || listener);\n }\n } else if (typeof list !== 'function') {\n position = -1;\n\n for (i = list.length - 1; i >= 0; i--) {\n if (list[i] === listener || list[i].listener === listener) {\n originalListener = list[i].listener;\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (position === 0)\n list.shift();\n else {\n spliceOne(list, position);\n }\n\n if (list.length === 1)\n events[type] = list[0];\n\n if (events.removeListener !== undefined)\n this.emit('removeListener', type, originalListener || listener);\n }\n\n return this;\n };\n\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\n\nEventEmitter.prototype.removeAllListeners =\n function removeAllListeners(type) {\n var listeners, events, i;\n\n events = this._events;\n if (events === undefined)\n return this;\n\n // not listening for removeListener, no need to emit\n if (events.removeListener === undefined) {\n if (arguments.length === 0) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n } else if (events[type] !== undefined) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else\n delete events[type];\n }\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n var keys = Object.keys(events);\n var key;\n for (i = 0; i < keys.length; ++i) {\n key = keys[i];\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = Object.create(null);\n this._eventsCount = 0;\n return this;\n }\n\n listeners = events[type];\n\n if (typeof listeners === 'function') {\n this.removeListener(type, listeners);\n } else if (listeners !== undefined) {\n // LIFO order\n for (i = listeners.length - 1; i >= 0; i--) {\n this.removeListener(type, listeners[i]);\n }\n }\n\n return this;\n };\n\nfunction _listeners(target, type, unwrap) {\n var events = target._events;\n\n if (events === undefined)\n return [];\n\n var evlistener = events[type];\n if (evlistener === undefined)\n return [];\n\n if (typeof evlistener === 'function')\n return unwrap ? [evlistener.listener || evlistener] : [evlistener];\n\n return unwrap ?\n unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);\n}\n\nEventEmitter.prototype.listeners = function listeners(type) {\n return _listeners(this, type, true);\n};\n\nEventEmitter.prototype.rawListeners = function rawListeners(type) {\n return _listeners(this, type, false);\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n if (typeof emitter.listenerCount === 'function') {\n return emitter.listenerCount(type);\n } else {\n return listenerCount.call(emitter, type);\n }\n};\n\nEventEmitter.prototype.listenerCount = listenerCount;\nfunction listenerCount(type) {\n var events = this._events;\n\n if (events !== undefined) {\n var evlistener = events[type];\n\n if (typeof evlistener === 'function') {\n return 1;\n } else if (evlistener !== undefined) {\n return evlistener.length;\n }\n }\n\n return 0;\n}\n\nEventEmitter.prototype.eventNames = function eventNames() {\n return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];\n};\n\nfunction arrayClone(arr, n) {\n var copy = new Array(n);\n for (var i = 0; i < n; ++i)\n copy[i] = arr[i];\n return copy;\n}\n\nfunction spliceOne(list, index) {\n for (; index + 1 < list.length; index++)\n list[index] = list[index + 1];\n list.pop();\n}\n\nfunction unwrapListeners(arr) {\n var ret = new Array(arr.length);\n for (var i = 0; i < ret.length; ++i) {\n ret[i] = arr[i].listener || arr[i];\n }\n return ret;\n}\n\nfunction once(emitter, name) {\n return new Promise(function (resolve, reject) {\n function errorListener(err) {\n emitter.removeListener(name, resolver);\n reject(err);\n }\n\n function resolver() {\n if (typeof emitter.removeListener === 'function') {\n emitter.removeListener('error', errorListener);\n }\n resolve([].slice.call(arguments));\n };\n\n eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });\n if (name !== 'error') {\n addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });\n }\n });\n}\n\nfunction addErrorHandlerIfEventEmitter(emitter, handler, flags) {\n if (typeof emitter.on === 'function') {\n eventTargetAgnosticAddListener(emitter, 'error', handler, flags);\n }\n}\n\nfunction eventTargetAgnosticAddListener(emitter, name, listener, flags) {\n if (typeof emitter.on === 'function') {\n if (flags.once) {\n emitter.once(name, listener);\n } else {\n emitter.on(name, listener);\n }\n } else if (typeof emitter.addEventListener === 'function') {\n // EventTarget does not have `error` event semantics like Node\n // EventEmitters, we do not listen for `error` events here.\n emitter.addEventListener(name, function wrapListener(arg) {\n // IE does not have builtin `{ once: true }` support so we\n // have to do it manually.\n if (flags.once) {\n emitter.removeEventListener(name, wrapListener);\n }\n listener(arg);\n });\n } else {\n throw new TypeError('The \"emitter\" argument must be of type EventEmitter. Received type ' + typeof emitter);\n }\n}\n", "module.exports = typeof queueMicrotask === 'function' ? queueMicrotask : (fn) => Promise.resolve().then(fn)\n", "'use strict'\n\nvar nextTick = require('./next-tick')\n\nexports.fromCallback = function (callback, symbol) {\n if (callback === undefined) {\n var promise = new Promise(function (resolve, reject) {\n callback = function (err, res) {\n if (err) reject(err)\n else resolve(res)\n }\n })\n\n callback[symbol !== undefined ? symbol : 'promise'] = promise\n } else if (typeof callback !== 'function') {\n throw new TypeError('Callback must be a function')\n }\n\n return callback\n}\n\nexports.fromPromise = function (promise, callback) {\n if (callback === undefined) return promise\n\n promise\n .then(function (res) { nextTick(() => callback(null, res)) })\n .catch(function (err) { nextTick(() => callback(err)) })\n}\n", "'use strict'\n\nexports.getCallback = function (options, callback) {\n return typeof options === 'function' ? options : callback\n}\n\nexports.getOptions = function (options, def) {\n if (typeof options === 'object' && options !== null) {\n return options\n }\n\n if (def !== undefined) {\n return def\n }\n\n return {}\n}\n", "'use strict'\n\nconst { fromCallback } = require('catering')\nconst ModuleError = require('module-error')\nconst { getOptions, getCallback } = require('./lib/common')\n\nconst kPromise = Symbol('promise')\nconst kCallback = Symbol('callback')\nconst kWorking = Symbol('working')\nconst kHandleOne = Symbol('handleOne')\nconst kHandleMany = Symbol('handleMany')\nconst kAutoClose = Symbol('autoClose')\nconst kFinishWork = Symbol('finishWork')\nconst kReturnMany = Symbol('returnMany')\nconst kClosing = Symbol('closing')\nconst kHandleClose = Symbol('handleClose')\nconst kClosed = Symbol('closed')\nconst kCloseCallbacks = Symbol('closeCallbacks')\nconst kKeyEncoding = Symbol('keyEncoding')\nconst kValueEncoding = Symbol('valueEncoding')\nconst kAbortOnClose = Symbol('abortOnClose')\nconst kLegacy = Symbol('legacy')\nconst kKeys = Symbol('keys')\nconst kValues = Symbol('values')\nconst kLimit = Symbol('limit')\nconst kCount = Symbol('count')\n\nconst emptyOptions = Object.freeze({})\nconst noop = () => {}\nlet warnedEnd = false\n\n// This class is an internal utility for common functionality between AbstractIterator,\n// AbstractKeyIterator and AbstractValueIterator. It's not exported.\nclass CommonIterator {\n constructor (db, options, legacy) {\n if (typeof db !== 'object' || db === null) {\n const hint = db === null ? 'null' : typeof db\n throw new TypeError(`The first argument must be an abstract-level database, received ${hint}`)\n }\n\n if (typeof options !== 'object' || options === null) {\n throw new TypeError('The second argument must be an options object')\n }\n\n this[kClosed] = false\n this[kCloseCallbacks] = []\n this[kWorking] = false\n this[kClosing] = false\n this[kAutoClose] = false\n this[kCallback] = null\n this[kHandleOne] = this[kHandleOne].bind(this)\n this[kHandleMany] = this[kHandleMany].bind(this)\n this[kHandleClose] = this[kHandleClose].bind(this)\n this[kKeyEncoding] = options[kKeyEncoding]\n this[kValueEncoding] = options[kValueEncoding]\n this[kLegacy] = legacy\n this[kLimit] = Number.isInteger(options.limit) && options.limit >= 0 ? options.limit : Infinity\n this[kCount] = 0\n\n // Undocumented option to abort pending work on close(). Used by the\n // many-level module as a temporary solution to a blocked close().\n // TODO (next major): consider making this the default behavior. Native\n // implementations should have their own logic to safely close iterators.\n this[kAbortOnClose] = !!options.abortOnClose\n\n this.db = db\n this.db.attachResource(this)\n this.nextTick = db.nextTick\n }\n\n get count () {\n return this[kCount]\n }\n\n get limit () {\n return this[kLimit]\n }\n\n next (callback) {\n let promise\n\n if (callback === undefined) {\n promise = new Promise((resolve, reject) => {\n callback = (err, key, value) => {\n if (err) reject(err)\n else if (!this[kLegacy]) resolve(key)\n else if (key === undefined && value === undefined) resolve()\n else resolve([key, value])\n }\n })\n } else if (typeof callback !== 'function') {\n throw new TypeError('Callback must be a function')\n }\n\n if (this[kClosing]) {\n this.nextTick(callback, new ModuleError('Iterator is not open: cannot call next() after close()', {\n code: 'LEVEL_ITERATOR_NOT_OPEN'\n }))\n } else if (this[kWorking]) {\n this.nextTick(callback, new ModuleError('Iterator is busy: cannot call next() until previous call has completed', {\n code: 'LEVEL_ITERATOR_BUSY'\n }))\n } else {\n this[kWorking] = true\n this[kCallback] = callback\n\n if (this[kCount] >= this[kLimit]) this.nextTick(this[kHandleOne], null)\n else this._next(this[kHandleOne])\n }\n\n return promise\n }\n\n _next (callback) {\n this.nextTick(callback)\n }\n\n nextv (size, options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n options = getOptions(options, emptyOptions)\n\n if (!Number.isInteger(size)) {\n this.nextTick(callback, new TypeError(\"The first argument 'size' must be an integer\"))\n return callback[kPromise]\n }\n\n if (this[kClosing]) {\n this.nextTick(callback, new ModuleError('Iterator is not open: cannot call nextv() after close()', {\n code: 'LEVEL_ITERATOR_NOT_OPEN'\n }))\n } else if (this[kWorking]) {\n this.nextTick(callback, new ModuleError('Iterator is busy: cannot call nextv() until previous call has completed', {\n code: 'LEVEL_ITERATOR_BUSY'\n }))\n } else {\n if (size < 1) size = 1\n if (this[kLimit] < Infinity) size = Math.min(size, this[kLimit] - this[kCount])\n\n this[kWorking] = true\n this[kCallback] = callback\n\n if (size <= 0) this.nextTick(this[kHandleMany], null, [])\n else this._nextv(size, options, this[kHandleMany])\n }\n\n return callback[kPromise]\n }\n\n _nextv (size, options, callback) {\n const acc = []\n const onnext = (err, key, value) => {\n if (err) {\n return callback(err)\n } else if (this[kLegacy] ? key === undefined && value === undefined : key === undefined) {\n return callback(null, acc)\n }\n\n acc.push(this[kLegacy] ? [key, value] : key)\n\n if (acc.length === size) {\n callback(null, acc)\n } else {\n this._next(onnext)\n }\n }\n\n this._next(onnext)\n }\n\n all (options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n options = getOptions(options, emptyOptions)\n\n if (this[kClosing]) {\n this.nextTick(callback, new ModuleError('Iterator is not open: cannot call all() after close()', {\n code: 'LEVEL_ITERATOR_NOT_OPEN'\n }))\n } else if (this[kWorking]) {\n this.nextTick(callback, new ModuleError('Iterator is busy: cannot call all() until previous call has completed', {\n code: 'LEVEL_ITERATOR_BUSY'\n }))\n } else {\n this[kWorking] = true\n this[kCallback] = callback\n this[kAutoClose] = true\n\n if (this[kCount] >= this[kLimit]) this.nextTick(this[kHandleMany], null, [])\n else this._all(options, this[kHandleMany])\n }\n\n return callback[kPromise]\n }\n\n _all (options, callback) {\n // Must count here because we're directly calling _nextv()\n let count = this[kCount]\n const acc = []\n\n const nextv = () => {\n // Not configurable, because implementations should optimize _all().\n const size = this[kLimit] < Infinity ? Math.min(1e3, this[kLimit] - count) : 1e3\n\n if (size <= 0) {\n this.nextTick(callback, null, acc)\n } else {\n this._nextv(size, emptyOptions, onnextv)\n }\n }\n\n const onnextv = (err, items) => {\n if (err) {\n callback(err)\n } else if (items.length === 0) {\n callback(null, acc)\n } else {\n acc.push.apply(acc, items)\n count += items.length\n nextv()\n }\n }\n\n nextv()\n }\n\n [kFinishWork] () {\n const cb = this[kCallback]\n\n // Callback will be null if work was aborted on close\n if (this[kAbortOnClose] && cb === null) return noop\n\n this[kWorking] = false\n this[kCallback] = null\n\n if (this[kClosing]) this._close(this[kHandleClose])\n\n return cb\n }\n\n [kReturnMany] (cb, err, items) {\n if (this[kAutoClose]) {\n this.close(cb.bind(null, err, items))\n } else {\n cb(err, items)\n }\n }\n\n seek (target, options) {\n options = getOptions(options, emptyOptions)\n\n if (this[kClosing]) {\n // Don't throw here, to be kind to implementations that wrap\n // another db and don't necessarily control when the db is closed\n } else if (this[kWorking]) {\n throw new ModuleError('Iterator is busy: cannot call seek() until next() has completed', {\n code: 'LEVEL_ITERATOR_BUSY'\n })\n } else {\n const keyEncoding = this.db.keyEncoding(options.keyEncoding || this[kKeyEncoding])\n const keyFormat = keyEncoding.format\n\n if (options.keyEncoding !== keyFormat) {\n options = { ...options, keyEncoding: keyFormat }\n }\n\n const mapped = this.db.prefixKey(keyEncoding.encode(target), keyFormat)\n this._seek(mapped, options)\n }\n }\n\n _seek (target, options) {\n throw new ModuleError('Iterator does not support seek()', {\n code: 'LEVEL_NOT_SUPPORTED'\n })\n }\n\n close (callback) {\n callback = fromCallback(callback, kPromise)\n\n if (this[kClosed]) {\n this.nextTick(callback)\n } else if (this[kClosing]) {\n this[kCloseCallbacks].push(callback)\n } else {\n this[kClosing] = true\n this[kCloseCallbacks].push(callback)\n\n if (!this[kWorking]) {\n this._close(this[kHandleClose])\n } else if (this[kAbortOnClose]) {\n // Don't wait for work to finish. Subsequently ignore the result.\n const cb = this[kFinishWork]()\n\n cb(new ModuleError('Aborted on iterator close()', {\n code: 'LEVEL_ITERATOR_NOT_OPEN'\n }))\n }\n }\n\n return callback[kPromise]\n }\n\n _close (callback) {\n this.nextTick(callback)\n }\n\n [kHandleClose] () {\n this[kClosed] = true\n this.db.detachResource(this)\n\n const callbacks = this[kCloseCallbacks]\n this[kCloseCallbacks] = []\n\n for (const cb of callbacks) {\n cb()\n }\n }\n\n async * [Symbol.asyncIterator] () {\n try {\n let item\n\n while ((item = (await this.next())) !== undefined) {\n yield item\n }\n } finally {\n if (!this[kClosed]) await this.close()\n }\n }\n}\n\n// For backwards compatibility this class is not (yet) called AbstractEntryIterator.\nclass AbstractIterator extends CommonIterator {\n constructor (db, options) {\n super(db, options, true)\n this[kKeys] = options.keys !== false\n this[kValues] = options.values !== false\n }\n\n [kHandleOne] (err, key, value) {\n const cb = this[kFinishWork]()\n if (err) return cb(err)\n\n try {\n key = this[kKeys] && key !== undefined ? this[kKeyEncoding].decode(key) : undefined\n value = this[kValues] && value !== undefined ? this[kValueEncoding].decode(value) : undefined\n } catch (err) {\n return cb(new IteratorDecodeError('entry', err))\n }\n\n if (!(key === undefined && value === undefined)) {\n this[kCount]++\n }\n\n cb(null, key, value)\n }\n\n [kHandleMany] (err, entries) {\n const cb = this[kFinishWork]()\n if (err) return this[kReturnMany](cb, err)\n\n try {\n for (const entry of entries) {\n const key = entry[0]\n const value = entry[1]\n\n entry[0] = this[kKeys] && key !== undefined ? this[kKeyEncoding].decode(key) : undefined\n entry[1] = this[kValues] && value !== undefined ? this[kValueEncoding].decode(value) : undefined\n }\n } catch (err) {\n return this[kReturnMany](cb, new IteratorDecodeError('entries', err))\n }\n\n this[kCount] += entries.length\n this[kReturnMany](cb, null, entries)\n }\n\n end (callback) {\n if (!warnedEnd && typeof console !== 'undefined') {\n warnedEnd = true\n console.warn(new ModuleError(\n 'The iterator.end() method was renamed to close() and end() is an alias that will be removed in a future version',\n { code: 'LEVEL_LEGACY' }\n ))\n }\n\n return this.close(callback)\n }\n}\n\nclass AbstractKeyIterator extends CommonIterator {\n constructor (db, options) {\n super(db, options, false)\n }\n\n [kHandleOne] (err, key) {\n const cb = this[kFinishWork]()\n if (err) return cb(err)\n\n try {\n key = key !== undefined ? this[kKeyEncoding].decode(key) : undefined\n } catch (err) {\n return cb(new IteratorDecodeError('key', err))\n }\n\n if (key !== undefined) this[kCount]++\n cb(null, key)\n }\n\n [kHandleMany] (err, keys) {\n const cb = this[kFinishWork]()\n if (err) return this[kReturnMany](cb, err)\n\n try {\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n keys[i] = key !== undefined ? this[kKeyEncoding].decode(key) : undefined\n }\n } catch (err) {\n return this[kReturnMany](cb, new IteratorDecodeError('keys', err))\n }\n\n this[kCount] += keys.length\n this[kReturnMany](cb, null, keys)\n }\n}\n\nclass AbstractValueIterator extends CommonIterator {\n constructor (db, options) {\n super(db, options, false)\n }\n\n [kHandleOne] (err, value) {\n const cb = this[kFinishWork]()\n if (err) return cb(err)\n\n try {\n value = value !== undefined ? this[kValueEncoding].decode(value) : undefined\n } catch (err) {\n return cb(new IteratorDecodeError('value', err))\n }\n\n if (value !== undefined) this[kCount]++\n cb(null, value)\n }\n\n [kHandleMany] (err, values) {\n const cb = this[kFinishWork]()\n if (err) return this[kReturnMany](cb, err)\n\n try {\n for (let i = 0; i < values.length; i++) {\n const value = values[i]\n values[i] = value !== undefined ? this[kValueEncoding].decode(value) : undefined\n }\n } catch (err) {\n return this[kReturnMany](cb, new IteratorDecodeError('values', err))\n }\n\n this[kCount] += values.length\n this[kReturnMany](cb, null, values)\n }\n}\n\n// Internal utility, not typed or exported\nclass IteratorDecodeError extends ModuleError {\n constructor (subject, cause) {\n super(`Iterator could not decode ${subject}`, {\n code: 'LEVEL_DECODE_ERROR',\n cause\n })\n }\n}\n\n// To help migrating to abstract-level\nfor (const k of ['_ended property', '_nexting property', '_end method']) {\n Object.defineProperty(AbstractIterator.prototype, k.split(' ')[0], {\n get () { throw new ModuleError(`The ${k} has been removed`, { code: 'LEVEL_LEGACY' }) },\n set () { throw new ModuleError(`The ${k} has been removed`, { code: 'LEVEL_LEGACY' }) }\n })\n}\n\n// Exposed so that AbstractLevel can set these options\nAbstractIterator.keyEncoding = kKeyEncoding\nAbstractIterator.valueEncoding = kValueEncoding\n\nexports.AbstractIterator = AbstractIterator\nexports.AbstractKeyIterator = AbstractKeyIterator\nexports.AbstractValueIterator = AbstractValueIterator\n", "'use strict'\n\nconst { AbstractKeyIterator, AbstractValueIterator } = require('../abstract-iterator')\n\nconst kIterator = Symbol('iterator')\nconst kCallback = Symbol('callback')\nconst kHandleOne = Symbol('handleOne')\nconst kHandleMany = Symbol('handleMany')\n\nclass DefaultKeyIterator extends AbstractKeyIterator {\n constructor (db, options) {\n super(db, options)\n\n this[kIterator] = db.iterator({ ...options, keys: true, values: false })\n this[kHandleOne] = this[kHandleOne].bind(this)\n this[kHandleMany] = this[kHandleMany].bind(this)\n }\n}\n\nclass DefaultValueIterator extends AbstractValueIterator {\n constructor (db, options) {\n super(db, options)\n\n this[kIterator] = db.iterator({ ...options, keys: false, values: true })\n this[kHandleOne] = this[kHandleOne].bind(this)\n this[kHandleMany] = this[kHandleMany].bind(this)\n }\n}\n\nfor (const Iterator of [DefaultKeyIterator, DefaultValueIterator]) {\n const keys = Iterator === DefaultKeyIterator\n const mapEntry = keys ? (entry) => entry[0] : (entry) => entry[1]\n\n Iterator.prototype._next = function (callback) {\n this[kCallback] = callback\n this[kIterator].next(this[kHandleOne])\n }\n\n Iterator.prototype[kHandleOne] = function (err, key, value) {\n const callback = this[kCallback]\n if (err) callback(err)\n else callback(null, keys ? key : value)\n }\n\n Iterator.prototype._nextv = function (size, options, callback) {\n this[kCallback] = callback\n this[kIterator].nextv(size, options, this[kHandleMany])\n }\n\n Iterator.prototype._all = function (options, callback) {\n this[kCallback] = callback\n this[kIterator].all(options, this[kHandleMany])\n }\n\n Iterator.prototype[kHandleMany] = function (err, entries) {\n const callback = this[kCallback]\n if (err) callback(err)\n else callback(null, entries.map(mapEntry))\n }\n\n Iterator.prototype._seek = function (target, options) {\n this[kIterator].seek(target, options)\n }\n\n Iterator.prototype._close = function (callback) {\n this[kIterator].close(callback)\n }\n}\n\n// Internal utilities, should be typed as AbstractKeyIterator and AbstractValueIterator\nexports.DefaultKeyIterator = DefaultKeyIterator\nexports.DefaultValueIterator = DefaultValueIterator\n", "'use strict'\n\nconst { AbstractIterator, AbstractKeyIterator, AbstractValueIterator } = require('../abstract-iterator')\nconst ModuleError = require('module-error')\n\nconst kNut = Symbol('nut')\nconst kUndefer = Symbol('undefer')\nconst kFactory = Symbol('factory')\n\nclass DeferredIterator extends AbstractIterator {\n constructor (db, options) {\n super(db, options)\n\n this[kNut] = null\n this[kFactory] = () => db.iterator(options)\n\n this.db.defer(() => this[kUndefer]())\n }\n}\n\nclass DeferredKeyIterator extends AbstractKeyIterator {\n constructor (db, options) {\n super(db, options)\n\n this[kNut] = null\n this[kFactory] = () => db.keys(options)\n\n this.db.defer(() => this[kUndefer]())\n }\n}\n\nclass DeferredValueIterator extends AbstractValueIterator {\n constructor (db, options) {\n super(db, options)\n\n this[kNut] = null\n this[kFactory] = () => db.values(options)\n\n this.db.defer(() => this[kUndefer]())\n }\n}\n\nfor (const Iterator of [DeferredIterator, DeferredKeyIterator, DeferredValueIterator]) {\n Iterator.prototype[kUndefer] = function () {\n if (this.db.status === 'open') {\n this[kNut] = this[kFactory]()\n }\n }\n\n Iterator.prototype._next = function (callback) {\n if (this[kNut] !== null) {\n this[kNut].next(callback)\n } else if (this.db.status === 'opening') {\n this.db.defer(() => this._next(callback))\n } else {\n this.nextTick(callback, new ModuleError('Iterator is not open: cannot call next() after close()', {\n code: 'LEVEL_ITERATOR_NOT_OPEN'\n }))\n }\n }\n\n Iterator.prototype._nextv = function (size, options, callback) {\n if (this[kNut] !== null) {\n this[kNut].nextv(size, options, callback)\n } else if (this.db.status === 'opening') {\n this.db.defer(() => this._nextv(size, options, callback))\n } else {\n this.nextTick(callback, new ModuleError('Iterator is not open: cannot call nextv() after close()', {\n code: 'LEVEL_ITERATOR_NOT_OPEN'\n }))\n }\n }\n\n Iterator.prototype._all = function (options, callback) {\n if (this[kNut] !== null) {\n this[kNut].all(callback)\n } else if (this.db.status === 'opening') {\n this.db.defer(() => this._all(options, callback))\n } else {\n this.nextTick(callback, new ModuleError('Iterator is not open: cannot call all() after close()', {\n code: 'LEVEL_ITERATOR_NOT_OPEN'\n }))\n }\n }\n\n Iterator.prototype._seek = function (target, options) {\n if (this[kNut] !== null) {\n // TODO: explain why we need _seek() rather than seek() here\n this[kNut]._seek(target, options)\n } else if (this.db.status === 'opening') {\n this.db.defer(() => this._seek(target, options))\n }\n }\n\n Iterator.prototype._close = function (callback) {\n if (this[kNut] !== null) {\n this[kNut].close(callback)\n } else if (this.db.status === 'opening') {\n this.db.defer(() => this._close(callback))\n } else {\n this.nextTick(callback)\n }\n }\n}\n\nexports.DeferredIterator = DeferredIterator\nexports.DeferredKeyIterator = DeferredKeyIterator\nexports.DeferredValueIterator = DeferredValueIterator\n", "'use strict'\n\nconst { fromCallback } = require('catering')\nconst ModuleError = require('module-error')\nconst { getCallback, getOptions } = require('./lib/common')\n\nconst kPromise = Symbol('promise')\nconst kStatus = Symbol('status')\nconst kOperations = Symbol('operations')\nconst kFinishClose = Symbol('finishClose')\nconst kCloseCallbacks = Symbol('closeCallbacks')\n\nclass AbstractChainedBatch {\n constructor (db) {\n if (typeof db !== 'object' || db === null) {\n const hint = db === null ? 'null' : typeof db\n throw new TypeError(`The first argument must be an abstract-level database, received ${hint}`)\n }\n\n this[kOperations] = []\n this[kCloseCallbacks] = []\n this[kStatus] = 'open'\n this[kFinishClose] = this[kFinishClose].bind(this)\n\n this.db = db\n this.db.attachResource(this)\n this.nextTick = db.nextTick\n }\n\n get length () {\n return this[kOperations].length\n }\n\n put (key, value, options) {\n if (this[kStatus] !== 'open') {\n throw new ModuleError('Batch is not open: cannot call put() after write() or close()', {\n code: 'LEVEL_BATCH_NOT_OPEN'\n })\n }\n\n const err = this.db._checkKey(key) || this.db._checkValue(value)\n if (err) throw err\n\n const db = options && options.sublevel != null ? options.sublevel : this.db\n const original = options\n const keyEncoding = db.keyEncoding(options && options.keyEncoding)\n const valueEncoding = db.valueEncoding(options && options.valueEncoding)\n const keyFormat = keyEncoding.format\n\n // Forward encoding options\n options = { ...options, keyEncoding: keyFormat, valueEncoding: valueEncoding.format }\n\n // Prevent double prefixing\n if (db !== this.db) {\n options.sublevel = null\n }\n\n const mappedKey = db.prefixKey(keyEncoding.encode(key), keyFormat)\n const mappedValue = valueEncoding.encode(value)\n\n this._put(mappedKey, mappedValue, options)\n this[kOperations].push({ ...original, type: 'put', key, value })\n\n return this\n }\n\n _put (key, value, options) {}\n\n del (key, options) {\n if (this[kStatus] !== 'open') {\n throw new ModuleError('Batch is not open: cannot call del() after write() or close()', {\n code: 'LEVEL_BATCH_NOT_OPEN'\n })\n }\n\n const err = this.db._checkKey(key)\n if (err) throw err\n\n const db = options && options.sublevel != null ? options.sublevel : this.db\n const original = options\n const keyEncoding = db.keyEncoding(options && options.keyEncoding)\n const keyFormat = keyEncoding.format\n\n // Forward encoding options\n options = { ...options, keyEncoding: keyFormat }\n\n // Prevent double prefixing\n if (db !== this.db) {\n options.sublevel = null\n }\n\n this._del(db.prefixKey(keyEncoding.encode(key), keyFormat), options)\n this[kOperations].push({ ...original, type: 'del', key })\n\n return this\n }\n\n _del (key, options) {}\n\n clear () {\n if (this[kStatus] !== 'open') {\n throw new ModuleError('Batch is not open: cannot call clear() after write() or close()', {\n code: 'LEVEL_BATCH_NOT_OPEN'\n })\n }\n\n this._clear()\n this[kOperations] = []\n\n return this\n }\n\n _clear () {}\n\n write (options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n options = getOptions(options)\n\n if (this[kStatus] !== 'open') {\n this.nextTick(callback, new ModuleError('Batch is not open: cannot call write() after write() or close()', {\n code: 'LEVEL_BATCH_NOT_OPEN'\n }))\n } else if (this.length === 0) {\n this.close(callback)\n } else {\n this[kStatus] = 'writing'\n this._write(options, (err) => {\n this[kStatus] = 'closing'\n this[kCloseCallbacks].push(() => callback(err))\n\n // Emit after setting 'closing' status, because event may trigger a\n // db close which in turn triggers (idempotently) closing this batch.\n if (!err) this.db.emit('batch', this[kOperations])\n\n this._close(this[kFinishClose])\n })\n }\n\n return callback[kPromise]\n }\n\n _write (options, callback) {}\n\n close (callback) {\n callback = fromCallback(callback, kPromise)\n\n if (this[kStatus] === 'closing') {\n this[kCloseCallbacks].push(callback)\n } else if (this[kStatus] === 'closed') {\n this.nextTick(callback)\n } else {\n this[kCloseCallbacks].push(callback)\n\n if (this[kStatus] !== 'writing') {\n this[kStatus] = 'closing'\n this._close(this[kFinishClose])\n }\n }\n\n return callback[kPromise]\n }\n\n _close (callback) {\n this.nextTick(callback)\n }\n\n [kFinishClose] () {\n this[kStatus] = 'closed'\n this.db.detachResource(this)\n\n const callbacks = this[kCloseCallbacks]\n this[kCloseCallbacks] = []\n\n for (const cb of callbacks) {\n cb()\n }\n }\n}\n\nexports.AbstractChainedBatch = AbstractChainedBatch\n", "'use strict'\n\nconst { AbstractChainedBatch } = require('../abstract-chained-batch')\nconst ModuleError = require('module-error')\nconst kEncoded = Symbol('encoded')\n\n// Functional default for chained batch, with support of deferred open\nclass DefaultChainedBatch extends AbstractChainedBatch {\n constructor (db) {\n super(db)\n this[kEncoded] = []\n }\n\n _put (key, value, options) {\n this[kEncoded].push({ ...options, type: 'put', key, value })\n }\n\n _del (key, options) {\n this[kEncoded].push({ ...options, type: 'del', key })\n }\n\n _clear () {\n this[kEncoded] = []\n }\n\n // Assumes this[kEncoded] cannot change after write()\n _write (options, callback) {\n if (this.db.status === 'opening') {\n this.db.defer(() => this._write(options, callback))\n } else if (this.db.status === 'open') {\n if (this[kEncoded].length === 0) this.nextTick(callback)\n else this.db._batch(this[kEncoded], options, callback)\n } else {\n this.nextTick(callback, new ModuleError('Batch is not open: cannot call write() after write() or close()', {\n code: 'LEVEL_BATCH_NOT_OPEN'\n }))\n }\n }\n}\n\nexports.DefaultChainedBatch = DefaultChainedBatch\n", "'use strict'\n\nconst ModuleError = require('module-error')\nconst hasOwnProperty = Object.prototype.hasOwnProperty\nconst rangeOptions = new Set(['lt', 'lte', 'gt', 'gte'])\n\nmodule.exports = function (options, keyEncoding) {\n const result = {}\n\n for (const k in options) {\n if (!hasOwnProperty.call(options, k)) continue\n if (k === 'keyEncoding' || k === 'valueEncoding') continue\n\n if (k === 'start' || k === 'end') {\n throw new ModuleError(`The legacy range option '${k}' has been removed`, {\n code: 'LEVEL_LEGACY'\n })\n } else if (k === 'encoding') {\n // To help migrating to abstract-level\n throw new ModuleError(\"The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead\", {\n code: 'LEVEL_LEGACY'\n })\n }\n\n if (rangeOptions.has(k)) {\n // Note that we don't reject nullish and empty options here. While\n // those types are invalid as keys, they are valid as range options.\n result[k] = keyEncoding.encode(options[k])\n } else {\n result[k] = options[k]\n }\n }\n\n result.reverse = !!result.reverse\n result.limit = Number.isInteger(result.limit) && result.limit >= 0 ? result.limit : -1\n\n return result\n}\n", "/*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */\nlet promise\n\nmodule.exports = typeof queueMicrotask === 'function'\n ? queueMicrotask.bind(typeof window !== 'undefined' ? window : global)\n // reuse resolved promise, and allocate it lazily\n : cb => (promise || (promise = Promise.resolve()))\n .then(cb)\n .catch(err => setTimeout(() => { throw err }, 0))\n", "'use strict'\n\nconst queueMicrotask = require('queue-microtask')\n\nmodule.exports = function (fn, ...args) {\n if (args.length === 0) {\n queueMicrotask(fn)\n } else {\n queueMicrotask(() => fn(...args))\n }\n}\n", "'use strict'\n\nconst { AbstractIterator, AbstractKeyIterator, AbstractValueIterator } = require('../abstract-iterator')\n\nconst kUnfix = Symbol('unfix')\nconst kIterator = Symbol('iterator')\nconst kHandleOne = Symbol('handleOne')\nconst kHandleMany = Symbol('handleMany')\nconst kCallback = Symbol('callback')\n\n// TODO: unfix natively if db supports it\nclass AbstractSublevelIterator extends AbstractIterator {\n constructor (db, options, iterator, unfix) {\n super(db, options)\n\n this[kIterator] = iterator\n this[kUnfix] = unfix\n this[kHandleOne] = this[kHandleOne].bind(this)\n this[kHandleMany] = this[kHandleMany].bind(this)\n this[kCallback] = null\n }\n\n [kHandleOne] (err, key, value) {\n const callback = this[kCallback]\n if (err) return callback(err)\n if (key !== undefined) key = this[kUnfix](key)\n callback(err, key, value)\n }\n\n [kHandleMany] (err, entries) {\n const callback = this[kCallback]\n if (err) return callback(err)\n\n for (const entry of entries) {\n const key = entry[0]\n if (key !== undefined) entry[0] = this[kUnfix](key)\n }\n\n callback(err, entries)\n }\n}\n\nclass AbstractSublevelKeyIterator extends AbstractKeyIterator {\n constructor (db, options, iterator, unfix) {\n super(db, options)\n\n this[kIterator] = iterator\n this[kUnfix] = unfix\n this[kHandleOne] = this[kHandleOne].bind(this)\n this[kHandleMany] = this[kHandleMany].bind(this)\n this[kCallback] = null\n }\n\n [kHandleOne] (err, key) {\n const callback = this[kCallback]\n if (err) return callback(err)\n if (key !== undefined) key = this[kUnfix](key)\n callback(err, key)\n }\n\n [kHandleMany] (err, keys) {\n const callback = this[kCallback]\n if (err) return callback(err)\n\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n if (key !== undefined) keys[i] = this[kUnfix](key)\n }\n\n callback(err, keys)\n }\n}\n\nclass AbstractSublevelValueIterator extends AbstractValueIterator {\n constructor (db, options, iterator) {\n super(db, options)\n this[kIterator] = iterator\n }\n}\n\nfor (const Iterator of [AbstractSublevelIterator, AbstractSublevelKeyIterator]) {\n Iterator.prototype._next = function (callback) {\n this[kCallback] = callback\n this[kIterator].next(this[kHandleOne])\n }\n\n Iterator.prototype._nextv = function (size, options, callback) {\n this[kCallback] = callback\n this[kIterator].nextv(size, options, this[kHandleMany])\n }\n\n Iterator.prototype._all = function (options, callback) {\n this[kCallback] = callback\n this[kIterator].all(options, this[kHandleMany])\n }\n}\n\nfor (const Iterator of [AbstractSublevelValueIterator]) {\n Iterator.prototype._next = function (callback) {\n this[kIterator].next(callback)\n }\n\n Iterator.prototype._nextv = function (size, options, callback) {\n this[kIterator].nextv(size, options, callback)\n }\n\n Iterator.prototype._all = function (options, callback) {\n this[kIterator].all(options, callback)\n }\n}\n\nfor (const Iterator of [AbstractSublevelIterator, AbstractSublevelKeyIterator, AbstractSublevelValueIterator]) {\n Iterator.prototype._seek = function (target, options) {\n this[kIterator].seek(target, options)\n }\n\n Iterator.prototype._close = function (callback) {\n this[kIterator].close(callback)\n }\n}\n\nexports.AbstractSublevelIterator = AbstractSublevelIterator\nexports.AbstractSublevelKeyIterator = AbstractSublevelKeyIterator\nexports.AbstractSublevelValueIterator = AbstractSublevelValueIterator\n", "'use strict'\n\nconst ModuleError = require('module-error')\nconst { Buffer } = require('buffer') || {}\nconst {\n AbstractSublevelIterator,\n AbstractSublevelKeyIterator,\n AbstractSublevelValueIterator\n} = require('./abstract-sublevel-iterator')\n\nconst kPrefix = Symbol('prefix')\nconst kUpperBound = Symbol('upperBound')\nconst kPrefixRange = Symbol('prefixRange')\nconst kParent = Symbol('parent')\nconst kUnfix = Symbol('unfix')\n\nconst textEncoder = new TextEncoder()\nconst defaults = { separator: '!' }\n\n// Wrapped to avoid circular dependency\nmodule.exports = function ({ AbstractLevel }) {\n class AbstractSublevel extends AbstractLevel {\n static defaults (options) {\n // To help migrating from subleveldown to abstract-level\n if (typeof options === 'string') {\n throw new ModuleError('The subleveldown string shorthand for { separator } has been removed', {\n code: 'LEVEL_LEGACY'\n })\n } else if (options && options.open) {\n throw new ModuleError('The subleveldown open option has been removed', {\n code: 'LEVEL_LEGACY'\n })\n }\n\n if (options == null) {\n return defaults\n } else if (!options.separator) {\n return { ...options, separator: '!' }\n } else {\n return options\n }\n }\n\n // TODO: add autoClose option, which if true, does parent.attachResource(this)\n constructor (db, name, options) {\n // Don't forward AbstractSublevel options to AbstractLevel\n const { separator, manifest, ...forward } = AbstractSublevel.defaults(options)\n name = trim(name, separator)\n\n // Reserve one character between separator and name to give us an upper bound\n const reserved = separator.charCodeAt(0) + 1\n const parent = db[kParent] || db\n\n // Keys should sort like ['!a!', '!a!!a!', '!a\"', '!aa!', '!b!'].\n // Use ASCII for consistent length between string, Buffer and Uint8Array\n if (!textEncoder.encode(name).every(x => x > reserved && x < 127)) {\n throw new ModuleError(`Prefix must use bytes > ${reserved} < ${127}`, {\n code: 'LEVEL_INVALID_PREFIX'\n })\n }\n\n super(mergeManifests(parent, manifest), forward)\n\n const prefix = (db.prefix || '') + separator + name + separator\n const upperBound = prefix.slice(0, -1) + String.fromCharCode(reserved)\n\n this[kParent] = parent\n this[kPrefix] = new MultiFormat(prefix)\n this[kUpperBound] = new MultiFormat(upperBound)\n this[kUnfix] = new Unfixer()\n\n this.nextTick = parent.nextTick\n }\n\n prefixKey (key, keyFormat) {\n if (keyFormat === 'utf8') {\n return this[kPrefix].utf8 + key\n } else if (key.byteLength === 0) {\n // Fast path for empty key (no copy)\n return this[kPrefix][keyFormat]\n } else if (keyFormat === 'view') {\n const view = this[kPrefix].view\n const result = new Uint8Array(view.byteLength + key.byteLength)\n\n result.set(view, 0)\n result.set(key, view.byteLength)\n\n return result\n } else {\n const buffer = this[kPrefix].buffer\n return Buffer.concat([buffer, key], buffer.byteLength + key.byteLength)\n }\n }\n\n // Not exposed for now.\n [kPrefixRange] (range, keyFormat) {\n if (range.gte !== undefined) {\n range.gte = this.prefixKey(range.gte, keyFormat)\n } else if (range.gt !== undefined) {\n range.gt = this.prefixKey(range.gt, keyFormat)\n } else {\n range.gte = this[kPrefix][keyFormat]\n }\n\n if (range.lte !== undefined) {\n range.lte = this.prefixKey(range.lte, keyFormat)\n } else if (range.lt !== undefined) {\n range.lt = this.prefixKey(range.lt, keyFormat)\n } else {\n range.lte = this[kUpperBound][keyFormat]\n }\n }\n\n get prefix () {\n return this[kPrefix].utf8\n }\n\n get db () {\n return this[kParent]\n }\n\n _open (options, callback) {\n // The parent db must open itself or be (re)opened by the user because\n // a sublevel should not initiate state changes on the rest of the db.\n this[kParent].open({ passive: true }, callback)\n }\n\n _put (key, value, options, callback) {\n this[kParent].put(key, value, options, callback)\n }\n\n _get (key, options, callback) {\n this[kParent].get(key, options, callback)\n }\n\n _getMany (keys, options, callback) {\n this[kParent].getMany(keys, options, callback)\n }\n\n _del (key, options, callback) {\n this[kParent].del(key, options, callback)\n }\n\n _batch (operations, options, callback) {\n this[kParent].batch(operations, options, callback)\n }\n\n _clear (options, callback) {\n // TODO (refactor): move to AbstractLevel\n this[kPrefixRange](options, options.keyEncoding)\n this[kParent].clear(options, callback)\n }\n\n _iterator (options) {\n // TODO (refactor): move to AbstractLevel\n this[kPrefixRange](options, options.keyEncoding)\n const iterator = this[kParent].iterator(options)\n const unfix = this[kUnfix].get(this[kPrefix].utf8.length, options.keyEncoding)\n return new AbstractSublevelIterator(this, options, iterator, unfix)\n }\n\n _keys (options) {\n this[kPrefixRange](options, options.keyEncoding)\n const iterator = this[kParent].keys(options)\n const unfix = this[kUnfix].get(this[kPrefix].utf8.length, options.keyEncoding)\n return new AbstractSublevelKeyIterator(this, options, iterator, unfix)\n }\n\n _values (options) {\n this[kPrefixRange](options, options.keyEncoding)\n const iterator = this[kParent].values(options)\n return new AbstractSublevelValueIterator(this, options, iterator)\n }\n }\n\n return { AbstractSublevel }\n}\n\nconst mergeManifests = function (parent, manifest) {\n return {\n // Inherit manifest of parent db\n ...parent.supports,\n\n // Disable unsupported features\n createIfMissing: false,\n errorIfExists: false,\n\n // Unset additional events because we're not forwarding them\n events: {},\n\n // Unset additional methods (like approximateSize) which we can't support here unless\n // the AbstractSublevel class is overridden by an implementation of `abstract-level`.\n additionalMethods: {},\n\n // Inherit manifest of custom AbstractSublevel subclass. Such a class is not\n // allowed to override encodings.\n ...manifest,\n\n encodings: {\n utf8: supportsEncoding(parent, 'utf8'),\n buffer: supportsEncoding(parent, 'buffer'),\n view: supportsEncoding(parent, 'view')\n }\n }\n}\n\nconst supportsEncoding = function (parent, encoding) {\n // Prefer a non-transcoded encoding for optimal performance\n return parent.supports.encodings[encoding]\n ? parent.keyEncoding(encoding).name === encoding\n : false\n}\n\nclass MultiFormat {\n constructor (key) {\n this.utf8 = key\n this.view = textEncoder.encode(key)\n this.buffer = Buffer ? Buffer.from(this.view.buffer, 0, this.view.byteLength) : {}\n }\n}\n\nclass Unfixer {\n constructor () {\n this.cache = new Map()\n }\n\n get (prefixLength, keyFormat) {\n let unfix = this.cache.get(keyFormat)\n\n if (unfix === undefined) {\n if (keyFormat === 'view') {\n unfix = function (prefixLength, key) {\n // Avoid Uint8Array#slice() because it copies\n return key.subarray(prefixLength)\n }.bind(null, prefixLength)\n } else {\n unfix = function (prefixLength, key) {\n // Avoid Buffer#subarray() because it's slow\n return key.slice(prefixLength)\n }.bind(null, prefixLength)\n }\n\n this.cache.set(keyFormat, unfix)\n }\n\n return unfix\n }\n}\n\nconst trim = function (str, char) {\n let start = 0\n let end = str.length\n\n while (start < end && str[start] === char) start++\n while (end > start && str[end - 1] === char) end--\n\n return str.slice(start, end)\n}\n", "'use strict'\n\nconst { supports } = require('level-supports')\nconst { Transcoder } = require('level-transcoder')\nconst { EventEmitter } = require('events')\nconst { fromCallback } = require('catering')\nconst ModuleError = require('module-error')\nconst { AbstractIterator } = require('./abstract-iterator')\nconst { DefaultKeyIterator, DefaultValueIterator } = require('./lib/default-kv-iterator')\nconst { DeferredIterator, DeferredKeyIterator, DeferredValueIterator } = require('./lib/deferred-iterator')\nconst { DefaultChainedBatch } = require('./lib/default-chained-batch')\nconst { getCallback, getOptions } = require('./lib/common')\nconst rangeOptions = require('./lib/range-options')\n\nconst kPromise = Symbol('promise')\nconst kLanded = Symbol('landed')\nconst kResources = Symbol('resources')\nconst kCloseResources = Symbol('closeResources')\nconst kOperations = Symbol('operations')\nconst kUndefer = Symbol('undefer')\nconst kDeferOpen = Symbol('deferOpen')\nconst kOptions = Symbol('options')\nconst kStatus = Symbol('status')\nconst kDefaultOptions = Symbol('defaultOptions')\nconst kTranscoder = Symbol('transcoder')\nconst kKeyEncoding = Symbol('keyEncoding')\nconst kValueEncoding = Symbol('valueEncoding')\nconst noop = () => {}\n\nclass AbstractLevel extends EventEmitter {\n constructor (manifest, options) {\n super()\n\n if (typeof manifest !== 'object' || manifest === null) {\n throw new TypeError(\"The first argument 'manifest' must be an object\")\n }\n\n options = getOptions(options)\n const { keyEncoding, valueEncoding, passive, ...forward } = options\n\n this[kResources] = new Set()\n this[kOperations] = []\n this[kDeferOpen] = true\n this[kOptions] = forward\n this[kStatus] = 'opening'\n\n this.supports = supports(manifest, {\n status: true,\n promises: true,\n clear: true,\n getMany: true,\n deferredOpen: true,\n\n // TODO (next major): add seek\n snapshots: manifest.snapshots !== false,\n permanence: manifest.permanence !== false,\n\n // TODO: remove from level-supports because it's always supported\n keyIterator: true,\n valueIterator: true,\n iteratorNextv: true,\n iteratorAll: true,\n\n encodings: manifest.encodings || {},\n events: Object.assign({}, manifest.events, {\n opening: true,\n open: true,\n closing: true,\n closed: true,\n put: true,\n del: true,\n batch: true,\n clear: true\n })\n })\n\n this[kTranscoder] = new Transcoder(formats(this))\n this[kKeyEncoding] = this[kTranscoder].encoding(keyEncoding || 'utf8')\n this[kValueEncoding] = this[kTranscoder].encoding(valueEncoding || 'utf8')\n\n // Add custom and transcoder encodings to manifest\n for (const encoding of this[kTranscoder].encodings()) {\n if (!this.supports.encodings[encoding.commonName]) {\n this.supports.encodings[encoding.commonName] = true\n }\n }\n\n this[kDefaultOptions] = {\n empty: Object.freeze({}),\n entry: Object.freeze({\n keyEncoding: this[kKeyEncoding].commonName,\n valueEncoding: this[kValueEncoding].commonName\n }),\n key: Object.freeze({\n keyEncoding: this[kKeyEncoding].commonName\n })\n }\n\n // Let subclass finish its constructor\n this.nextTick(() => {\n if (this[kDeferOpen]) {\n this.open({ passive: false }, noop)\n }\n })\n }\n\n get status () {\n return this[kStatus]\n }\n\n keyEncoding (encoding) {\n return this[kTranscoder].encoding(encoding != null ? encoding : this[kKeyEncoding])\n }\n\n valueEncoding (encoding) {\n return this[kTranscoder].encoding(encoding != null ? encoding : this[kValueEncoding])\n }\n\n open (options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n\n options = { ...this[kOptions], ...getOptions(options) }\n\n options.createIfMissing = options.createIfMissing !== false\n options.errorIfExists = !!options.errorIfExists\n\n const maybeOpened = (err) => {\n if (this[kStatus] === 'closing' || this[kStatus] === 'opening') {\n // Wait until pending state changes are done\n this.once(kLanded, err ? () => maybeOpened(err) : maybeOpened)\n } else if (this[kStatus] !== 'open') {\n callback(new ModuleError('Database is not open', {\n code: 'LEVEL_DATABASE_NOT_OPEN',\n cause: err\n }))\n } else {\n callback()\n }\n }\n\n if (options.passive) {\n if (this[kStatus] === 'opening') {\n this.once(kLanded, maybeOpened)\n } else {\n this.nextTick(maybeOpened)\n }\n } else if (this[kStatus] === 'closed' || this[kDeferOpen]) {\n this[kDeferOpen] = false\n this[kStatus] = 'opening'\n this.emit('opening')\n\n this._open(options, (err) => {\n if (err) {\n this[kStatus] = 'closed'\n\n // Resources must be safe to close in any db state\n this[kCloseResources](() => {\n this.emit(kLanded)\n maybeOpened(err)\n })\n\n this[kUndefer]()\n return\n }\n\n this[kStatus] = 'open'\n this[kUndefer]()\n this.emit(kLanded)\n\n // Only emit public event if pending state changes are done\n if (this[kStatus] === 'open') this.emit('open')\n\n // TODO (next major): remove this alias\n if (this[kStatus] === 'open') this.emit('ready')\n\n maybeOpened()\n })\n } else if (this[kStatus] === 'open') {\n this.nextTick(maybeOpened)\n } else {\n this.once(kLanded, () => this.open(options, callback))\n }\n\n return callback[kPromise]\n }\n\n _open (options, callback) {\n this.nextTick(callback)\n }\n\n close (callback) {\n callback = fromCallback(callback, kPromise)\n\n const maybeClosed = (err) => {\n if (this[kStatus] === 'opening' || this[kStatus] === 'closing') {\n // Wait until pending state changes are done\n this.once(kLanded, err ? maybeClosed(err) : maybeClosed)\n } else if (this[kStatus] !== 'closed') {\n callback(new ModuleError('Database is not closed', {\n code: 'LEVEL_DATABASE_NOT_CLOSED',\n cause: err\n }))\n } else {\n callback()\n }\n }\n\n if (this[kStatus] === 'open') {\n this[kStatus] = 'closing'\n this.emit('closing')\n\n const cancel = (err) => {\n this[kStatus] = 'open'\n this[kUndefer]()\n this.emit(kLanded)\n maybeClosed(err)\n }\n\n this[kCloseResources](() => {\n this._close((err) => {\n if (err) return cancel(err)\n\n this[kStatus] = 'closed'\n this[kUndefer]()\n this.emit(kLanded)\n\n // Only emit public event if pending state changes are done\n if (this[kStatus] === 'closed') this.emit('closed')\n\n maybeClosed()\n })\n })\n } else if (this[kStatus] === 'closed') {\n this.nextTick(maybeClosed)\n } else {\n this.once(kLanded, () => this.close(callback))\n }\n\n return callback[kPromise]\n }\n\n [kCloseResources] (callback) {\n if (this[kResources].size === 0) {\n return this.nextTick(callback)\n }\n\n let pending = this[kResources].size\n let sync = true\n\n const next = () => {\n if (--pending === 0) {\n // We don't have tests for generic resources, so dezalgo\n if (sync) this.nextTick(callback)\n else callback()\n }\n }\n\n // In parallel so that all resources know they are closed\n for (const resource of this[kResources]) {\n resource.close(next)\n }\n\n sync = false\n this[kResources].clear()\n }\n\n _close (callback) {\n this.nextTick(callback)\n }\n\n get (key, options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n options = getOptions(options, this[kDefaultOptions].entry)\n\n if (this[kStatus] === 'opening') {\n this.defer(() => this.get(key, options, callback))\n return callback[kPromise]\n }\n\n if (maybeError(this, callback)) {\n return callback[kPromise]\n }\n\n const err = this._checkKey(key)\n\n if (err) {\n this.nextTick(callback, err)\n return callback[kPromise]\n }\n\n const keyEncoding = this.keyEncoding(options.keyEncoding)\n const valueEncoding = this.valueEncoding(options.valueEncoding)\n const keyFormat = keyEncoding.format\n const valueFormat = valueEncoding.format\n\n // Forward encoding options to the underlying store\n if (options.keyEncoding !== keyFormat || options.valueEncoding !== valueFormat) {\n // Avoid spread operator because of https://bugs.chromium.org/p/chromium/issues/detail?id=1204540\n options = Object.assign({}, options, { keyEncoding: keyFormat, valueEncoding: valueFormat })\n }\n\n this._get(this.prefixKey(keyEncoding.encode(key), keyFormat), options, (err, value) => {\n if (err) {\n // Normalize not found error for backwards compatibility with abstract-leveldown and level(up)\n if (err.code === 'LEVEL_NOT_FOUND' || err.notFound || /NotFound/i.test(err)) {\n if (!err.code) err.code = 'LEVEL_NOT_FOUND' // Preferred way going forward\n if (!err.notFound) err.notFound = true // Same as level-errors\n if (!err.status) err.status = 404 // Same as level-errors\n }\n\n return callback(err)\n }\n\n try {\n value = valueEncoding.decode(value)\n } catch (err) {\n return callback(new ModuleError('Could not decode value', {\n code: 'LEVEL_DECODE_ERROR',\n cause: err\n }))\n }\n\n callback(null, value)\n })\n\n return callback[kPromise]\n }\n\n _get (key, options, callback) {\n this.nextTick(callback, new Error('NotFound'))\n }\n\n getMany (keys, options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n options = getOptions(options, this[kDefaultOptions].entry)\n\n if (this[kStatus] === 'opening') {\n this.defer(() => this.getMany(keys, options, callback))\n return callback[kPromise]\n }\n\n if (maybeError(this, callback)) {\n return callback[kPromise]\n }\n\n if (!Array.isArray(keys)) {\n this.nextTick(callback, new TypeError(\"The first argument 'keys' must be an array\"))\n return callback[kPromise]\n }\n\n if (keys.length === 0) {\n this.nextTick(callback, null, [])\n return callback[kPromise]\n }\n\n const keyEncoding = this.keyEncoding(options.keyEncoding)\n const valueEncoding = this.valueEncoding(options.valueEncoding)\n const keyFormat = keyEncoding.format\n const valueFormat = valueEncoding.format\n\n // Forward encoding options\n if (options.keyEncoding !== keyFormat || options.valueEncoding !== valueFormat) {\n options = Object.assign({}, options, { keyEncoding: keyFormat, valueEncoding: valueFormat })\n }\n\n const mappedKeys = new Array(keys.length)\n\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n const err = this._checkKey(key)\n\n if (err) {\n this.nextTick(callback, err)\n return callback[kPromise]\n }\n\n mappedKeys[i] = this.prefixKey(keyEncoding.encode(key), keyFormat)\n }\n\n this._getMany(mappedKeys, options, (err, values) => {\n if (err) return callback(err)\n\n try {\n for (let i = 0; i < values.length; i++) {\n if (values[i] !== undefined) {\n values[i] = valueEncoding.decode(values[i])\n }\n }\n } catch (err) {\n return callback(new ModuleError(`Could not decode one or more of ${values.length} value(s)`, {\n code: 'LEVEL_DECODE_ERROR',\n cause: err\n }))\n }\n\n callback(null, values)\n })\n\n return callback[kPromise]\n }\n\n _getMany (keys, options, callback) {\n this.nextTick(callback, null, new Array(keys.length).fill(undefined))\n }\n\n put (key, value, options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n options = getOptions(options, this[kDefaultOptions].entry)\n\n if (this[kStatus] === 'opening') {\n this.defer(() => this.put(key, value, options, callback))\n return callback[kPromise]\n }\n\n if (maybeError(this, callback)) {\n return callback[kPromise]\n }\n\n const err = this._checkKey(key) || this._checkValue(value)\n\n if (err) {\n this.nextTick(callback, err)\n return callback[kPromise]\n }\n\n const keyEncoding = this.keyEncoding(options.keyEncoding)\n const valueEncoding = this.valueEncoding(options.valueEncoding)\n const keyFormat = keyEncoding.format\n const valueFormat = valueEncoding.format\n\n // Forward encoding options\n if (options.keyEncoding !== keyFormat || options.valueEncoding !== valueFormat) {\n options = Object.assign({}, options, { keyEncoding: keyFormat, valueEncoding: valueFormat })\n }\n\n const mappedKey = this.prefixKey(keyEncoding.encode(key), keyFormat)\n const mappedValue = valueEncoding.encode(value)\n\n this._put(mappedKey, mappedValue, options, (err) => {\n if (err) return callback(err)\n this.emit('put', key, value)\n callback()\n })\n\n return callback[kPromise]\n }\n\n _put (key, value, options, callback) {\n this.nextTick(callback)\n }\n\n del (key, options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n options = getOptions(options, this[kDefaultOptions].key)\n\n if (this[kStatus] === 'opening') {\n this.defer(() => this.del(key, options, callback))\n return callback[kPromise]\n }\n\n if (maybeError(this, callback)) {\n return callback[kPromise]\n }\n\n const err = this._checkKey(key)\n\n if (err) {\n this.nextTick(callback, err)\n return callback[kPromise]\n }\n\n const keyEncoding = this.keyEncoding(options.keyEncoding)\n const keyFormat = keyEncoding.format\n\n // Forward encoding options\n if (options.keyEncoding !== keyFormat) {\n options = Object.assign({}, options, { keyEncoding: keyFormat })\n }\n\n this._del(this.prefixKey(keyEncoding.encode(key), keyFormat), options, (err) => {\n if (err) return callback(err)\n this.emit('del', key)\n callback()\n })\n\n return callback[kPromise]\n }\n\n _del (key, options, callback) {\n this.nextTick(callback)\n }\n\n batch (operations, options, callback) {\n if (!arguments.length) {\n if (this[kStatus] === 'opening') return new DefaultChainedBatch(this)\n if (this[kStatus] !== 'open') {\n throw new ModuleError('Database is not open', {\n code: 'LEVEL_DATABASE_NOT_OPEN'\n })\n }\n return this._chainedBatch()\n }\n\n if (typeof operations === 'function') callback = operations\n else callback = getCallback(options, callback)\n\n callback = fromCallback(callback, kPromise)\n options = getOptions(options, this[kDefaultOptions].empty)\n\n if (this[kStatus] === 'opening') {\n this.defer(() => this.batch(operations, options, callback))\n return callback[kPromise]\n }\n\n if (maybeError(this, callback)) {\n return callback[kPromise]\n }\n\n if (!Array.isArray(operations)) {\n this.nextTick(callback, new TypeError(\"The first argument 'operations' must be an array\"))\n return callback[kPromise]\n }\n\n if (operations.length === 0) {\n this.nextTick(callback)\n return callback[kPromise]\n }\n\n const mapped = new Array(operations.length)\n const { keyEncoding: ke, valueEncoding: ve, ...forward } = options\n\n for (let i = 0; i < operations.length; i++) {\n if (typeof operations[i] !== 'object' || operations[i] === null) {\n this.nextTick(callback, new TypeError('A batch operation must be an object'))\n return callback[kPromise]\n }\n\n const op = Object.assign({}, operations[i])\n\n if (op.type !== 'put' && op.type !== 'del') {\n this.nextTick(callback, new TypeError(\"A batch operation must have a type property that is 'put' or 'del'\"))\n return callback[kPromise]\n }\n\n const err = this._checkKey(op.key)\n\n if (err) {\n this.nextTick(callback, err)\n return callback[kPromise]\n }\n\n const db = op.sublevel != null ? op.sublevel : this\n const keyEncoding = db.keyEncoding(op.keyEncoding || ke)\n const keyFormat = keyEncoding.format\n\n op.key = db.prefixKey(keyEncoding.encode(op.key), keyFormat)\n op.keyEncoding = keyFormat\n\n if (op.type === 'put') {\n const valueErr = this._checkValue(op.value)\n\n if (valueErr) {\n this.nextTick(callback, valueErr)\n return callback[kPromise]\n }\n\n const valueEncoding = db.valueEncoding(op.valueEncoding || ve)\n\n op.value = valueEncoding.encode(op.value)\n op.valueEncoding = valueEncoding.format\n }\n\n // Prevent double prefixing\n if (db !== this) {\n op.sublevel = null\n }\n\n mapped[i] = op\n }\n\n this._batch(mapped, forward, (err) => {\n if (err) return callback(err)\n this.emit('batch', operations)\n callback()\n })\n\n return callback[kPromise]\n }\n\n _batch (operations, options, callback) {\n this.nextTick(callback)\n }\n\n sublevel (name, options) {\n return this._sublevel(name, AbstractSublevel.defaults(options))\n }\n\n _sublevel (name, options) {\n return new AbstractSublevel(this, name, options)\n }\n\n prefixKey (key, keyFormat) {\n return key\n }\n\n clear (options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n options = getOptions(options, this[kDefaultOptions].empty)\n\n if (this[kStatus] === 'opening') {\n this.defer(() => this.clear(options, callback))\n return callback[kPromise]\n }\n\n if (maybeError(this, callback)) {\n return callback[kPromise]\n }\n\n const original = options\n const keyEncoding = this.keyEncoding(options.keyEncoding)\n\n options = rangeOptions(options, keyEncoding)\n options.keyEncoding = keyEncoding.format\n\n if (options.limit === 0) {\n this.nextTick(callback)\n } else {\n this._clear(options, (err) => {\n if (err) return callback(err)\n this.emit('clear', original)\n callback()\n })\n }\n\n return callback[kPromise]\n }\n\n _clear (options, callback) {\n this.nextTick(callback)\n }\n\n iterator (options) {\n const keyEncoding = this.keyEncoding(options && options.keyEncoding)\n const valueEncoding = this.valueEncoding(options && options.valueEncoding)\n\n options = rangeOptions(options, keyEncoding)\n options.keys = options.keys !== false\n options.values = options.values !== false\n\n // We need the original encoding options in AbstractIterator in order to decode data\n options[AbstractIterator.keyEncoding] = keyEncoding\n options[AbstractIterator.valueEncoding] = valueEncoding\n\n // Forward encoding options to private API\n options.keyEncoding = keyEncoding.format\n options.valueEncoding = valueEncoding.format\n\n if (this[kStatus] === 'opening') {\n return new DeferredIterator(this, options)\n } else if (this[kStatus] !== 'open') {\n throw new ModuleError('Database is not open', {\n code: 'LEVEL_DATABASE_NOT_OPEN'\n })\n }\n\n return this._iterator(options)\n }\n\n _iterator (options) {\n return new AbstractIterator(this, options)\n }\n\n keys (options) {\n // Also include valueEncoding (though unused) because we may fallback to _iterator()\n const keyEncoding = this.keyEncoding(options && options.keyEncoding)\n const valueEncoding = this.valueEncoding(options && options.valueEncoding)\n\n options = rangeOptions(options, keyEncoding)\n\n // We need the original encoding options in AbstractKeyIterator in order to decode data\n options[AbstractIterator.keyEncoding] = keyEncoding\n options[AbstractIterator.valueEncoding] = valueEncoding\n\n // Forward encoding options to private API\n options.keyEncoding = keyEncoding.format\n options.valueEncoding = valueEncoding.format\n\n if (this[kStatus] === 'opening') {\n return new DeferredKeyIterator(this, options)\n } else if (this[kStatus] !== 'open') {\n throw new ModuleError('Database is not open', {\n code: 'LEVEL_DATABASE_NOT_OPEN'\n })\n }\n\n return this._keys(options)\n }\n\n _keys (options) {\n return new DefaultKeyIterator(this, options)\n }\n\n values (options) {\n const keyEncoding = this.keyEncoding(options && options.keyEncoding)\n const valueEncoding = this.valueEncoding(options && options.valueEncoding)\n\n options = rangeOptions(options, keyEncoding)\n\n // We need the original encoding options in AbstractValueIterator in order to decode data\n options[AbstractIterator.keyEncoding] = keyEncoding\n options[AbstractIterator.valueEncoding] = valueEncoding\n\n // Forward encoding options to private API\n options.keyEncoding = keyEncoding.format\n options.valueEncoding = valueEncoding.format\n\n if (this[kStatus] === 'opening') {\n return new DeferredValueIterator(this, options)\n } else if (this[kStatus] !== 'open') {\n throw new ModuleError('Database is not open', {\n code: 'LEVEL_DATABASE_NOT_OPEN'\n })\n }\n\n return this._values(options)\n }\n\n _values (options) {\n return new DefaultValueIterator(this, options)\n }\n\n defer (fn) {\n if (typeof fn !== 'function') {\n throw new TypeError('The first argument must be a function')\n }\n\n this[kOperations].push(fn)\n }\n\n [kUndefer] () {\n if (this[kOperations].length === 0) {\n return\n }\n\n const operations = this[kOperations]\n this[kOperations] = []\n\n for (const op of operations) {\n op()\n }\n }\n\n // TODO: docs and types\n attachResource (resource) {\n if (typeof resource !== 'object' || resource === null ||\n typeof resource.close !== 'function') {\n throw new TypeError('The first argument must be a resource object')\n }\n\n this[kResources].add(resource)\n }\n\n // TODO: docs and types\n detachResource (resource) {\n this[kResources].delete(resource)\n }\n\n _chainedBatch () {\n return new DefaultChainedBatch(this)\n }\n\n _checkKey (key) {\n if (key === null || key === undefined) {\n return new ModuleError('Key cannot be null or undefined', {\n code: 'LEVEL_INVALID_KEY'\n })\n }\n }\n\n _checkValue (value) {\n if (value === null || value === undefined) {\n return new ModuleError('Value cannot be null or undefined', {\n code: 'LEVEL_INVALID_VALUE'\n })\n }\n }\n}\n\n// Expose browser-compatible nextTick for dependents\n// TODO: after we drop node 10, also use queueMicrotask in node\nAbstractLevel.prototype.nextTick = require('./lib/next-tick')\n\nconst { AbstractSublevel } = require('./lib/abstract-sublevel')({ AbstractLevel })\n\nexports.AbstractLevel = AbstractLevel\nexports.AbstractSublevel = AbstractSublevel\n\nconst maybeError = function (db, callback) {\n if (db[kStatus] !== 'open') {\n db.nextTick(callback, new ModuleError('Database is not open', {\n code: 'LEVEL_DATABASE_NOT_OPEN'\n }))\n return true\n }\n\n return false\n}\n\nconst formats = function (db) {\n return Object.keys(db.supports.encodings)\n .filter(k => !!db.supports.encodings[k])\n}\n", "'use strict'\n\nexports.AbstractLevel = require('./abstract-level').AbstractLevel\nexports.AbstractSublevel = require('./abstract-level').AbstractSublevel\nexports.AbstractIterator = require('./abstract-iterator').AbstractIterator\nexports.AbstractKeyIterator = require('./abstract-iterator').AbstractKeyIterator\nexports.AbstractValueIterator = require('./abstract-iterator').AbstractValueIterator\nexports.AbstractChainedBatch = require('./abstract-chained-batch').AbstractChainedBatch\n", "/*! run-parallel-limit. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */\nmodule.exports = runParallelLimit\n\nconst queueMicrotask = require('queue-microtask')\n\nfunction runParallelLimit (tasks, limit, cb) {\n if (typeof limit !== 'number') throw new Error('second argument must be a Number')\n let results, len, pending, keys, isErrored\n let isSync = true\n let next\n\n if (Array.isArray(tasks)) {\n results = []\n pending = len = tasks.length\n } else {\n keys = Object.keys(tasks)\n results = {}\n pending = len = keys.length\n }\n\n function done (err) {\n function end () {\n if (cb) cb(err, results)\n cb = null\n }\n if (isSync) queueMicrotask(end)\n else end()\n }\n\n function each (i, err, result) {\n results[i] = result\n if (err) isErrored = true\n if (--pending === 0 || err) {\n done(err)\n } else if (!isErrored && next < len) {\n let key\n if (keys) {\n key = keys[next]\n next += 1\n tasks[key](function (err, result) { each(key, err, result) })\n } else {\n key = next\n next += 1\n tasks[key](function (err, result) { each(key, err, result) })\n }\n }\n }\n\n next = limit\n if (!pending) {\n // empty\n done(null)\n } else if (keys) {\n // object\n keys.some(function (key, i) {\n tasks[key](function (err, result) { each(key, err, result) })\n if (i === limit - 1) return true // early return\n return false\n })\n } else {\n // array\n tasks.some(function (task, i) {\n task(function (err, result) { each(i, err, result) })\n if (i === limit - 1) return true // early return\n return false\n })\n }\n\n isSync = false\n}\n", "/* global IDBKeyRange */\n\n'use strict'\n\nmodule.exports = function createKeyRange (options) {\n const lower = options.gte !== undefined ? options.gte : options.gt !== undefined ? options.gt : undefined\n const upper = options.lte !== undefined ? options.lte : options.lt !== undefined ? options.lt : undefined\n const lowerExclusive = options.gte === undefined\n const upperExclusive = options.lte === undefined\n\n if (lower !== undefined && upper !== undefined) {\n return IDBKeyRange.bound(lower, upper, lowerExclusive, upperExclusive)\n } else if (lower !== undefined) {\n return IDBKeyRange.lowerBound(lower, lowerExclusive)\n } else if (upper !== undefined) {\n return IDBKeyRange.upperBound(upper, upperExclusive)\n } else {\n return null\n }\n}\n", "'use strict'\n\nconst textEncoder = new TextEncoder()\n\nmodule.exports = function (data) {\n if (data instanceof Uint8Array) {\n return data\n } else if (data instanceof ArrayBuffer) {\n return new Uint8Array(data)\n } else {\n // Non-binary data stored with an old version (level-js < 5.0.0)\n return textEncoder.encode(data)\n }\n}\n", "'use strict'\n\nconst { AbstractIterator } = require('abstract-level')\nconst createKeyRange = require('./util/key-range')\nconst deserialize = require('./util/deserialize')\n\nconst kCache = Symbol('cache')\nconst kFinished = Symbol('finished')\nconst kOptions = Symbol('options')\nconst kCurrentOptions = Symbol('currentOptions')\nconst kPosition = Symbol('position')\nconst kLocation = Symbol('location')\nconst kFirst = Symbol('first')\nconst emptyOptions = {}\n\nclass Iterator extends AbstractIterator {\n constructor (db, location, options) {\n super(db, options)\n\n this[kCache] = []\n this[kFinished] = this.limit === 0\n this[kOptions] = options\n this[kCurrentOptions] = { ...options }\n this[kPosition] = undefined\n this[kLocation] = location\n this[kFirst] = true\n }\n\n // Note: if called by _all() then size can be Infinity. This is an internal\n // detail; by design AbstractIterator.nextv() does not support Infinity.\n _nextv (size, options, callback) {\n this[kFirst] = false\n\n if (this[kFinished]) {\n return this.nextTick(callback, null, [])\n } else if (this[kCache].length > 0) {\n // TODO: mixing next and nextv is not covered by test suite\n size = Math.min(size, this[kCache].length)\n return this.nextTick(callback, null, this[kCache].splice(0, size))\n }\n\n // Adjust range by what we already visited\n if (this[kPosition] !== undefined) {\n if (this[kOptions].reverse) {\n this[kCurrentOptions].lt = this[kPosition]\n this[kCurrentOptions].lte = undefined\n } else {\n this[kCurrentOptions].gt = this[kPosition]\n this[kCurrentOptions].gte = undefined\n }\n }\n\n let keyRange\n\n try {\n keyRange = createKeyRange(this[kCurrentOptions])\n } catch (_) {\n // The lower key is greater than the upper key.\n // IndexedDB throws an error, but we'll just return 0 results.\n this[kFinished] = true\n return this.nextTick(callback, null, [])\n }\n\n const transaction = this.db.db.transaction([this[kLocation]], 'readonly')\n const store = transaction.objectStore(this[kLocation])\n const entries = []\n\n if (!this[kOptions].reverse) {\n let keys\n let values\n\n const complete = () => {\n // Wait for both requests to complete\n if (keys === undefined || values === undefined) return\n\n const length = Math.max(keys.length, values.length)\n\n if (length === 0 || size === Infinity) {\n this[kFinished] = true\n } else {\n this[kPosition] = keys[length - 1]\n }\n\n // Resize\n entries.length = length\n\n // Merge keys and values\n for (let i = 0; i < length; i++) {\n const key = keys[i]\n const value = values[i]\n\n entries[i] = [\n this[kOptions].keys && key !== undefined ? deserialize(key) : undefined,\n this[kOptions].values && value !== undefined ? deserialize(value) : undefined\n ]\n }\n\n maybeCommit(transaction)\n }\n\n // If keys were not requested and size is Infinity, we don't have to keep\n // track of position and can thus skip getting keys.\n if (this[kOptions].keys || size < Infinity) {\n store.getAllKeys(keyRange, size < Infinity ? size : undefined).onsuccess = (ev) => {\n keys = ev.target.result\n complete()\n }\n } else {\n keys = []\n this.nextTick(complete)\n }\n\n if (this[kOptions].values) {\n store.getAll(keyRange, size < Infinity ? size : undefined).onsuccess = (ev) => {\n values = ev.target.result\n complete()\n }\n } else {\n values = []\n this.nextTick(complete)\n }\n } else {\n // Can't use getAll() in reverse, so use a slower cursor that yields one item at a time\n // TODO: test if all target browsers support openKeyCursor\n const method = !this[kOptions].values && store.openKeyCursor ? 'openKeyCursor' : 'openCursor'\n\n store[method](keyRange, 'prev').onsuccess = (ev) => {\n const cursor = ev.target.result\n\n if (cursor) {\n const { key, value } = cursor\n this[kPosition] = key\n\n entries.push([\n this[kOptions].keys && key !== undefined ? deserialize(key) : undefined,\n this[kOptions].values && value !== undefined ? deserialize(value) : undefined\n ])\n\n if (entries.length < size) {\n cursor.continue()\n } else {\n maybeCommit(transaction)\n }\n } else {\n this[kFinished] = true\n }\n }\n }\n\n // If an error occurs (on the request), the transaction will abort.\n transaction.onabort = () => {\n callback(transaction.error || new Error('aborted by user'))\n callback = null\n }\n\n transaction.oncomplete = () => {\n callback(null, entries)\n callback = null\n }\n }\n\n _next (callback) {\n if (this[kCache].length > 0) {\n const [key, value] = this[kCache].shift()\n this.nextTick(callback, null, key, value)\n } else if (this[kFinished]) {\n this.nextTick(callback)\n } else {\n let size = Math.min(100, this.limit - this.count)\n\n if (this[kFirst]) {\n // It's common to only want one entry initially or after a seek()\n this[kFirst] = false\n size = 1\n }\n\n this._nextv(size, emptyOptions, (err, entries) => {\n if (err) return callback(err)\n this[kCache] = entries\n this._next(callback)\n })\n }\n }\n\n _all (options, callback) {\n this[kFirst] = false\n\n // TODO: mixing next and all is not covered by test suite\n const cache = this[kCache].splice(0, this[kCache].length)\n const size = this.limit - this.count - cache.length\n\n if (size <= 0) {\n return this.nextTick(callback, null, cache)\n }\n\n this._nextv(size, emptyOptions, (err, entries) => {\n if (err) return callback(err)\n if (cache.length > 0) entries = cache.concat(entries)\n callback(null, entries)\n })\n }\n\n _seek (target, options) {\n this[kFirst] = true\n this[kCache] = []\n this[kFinished] = false\n this[kPosition] = undefined\n\n // TODO: not covered by test suite\n this[kCurrentOptions] = { ...this[kOptions] }\n\n let keyRange\n\n try {\n keyRange = createKeyRange(this[kOptions])\n } catch (_) {\n this[kFinished] = true\n return\n }\n\n if (keyRange !== null && !keyRange.includes(target)) {\n this[kFinished] = true\n } else if (this[kOptions].reverse) {\n this[kCurrentOptions].lte = target\n } else {\n this[kCurrentOptions].gte = target\n }\n }\n}\n\nexports.Iterator = Iterator\n\nfunction maybeCommit (transaction) {\n // Commit (meaning close) now instead of waiting for auto-commit\n if (typeof transaction.commit === 'function') {\n transaction.commit()\n }\n}\n", "'use strict'\n\nmodule.exports = function clear (db, location, keyRange, options, callback) {\n if (options.limit === 0) return db.nextTick(callback)\n\n const transaction = db.db.transaction([location], 'readwrite')\n const store = transaction.objectStore(location)\n let count = 0\n\n transaction.oncomplete = function () {\n callback()\n }\n\n transaction.onabort = function () {\n callback(transaction.error || new Error('aborted by user'))\n }\n\n // A key cursor is faster (skips reading values) but not supported by IE\n // TODO: we no longer support IE. Test others\n const method = store.openKeyCursor ? 'openKeyCursor' : 'openCursor'\n const direction = options.reverse ? 'prev' : 'next'\n\n store[method](keyRange, direction).onsuccess = function (ev) {\n const cursor = ev.target.result\n\n if (cursor) {\n // Wait for a request to complete before continuing, saving CPU.\n store.delete(cursor.key).onsuccess = function () {\n if (options.limit <= 0 || ++count < options.limit) {\n cursor.continue()\n }\n }\n }\n }\n}\n", "/* global indexedDB */\n\n'use strict'\n\nconst { AbstractLevel } = require('abstract-level')\nconst ModuleError = require('module-error')\nconst parallel = require('run-parallel-limit')\nconst { fromCallback } = require('catering')\nconst { Iterator } = require('./iterator')\nconst deserialize = require('./util/deserialize')\nconst clear = require('./util/clear')\nconst createKeyRange = require('./util/key-range')\n\n// Keep as-is for compatibility with existing level-js databases\nconst DEFAULT_PREFIX = 'level-js-'\n\nconst kIDB = Symbol('idb')\nconst kNamePrefix = Symbol('namePrefix')\nconst kLocation = Symbol('location')\nconst kVersion = Symbol('version')\nconst kStore = Symbol('store')\nconst kOnComplete = Symbol('onComplete')\nconst kPromise = Symbol('promise')\n\nclass BrowserLevel extends AbstractLevel {\n constructor (location, options, _) {\n // To help migrating to abstract-level\n if (typeof options === 'function' || typeof _ === 'function') {\n throw new ModuleError('The levelup-style callback argument has been removed', {\n code: 'LEVEL_LEGACY'\n })\n }\n\n const { prefix, version, ...forward } = options || {}\n\n super({\n encodings: { view: true },\n snapshots: false,\n createIfMissing: false,\n errorIfExists: false,\n seek: true\n }, forward)\n\n if (typeof location !== 'string') {\n throw new Error('constructor requires a location string argument')\n }\n\n // TODO (next major): remove default prefix\n this[kLocation] = location\n this[kNamePrefix] = prefix == null ? DEFAULT_PREFIX : prefix\n this[kVersion] = parseInt(version || 1, 10)\n this[kIDB] = null\n }\n\n get location () {\n return this[kLocation]\n }\n\n get namePrefix () {\n return this[kNamePrefix]\n }\n\n get version () {\n return this[kVersion]\n }\n\n // Exposed for backwards compat and unit tests\n get db () {\n return this[kIDB]\n }\n\n get type () {\n return 'browser-level'\n }\n\n _open (options, callback) {\n const req = indexedDB.open(this[kNamePrefix] + this[kLocation], this[kVersion])\n\n req.onerror = function () {\n callback(req.error || new Error('unknown error'))\n }\n\n req.onsuccess = () => {\n this[kIDB] = req.result\n callback()\n }\n\n req.onupgradeneeded = (ev) => {\n const db = ev.target.result\n\n if (!db.objectStoreNames.contains(this[kLocation])) {\n db.createObjectStore(this[kLocation])\n }\n }\n }\n\n [kStore] (mode) {\n const transaction = this[kIDB].transaction([this[kLocation]], mode)\n return transaction.objectStore(this[kLocation])\n }\n\n [kOnComplete] (request, callback) {\n const transaction = request.transaction\n\n // Take advantage of the fact that a non-canceled request error aborts\n // the transaction. I.e. no need to listen for \"request.onerror\".\n transaction.onabort = function () {\n callback(transaction.error || new Error('aborted by user'))\n }\n\n transaction.oncomplete = function () {\n callback(null, request.result)\n }\n }\n\n _get (key, options, callback) {\n const store = this[kStore]('readonly')\n let req\n\n try {\n req = store.get(key)\n } catch (err) {\n return this.nextTick(callback, err)\n }\n\n this[kOnComplete](req, function (err, value) {\n if (err) return callback(err)\n\n if (value === undefined) {\n return callback(new ModuleError('Entry not found', {\n code: 'LEVEL_NOT_FOUND'\n }))\n }\n\n callback(null, deserialize(value))\n })\n }\n\n _getMany (keys, options, callback) {\n const store = this[kStore]('readonly')\n const tasks = keys.map((key) => (next) => {\n let request\n\n try {\n request = store.get(key)\n } catch (err) {\n return next(err)\n }\n\n request.onsuccess = () => {\n const value = request.result\n next(null, value === undefined ? value : deserialize(value))\n }\n\n request.onerror = (ev) => {\n ev.stopPropagation()\n next(request.error)\n }\n })\n\n parallel(tasks, 16, callback)\n }\n\n _del (key, options, callback) {\n const store = this[kStore]('readwrite')\n let req\n\n try {\n req = store.delete(key)\n } catch (err) {\n return this.nextTick(callback, err)\n }\n\n this[kOnComplete](req, callback)\n }\n\n _put (key, value, options, callback) {\n const store = this[kStore]('readwrite')\n let req\n\n try {\n // Will throw a DataError or DataCloneError if the environment\n // does not support serializing the key or value respectively.\n req = store.put(value, key)\n } catch (err) {\n return this.nextTick(callback, err)\n }\n\n this[kOnComplete](req, callback)\n }\n\n // TODO: implement key and value iterators\n _iterator (options) {\n return new Iterator(this, this[kLocation], options)\n }\n\n _batch (operations, options, callback) {\n const store = this[kStore]('readwrite')\n const transaction = store.transaction\n let index = 0\n let error\n\n transaction.onabort = function () {\n callback(error || transaction.error || new Error('aborted by user'))\n }\n\n transaction.oncomplete = function () {\n callback()\n }\n\n // Wait for a request to complete before making the next, saving CPU.\n function loop () {\n const op = operations[index++]\n const key = op.key\n\n let req\n\n try {\n req = op.type === 'del' ? store.delete(key) : store.put(op.value, key)\n } catch (err) {\n error = err\n transaction.abort()\n return\n }\n\n if (index < operations.length) {\n req.onsuccess = loop\n } else if (typeof transaction.commit === 'function') {\n // Commit now instead of waiting for auto-commit\n transaction.commit()\n }\n }\n\n loop()\n }\n\n _clear (options, callback) {\n let keyRange\n let req\n\n try {\n keyRange = createKeyRange(options)\n } catch (e) {\n // The lower key is greater than the upper key.\n // IndexedDB throws an error, but we'll just do nothing.\n return this.nextTick(callback)\n }\n\n if (options.limit >= 0) {\n // IDBObjectStore#delete(range) doesn't have such an option.\n // Fall back to cursor-based implementation.\n return clear(this, this[kLocation], keyRange, options, callback)\n }\n\n try {\n const store = this[kStore]('readwrite')\n req = keyRange ? store.delete(keyRange) : store.clear()\n } catch (err) {\n return this.nextTick(callback, err)\n }\n\n this[kOnComplete](req, callback)\n }\n\n _close (callback) {\n this[kIDB].close()\n this.nextTick(callback)\n }\n}\n\nBrowserLevel.destroy = function (location, prefix, callback) {\n if (typeof prefix === 'function') {\n callback = prefix\n prefix = DEFAULT_PREFIX\n }\n\n callback = fromCallback(callback, kPromise)\n const request = indexedDB.deleteDatabase(prefix + location)\n\n request.onsuccess = function () {\n callback()\n }\n\n request.onerror = function (err) {\n callback(err)\n }\n\n return callback[kPromise]\n}\n\nexports.BrowserLevel = BrowserLevel\n", "exports.Level = require('browser-level').BrowserLevel\n", "export * from './crypto-error.js';\nexport * from './local-key-manager.js';\nexport * from './utils.js';\n\nexport * from './algorithms/aes-ctr.js';\nexport * from './algorithms/aes-gcm.js';\nexport * from './algorithms/crypto-algorithm.js';\nexport * from './algorithms/ecdsa.js';\nexport * from './algorithms/eddsa.js';\nexport * from './algorithms/sha-2.js';\n\nexport * from './jose/jwe.js';\nexport * from './jose/jwk.js';\nexport * from './jose/jws.js';\nexport * from './jose/jwt.js';\nexport * from './jose/utils.js';\n\nexport * from './primitives/aes-ctr.js';\nexport * from './primitives/aes-gcm.js';\nexport * from './primitives/aes-kw.js';\nexport * from './primitives/concat-kdf.js';\nexport * from './primitives/ed25519.js';\nexport * from './primitives/hkdf.js';\nexport * from './primitives/secp256r1.js';\nexport * from './primitives/pbkdf2.js';\nexport * from './primitives/secp256k1.js';\nexport * from './primitives/sha256.js';\nexport * from './primitives/x25519.js';\nexport * from './primitives/xchacha20.js';\nexport * from './primitives/xchacha20-poly1305.js';\n\nexport type * from './types/cipher.js';\nexport type * from './types/crypto-api.js';\nexport type * from './types/hasher.js';\nexport type * from './types/identifier.js';\nexport type * from './types/key-compressor.js';\nexport type * from './types/key-converter.js';\nexport type * from './types/key-deriver.js';\nexport type * from './types/key-generator.js';\nexport type * from './types/key-io.js';\nexport type * from './types/key-wrapper.js';\nexport type * from './types/params-direct.js';\nexport type * from './types/params-enclosed.js';\nexport type * from './types/params-kms.js';\nexport type * from './types/signer.js';", "/**\n * A custom error class for Crypto-related errors.\n */\nexport class CryptoError extends Error {\n /**\n * Constructs an instance of CryptoError, a custom error class for handling Crypto-related errors.\n *\n * @param code - A {@link CryptoErrorCode} representing the specific type of error encountered.\n * @param message - A human-readable description of the error.\n */\n constructor(public code: CryptoErrorCode, message: string) {\n super(message);\n this.name = 'CryptoError';\n\n // Ensures that instanceof works properly, the correct prototype chain when using inheritance,\n // and that V8 stack traces (like Chrome, Edge, and Node.js) are more readable and relevant.\n Object.setPrototypeOf(this, new.target.prototype);\n\n // Captures the stack trace in V8 engines (like Chrome, Edge, and Node.js).\n // In non-V8 environments, the stack trace will still be captured.\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, CryptoError);\n }\n }\n}\n\n/**\n * An enumeration of possible Crypto error codes.\n */\nexport enum CryptoErrorCode {\n /** The supplied algorithm identifier is not supported by the implementation. */\n AlgorithmNotSupported = 'algorithmNotSupported',\n\n /** The encoding operation (either encoding or decoding) failed. */\n EncodingError = 'encodingError',\n\n /** The JWE supplied does not conform to valid syntax. */\n InvalidJwe = 'invalidJwe',\n\n /** The JWK supplied does not conform to valid syntax. */\n InvalidJwk = 'invalidJwk',\n\n /** The requested operation is not supported by the implementation. */\n OperationNotSupported = 'operationNotSupported',\n}\n", "import TTLCache from '@isaacs/ttlcache';\nexport { TTLCache as TtlCache };", "export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) return new Uint8Array(o)\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n", "/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable<number>} source\n */\n function encode (source) {\n // @ts-ignore\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) { return }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch\n }\n /**\n * @param {string | string[]} string\n */\n function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n", "import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder<Base extends string, Prefix extends string> implements MultibaseEncoder<Prefix>, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase<Prefix> {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder<Base extends string, Prefix extends string> implements MultibaseDecoder<Prefix>, UnibaseDecoder<Prefix>, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character')\n }\n this.prefixCodePoint = prefix.codePointAt(0) as number\n this.baseDecode = baseDecode\n }\n\n decode (text: string): Uint8Array {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n }\n return this.baseDecode(text.slice(this.prefix.length))\n } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or<OtherPrefix extends string> (decoder: UnibaseDecoder<OtherPrefix> | ComposedDecoder<OtherPrefix>): ComposedDecoder<Prefix | OtherPrefix> {\n return or(this, decoder)\n }\n}\n\ntype Decoders<Prefix extends string> = Record<Prefix, UnibaseDecoder<Prefix>>\n\nclass ComposedDecoder<Prefix extends string> implements MultibaseDecoder<Prefix>, CombobaseDecoder<Prefix> {\n readonly decoders: Decoders<Prefix>\n\n constructor (decoders: Decoders<Prefix>) {\n this.decoders = decoders\n }\n\n or <OtherPrefix extends string> (decoder: UnibaseDecoder<OtherPrefix> | ComposedDecoder<OtherPrefix>): ComposedDecoder<Prefix | OtherPrefix> {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\n } else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n }\n }\n}\n\nexport function or <L extends string, R extends string> (left: UnibaseDecoder<L> | CombobaseDecoder<L>, right: UnibaseDecoder<R> | CombobaseDecoder<R>): ComposedDecoder<L | R> {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder<L>).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder<R>).prefix]: right })\n } as Decoders<L | R>)\n}\n\nexport class Codec<Base extends string, Prefix extends string> implements MultibaseCodec<Prefix>, MultibaseEncoder<Prefix>, MultibaseDecoder<Prefix>, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder<Base, Prefix>\n readonly decoder: Decoder<Base, Prefix>\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n this.baseDecode = baseDecode\n this.encoder = new Encoder(name, prefix, baseEncode)\n this.decoder = new Decoder(name, prefix, baseDecode)\n }\n\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from <Base extends string, Prefix extends string> ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec<Base, Prefix> {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX <Base extends string, Prefix extends string> ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec<Base, Prefix> {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabet: string, bitsPerChar: number, name: string): Uint8Array {\n // Build the character lookup table:\n const codes: Record<string, number> = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\n // Parse the data:\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n let written = 0 // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]]\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`)\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8\n out[written++] = 0xff & (buffer >> bits)\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i]\n bits += 8\n\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '='\n }\n }\n\n return out\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 <Base extends string, Prefix extends string> ({ name, prefix, bitsPerChar, alphabet }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string }): Codec<Base, Prefix> {\n return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabet, bitsPerChar, name)\n }\n })\n}\n", "import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n", "import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n", "/**\n * Represents an array of a fixed length, preventing modifications to its size.\n *\n * The `FixedLengthArray` utility type transforms a standard array into a variant where\n * methods that could alter the length are omitted. It leverages TypeScript's advanced types,\n * such as conditional types and mapped types, to ensure that the array cannot be resized\n * through methods like `push`, `pop`, `splice`, `shift`, and `unshift`. The utility type\n * maintains all other characteristics of a standard array, including indexing, iteration,\n * and type checking for its elements.\n *\n * Note: The type does not prevent direct assignment to indices, even if it would exceed\n * the original length. However, such actions would lead to TypeScript type errors.\n *\n * @example\n * ```ts\n * // Declare a variable with a type of fixed-length array of three strings.\n * let myFixedLengthArray: FixedLengthArray< [string, string, string]>;\n *\n * // Array declaration tests\n * myFixedLengthArray = [ 'a', 'b', 'c' ]; // OK\n * myFixedLengthArray = [ 'a', 'b', 123 ]; // TYPE ERROR\n * myFixedLengthArray = [ 'a' ]; // LENGTH ERROR\n * myFixedLengthArray = [ 'a', 'b' ]; // LENGTH ERROR\n *\n * // Index assignment tests\n * myFixedLengthArray[1] = 'foo'; // OK\n * myFixedLengthArray[1000] = 'foo'; // INVALID INDEX ERROR\n *\n * // Methods that mutate array length\n * myFixedLengthArray.push('foo'); // MISSING METHOD ERROR\n * myFixedLengthArray.pop(); // MISSING METHOD ERROR\n *\n * // Direct length manipulation\n * myFixedLengthArray.length = 123; // READ-ONLY ERROR\n *\n * // Destructuring\n * let [ a ] = myFixedLengthArray; // OK\n * let [ a, b ] = myFixedLengthArray; // OK\n * let [ a, b, c ] = myFixedLengthArray; // OK\n * let [ a, b, c, d ] = myFixedLengthArray; // INVALID INDEX ERROR\n * ```\n *\n * @template T extends any[] - The array type to be transformed.\n */\nexport type FixedLengthArray<T extends any[]> =\n Pick<T, Exclude<keyof T, ArrayLengthMutationKeys>>\n & {\n /**\n * Custom iterator for the `FixedLengthArray` type.\n *\n * This iterator allows the `FixedLengthArray` to be used in standard iteration\n * contexts, such as `for...of` loops and spread syntax. It ensures that even though\n * the array is of a fixed length with disabled mutation methods, it still retains\n * iterable behavior similar to a regular array.\n *\n * @returns An IterableIterator for the array items.\n */\n [Symbol.iterator]: () => IterableIterator<ArrayItems<T>>\n };\n\n/** Helper types for {@link FixedLengthArray} */\ntype ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' | 'unshift' | number;\ntype ArrayItems<T extends Array<any>> = T extends Array<infer TItems> ? TItems : never;\n\n/**\n * isArrayBufferSlice\n *\n * Checks if the ArrayBufferView represents a slice (subarray or a subview)\n * of an ArrayBuffer.\n *\n * An ArrayBufferView (TypedArray or DataView) can represent a portion of an\n * ArrayBuffer - such a view is said to be a \"slice\" of the original buffer.\n * This can occur when the `subarray` or `slice` method is called on a\n * TypedArray or when a DataView is created with a byteOffset and/or\n * byteLength that doesn't cover the full ArrayBuffer.\n *\n * @param arrayBufferView - The ArrayBufferView to be checked\n * @returns true if the ArrayBufferView represents a slice of an ArrayBuffer; false otherwise.\n */\nexport function isArrayBufferSlice(arrayBufferView: ArrayBufferView): boolean {\n return arrayBufferView.byteOffset !== 0 || arrayBufferView.byteLength !== arrayBufferView.buffer.byteLength;\n}\n\n/**\n * Checks if the given object is an AsyncIterable.\n *\n * An AsyncIterable is an object that implements the AsyncIterable protocol,\n * which means it has a [Symbol.asyncIterator] method. This function checks\n * if the provided object conforms to this protocol by verifying the presence\n * and type of the [Symbol.asyncIterator] method.\n *\n * @param obj - The object to be checked for AsyncIterable conformity.\n * @returns True if the object is an AsyncIterable, false otherwise.\n *\n * @example\n * ```ts\n * // Returns true for a valid AsyncIterable\n * const asyncIterable = {\n * async *[Symbol.asyncIterator]() {\n * yield 1;\n * yield 2;\n * }\n * };\n * console.log(isAsyncIterable(asyncIterable)); // true\n * ```\n *\n * @example\n * ```ts\n * // Returns false for a regular object\n * console.log(isAsyncIterable({ a: 1, b: 2 })); // false\n * ```\n */\nexport function isAsyncIterable(obj: any): obj is AsyncIterable<any> {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n\n return typeof obj[Symbol.asyncIterator] === 'function';\n}\n\n/**\n * isDefined\n *\n * Utility function to check if a variable is neither null nor undefined.\n * This function helps in making TypeScript infer the type of the variable\n * as being defined, excluding `null` and `undefined`.\n *\n * The function uses strict equality (`!==`) for the comparison, ensuring\n * that the variable is not just falsy (like an empty string or zero),\n * but is truly either `null` or `undefined`.\n *\n * @param arg - The variable to be checked\n * @returns true if the variable is neither `null` nor `undefined`\n */\nexport function isDefined<T>(arg: T): arg is Exclude<T, null | undefined> {\n return arg !== null && typeof arg !== 'undefined';\n}\n\n/**\n * Utility type that transforms a type `T` to have only certain keys `K` as required, while the\n * rest remain optional, except for keys specified in `O`, which are omitted entirely.\n *\n * This type is useful when you need a variation of a type where only specific properties are\n * required, and others are either optional or not included at all. It allows for more flexible type\n * definitions based on existing types without the need to redefine them.\n *\n * @template T - The original type to be transformed.\n * @template K - The keys of `T` that should be required.\n * @template O - The keys of `T` that should be omitted from the resulting type (optional).\n *\n * @example\n * ```ts\n * // Given an interface\n * interface Example {\n * requiredProp: string;\n * optionalProp?: number;\n * anotherOptionalProp?: boolean;\n * }\n *\n * // Making 'optionalProp' required and omitting 'anotherOptionalProp'\n * type ModifiedExample = RequireOnly<Example, 'optionalProp', 'anotherOptionalProp'>;\n * // Result: { requiredProp?: string; optionalProp: number; }\n * ```\n */\nexport type RequireOnly<T, K extends keyof T, O extends keyof T = never> = Required<Pick<T, K>> & Omit<Partial<T>, O>;\n\n/**\n * universalTypeOf\n *\n * Why does this function exist?\n *\n * You can typically check if a value is of a particular type, such as\n * Uint8Array or ArrayBuffer, by using the `instanceof` operator. The\n * `instanceof` operator checks the prototype property of a constructor\n * in the object's prototype chain.\n *\n * However, there is a caveat with the `instanceof` check if the value\n * was created from a different JavaScript context (like an iframe or\n * a web worker). In those cases, the `instanceof` check might fail\n * because each context has a different global object, and therefore,\n * different built-in constructor functions.\n *\n * The `typeof` operator provides information about the type of the\n * operand in a less detailed way. For basic data types like number,\n * string, boolean, and undefined, the `typeof` operator works as\n * expected. However, for objects, including arrays and null,\n * it always returns \"object\". For functions, it returns \"function\".\n * So, while `typeof` is good for basic type checking, it doesn't\n * give detailed information about complex data types.\n *\n * Unlike `instanceof` and `typeof`, `Object.prototype.toString.call(value)`\n * can ensure a consistent result across different JavaScript\n * contexts.\n *\n * Credit for inspiration:\n * Angus Croll\n * https://github.com/angus-c\n * https://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/\n */\nexport function universalTypeOf(value: unknown): string {\n // Returns '[Object Type]' string.\n const typeString = Object.prototype.toString.call(value);\n // Returns ['Object', 'Type'] array or null.\n const match = typeString.match(/\\s([a-zA-Z0-9]+)/);\n // Deconstructs the array and gets just the type from index 1.\n const [_, type] = match as RegExpMatchArray;\n\n return type;\n}\n\n/**\n * Utility type to extract the type resolved by a Promise.\n *\n * This type unwraps the type `T` from `Promise<T>` if `T` is a Promise, otherwise returns `T` as\n * is. It's useful in situations where you need to handle the type returned by a promise-based\n * function in a synchronous context, such as defining types for test vectors or handling return\n * types in non-async code blocks.\n *\n * @template T - The type to unwrap from the Promise.\n *\n * @example\n * ```ts\n * // For a Promise type, it extracts the resolved type.\n * type AsyncNumber = Promise<number>;\n * type UnwrappedNumber = UnwrapPromise<AsyncNumber>; // number\n *\n * // For a non-Promise type, it returns the type as is.\n * type StringValue = string;\n * type UnwrappedString = UnwrapPromise<StringValue>; // string\n * ```\n */\nexport type UnwrapPromise<T> = T extends Promise<infer U> ? U : T;", "import type { Multibase } from 'multiformats';\n\nimport { base32z } from 'multiformats/bases/base32';\nimport { base58btc } from 'multiformats/bases/base58';\nimport { base64url } from 'multiformats/bases/base64';\n\nimport { isArrayBufferSlice, isAsyncIterable, universalTypeOf } from './type-utils.js';\n\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\nexport class Convert {\n data: any;\n format: string;\n\n constructor(data: any, format: string) {\n this.data = data;\n this.format = format;\n }\n\n static arrayBuffer(data: ArrayBuffer): Convert {\n return new Convert(data, 'ArrayBuffer');\n }\n\n static asyncIterable(data: AsyncIterable<any>): Convert {\n if (!isAsyncIterable(data)) {\n throw new TypeError('Input must be of type AsyncIterable.');\n }\n return new Convert(data, 'AsyncIterable');\n }\n\n static base32Z(data: string): Convert {\n return new Convert(data, 'Base32Z');\n }\n\n static base58Btc(data: string): Convert {\n return new Convert(data, 'Base58Btc');\n }\n\n static base64Url(data: string): Convert {\n return new Convert(data, 'Base64Url');\n }\n\n /**\n * Reference:\n * The BufferSource type is a TypeScript type that represents an ArrayBuffer\n * or one of the ArrayBufferView types, such a TypedArray (e.g., Uint8Array)\n * or a DataView.\n */\n static bufferSource(data: BufferSource): Convert {\n return new Convert(data, 'BufferSource');\n }\n\n static hex(data: string): Convert {\n if (typeof data !== 'string') {\n throw new TypeError('Hex input must be a string.');\n }\n if (data.length % 2 !== 0) {\n throw new TypeError('Hex input must have an even number of characters.');\n }\n return new Convert(data, 'Hex');\n }\n\n static multibase(data: string): Convert {\n return new Convert(data, 'Multibase');\n }\n\n static object(data: Record<string, any>): Convert {\n return new Convert(data, 'Object');\n }\n\n static string(data: string): Convert {\n return new Convert(data, 'String');\n }\n\n static uint8Array(data: Uint8Array): Convert {\n return new Convert(data, 'Uint8Array');\n }\n\n toArrayBuffer(): ArrayBuffer {\n switch (this.format) {\n\n case 'Base58Btc': {\n return base58btc.baseDecode(this.data).buffer;\n }\n\n case 'Base64Url': {\n return base64url.baseDecode(this.data).buffer;\n }\n\n case 'BufferSource': {\n const dataType = universalTypeOf(this.data);\n if (dataType === 'ArrayBuffer') {\n // Data is already an ArrayBuffer, No conversion is necessary.\n return this.data;\n } else if (ArrayBuffer.isView(this.data)) {\n // Data is a DataView or a different TypedArray (e.g., Uint16Array).\n if (isArrayBufferSlice(this.data)) {\n // Data is a slice of an ArrayBuffer. Return a new ArrayBuffer or ArrayBufferView of the same slice.\n return this.data.buffer.slice(this.data.byteOffset, this.data.byteOffset + this.data.byteLength);\n } else {\n // Data is a whole ArrayBuffer viewed as a different TypedArray or DataView. Return the whole ArrayBuffer.\n return this.data.buffer;\n }\n } else {\n throw new TypeError(`${this.format} value is not of type: ArrayBuffer, DataView, or TypedArray.`);\n }\n }\n\n case 'Hex': {\n return this.toUint8Array().buffer;\n }\n\n case 'String': {\n return this.toUint8Array().buffer;\n }\n\n case 'Uint8Array': {\n return this.data.buffer;\n }\n\n default:\n throw new TypeError(`Conversion from ${this.format} to ArrayBuffer is not supported.`);\n }\n }\n\n async toArrayBufferAsync(): Promise<ArrayBuffer> {\n switch (this.format) {\n case 'AsyncIterable': {\n const blob = await this.toBlobAsync();\n return await blob.arrayBuffer();\n }\n\n default:\n throw new TypeError(`Asynchronous conversion from ${this.format} to ArrayBuffer is not supported.`);\n }\n }\n\n toBase32Z(): string {\n switch (this.format) {\n\n case 'Uint8Array': {\n return base32z.baseEncode(this.data);\n }\n\n default:\n throw new TypeError(`Conversion from ${this.format} to Base64Z is not supported.`);\n }\n }\n\n toBase58Btc(): string {\n switch (this.format) {\n\n case 'ArrayBuffer': {\n const u8a = new Uint8Array(this.data);\n return base58btc.baseEncode(u8a);\n }\n\n case 'Multibase': {\n return this.data.substring(1);\n }\n\n case 'Uint8Array': {\n return base58btc.baseEncode(this.data);\n }\n\n default:\n throw new TypeError(`Conversion from ${this.format} to Base58Btc is not supported.`);\n }\n }\n\n toBase64Url(): string {\n switch (this.format) {\n\n case 'ArrayBuffer': {\n const u8a = new Uint8Array(this.data);\n return base64url.baseEncode(u8a);\n }\n\n case 'BufferSource': {\n const u8a = this.toUint8Array();\n return base64url.baseEncode(u8a);\n }\n\n case 'Object': {\n const string = JSON.stringify(this.data);\n const u8a = textEncoder.encode(string);\n return base64url.baseEncode(u8a);\n }\n\n case 'String': {\n const u8a = textEncoder.encode(this.data);\n return base64url.baseEncode(u8a);\n }\n\n case 'Uint8Array': {\n return base64url.baseEncode(this.data);\n }\n\n default:\n throw new TypeError(`Conversion from ${this.format} to Base64Url is not supported.`);\n }\n }\n\n async toBlobAsync(): Promise<Blob> {\n switch (this.format) {\n case 'AsyncIterable': {\n // Initialize an array to hold the chunks from the AsyncIterable.\n const chunks = [];\n\n // Asynchronously iterate over each chunk in the AsyncIterable.\n for await (const chunk of (this.data as AsyncIterable<any>)) {\n // Append each chunk to the chunks array. These chunks can be of any type, typically binary data or text.\n chunks.push(chunk);\n }\n\n // Create a new Blob from the aggregated chunks.\n // The Blob constructor combines these chunks into a single Blob object.\n const blob = new Blob(chunks);\n\n return blob;\n }\n\n default:\n throw new TypeError(`Asynchronous conversion from ${this.format} to Blob is not supported.`);\n }\n }\n\n toHex(): string {\n // pre-calculating Hex values improves runtime by 6-10x.\n const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));\n\n switch (this.format) {\n\n case 'ArrayBuffer': {\n const u8a = this.toUint8Array();\n return Convert.uint8Array(u8a).toHex();\n }\n\n case 'Base64Url': {\n const u8a = this.toUint8Array();\n return Convert.uint8Array(u8a).toHex();\n }\n\n case 'Uint8Array': {\n let hex = '';\n for (let i = 0; i < this.data.length; i++) {\n hex += hexes[this.data[i]];\n }\n return hex;\n }\n\n default:\n throw new TypeError(`Conversion from ${this.format} to Hex is not supported.`);\n }\n }\n\n toMultibase(): Multibase<any> {\n switch (this.format) {\n case 'Base58Btc': {\n return `z${this.data}`;\n }\n\n default:\n throw new TypeError(`Conversion from ${this.format} to Multibase is not supported.`);\n }\n }\n\n toObject(): object {\n switch (this.format) {\n\n case 'Base64Url': {\n const u8a = base64url.baseDecode(this.data);\n const text = textDecoder.decode(u8a);\n return JSON.parse(text);\n }\n\n case 'String': {\n return JSON.parse(this.data);\n }\n\n case 'Uint8Array': {\n const text = textDecoder.decode(this.data);\n return JSON.parse(text);\n }\n\n default:\n throw new TypeError(`Conversion from ${this.format} to Object is not supported.`);\n }\n }\n\n async toObjectAsync(): Promise<any> {\n switch (this.format) {\n case 'AsyncIterable': {\n // Convert the AsyncIterable to a String.\n const text = await this.toStringAsync();\n\n // Parse the string as JSON. This step assumes that the string represents a valid JSON structure.\n // JSON.parse() will convert the string into a corresponding JavaScript object.\n const json = JSON.parse(text);\n\n // Return the parsed JavaScript object. The type of this object will depend on the structure\n // of the JSON in the stream. It could be an object, array, string, number, etc.\n return json;\n }\n\n default:\n throw new TypeError(`Asynchronous conversion from ${this.format} to Object is not supported.`);\n }\n }\n\n toString(): string {\n switch (this.format) {\n\n case 'ArrayBuffer': {\n return textDecoder.decode(this.data);\n }\n\n case 'Base64Url': {\n const u8a = base64url.baseDecode(this.data);\n return textDecoder.decode(u8a);\n }\n\n case 'Object': {\n return JSON.stringify(this.data);\n }\n\n case 'Uint8Array': {\n return textDecoder.decode(this.data);\n }\n\n default:\n throw new TypeError(`Conversion from ${this.format} to String is not supported.`);\n }\n }\n\n async toStringAsync(): Promise<string> {\n switch (this.format) {\n case 'AsyncIterable': {\n // Initialize an empty string to accumulate the decoded text.\n let str = '';\n\n // Iterate over the chunks from the AsyncIterable.\n for await (const chunk of (this.data as AsyncIterable<any>)) {\n // If the chunk is already a string, concatenate it directly.\n if (typeof chunk === 'string')\n {str += chunk;}\n else\n // If the chunk is a Uint8Array or similar, use the decoder to convert it to a string.\n // The `stream: true` option lets the decoder handle multi-byte characters spanning\n // multiple chunks.\n {str += textDecoder.decode(chunk, { stream: true });}\n }\n\n // Finalize the decoding process to handle any remaining bytes and signal the end of the stream.\n // The `stream: false` option flushes the decoder's internal state.\n str += textDecoder.decode(undefined, { stream: false });\n\n // Return the accumulated string.\n return str;\n }\n\n default:\n throw new TypeError(`Asynchronous conversion from ${this.format} to String is not supported.`);\n }\n }\n\n toUint8Array(): Uint8Array {\n switch (this.format) {\n\n case 'ArrayBuffer': {\n // \u00C7reate Uint8Array as a view on the ArrayBuffer.\n // Note: The Uint8Array shares the same memory as the ArrayBuffer, so this operation is very efficient.\n return new Uint8Array(this.data);\n }\n\n case 'Base32Z': {\n return base32z.baseDecode(this.data);\n }\n\n case 'Base58Btc': {\n return base58btc.baseDecode(this.data);\n }\n\n case 'Base64Url': {\n return base64url.baseDecode(this.data);\n }\n\n case 'BufferSource': {\n const dataType = universalTypeOf(this.data);\n if (dataType === 'Uint8Array') {\n // Data is already a Uint8Array. No conversion is necessary.\n // Note: Uint8Array is a type of BufferSource.\n return this.data;\n } else if (dataType === 'ArrayBuffer') {\n // Data is an ArrayBuffer, create Uint8Array as a view on the ArrayBuffer.\n // Note: The Uint8Array shares the same memory as the ArrayBuffer, so this operation is very efficient.\n return new Uint8Array(this.data);\n } else if (ArrayBuffer.isView(this.data)) {\n // Data is a DataView or a different TypedArray (e.g., Uint16Array).\n return new Uint8Array(this.data.buffer, this.data.byteOffset, this.data.byteLength);\n } else {\n throw new TypeError(`${this.format} value is not of type: ArrayBuffer, DataView, or TypedArray.`);\n }\n }\n\n case 'Hex': {\n const u8a = new Uint8Array(this.data.length / 2);\n for (let i = 0; i < this.data.length; i += 2) {\n const byteValue = parseInt(this.data.substring(i, i + 2), 16);\n if (isNaN(byteValue)) {\n throw new TypeError('Input is not a valid hexadecimal string.');\n }\n u8a[i / 2] = byteValue;\n }\n return u8a;\n }\n\n case 'Object': {\n const string = JSON.stringify(this.data);\n return textEncoder.encode(string);\n }\n\n case 'String': {\n return textEncoder.encode(this.data);\n }\n\n default:\n throw new TypeError(`Conversion from ${this.format} to Uint8Array is not supported.`);\n }\n }\n\n async toUint8ArrayAsync(): Promise<Uint8Array> {\n switch (this.format) {\n case 'AsyncIterable': {\n const arrayBuffer = await this.toArrayBufferAsync();\n return new Uint8Array(arrayBuffer);\n }\n\n default:\n throw new TypeError(`Asynchronous conversion from ${this.format} to Uint8Array is not supported.`);\n }\n }\n}", "/**\n * Web5 logger level.\n */\nexport enum Web5LogLevel {\n Debug = 'debug',\n Silent = 'silent',\n}\n\n/**\n * Web5 logger interface.\n */\nexport interface Web5LoggerInterface {\n\n /**\n * Sets the log verbose level.\n */\n setLogLevel(logLevel: Web5LogLevel): void;\n\n /**\n * Same as `info()`.\n * Logs an informational message.\n */\n log (message: string): void;\n\n /**\n * Logs an informational message.\n */\n info(message: string): void;\n\n /**\n * Logs an error message.\n */\n error(message: string): void;\n}\n\n/**\n * A Web5 logger implementation.\n */\nclass Web5Logger implements Web5LoggerInterface {\n private logLevel: Web5LogLevel = Web5LogLevel.Silent; // Default to silent/no-op log level\n\n setLogLevel(logLevel: Web5LogLevel): void {\n this.logLevel = logLevel;\n }\n\n public log(message: string): void {\n this.info(message);\n }\n\n public info(message: string): void {\n if (this.logLevel === Web5LogLevel.Silent) { return; }\n\n console.info(message);\n }\n\n public error(message: string): void {\n if (this.logLevel === Web5LogLevel.Silent) { return; }\n\n console.error(message);\n }\n}\n\n// Export a singleton logger instance\nexport const logger = new Web5Logger();\n\n// Attach logger to the global window object in browser environment for easy access to the logger instance.\n// e.g. can call `web5logger.setLogLevel('debug');` directly in browser console.\ndeclare global {\n interface Window { web5logger?: Web5Logger }\n}\n\nif (typeof window !== 'undefined') {\n window.web5logger = logger;\n}", "import varint from './vendor/varint.js'\n\nexport function decode (data: Uint8Array, offset = 0): [number, number] {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\nexport function encodeTo (int: number, target: Uint8Array, offset = 0): Uint8Array {\n varint.encode(int, target, offset)\n return target\n}\n\nexport function encodingLength (int: number): number {\n return varint.encodingLength(int)\n}\n", "/* eslint-disable */\nvar encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\n while(num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while(num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n \n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1)\n\n // @ts-ignore\n read.bytes = counter - offset;\n\n return res\n}\n\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\n\nvar length = function (/** @type {number} */ value) {\n return (\n value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10\n )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n", "import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\nimport type { MultihashDigest } from './interface.js'\n\n/**\n * Creates a multihash digest.\n */\nexport function create <Code extends number> (code: Code, digest: Uint8Array): Digest<Code, number> {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\n const bytes = new Uint8Array(digestOffset + size)\n varint.encodeTo(code, bytes, 0)\n varint.encodeTo(size, bytes, sizeOffset)\n bytes.set(digest, digestOffset)\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode (multihash: Uint8Array): MultihashDigest {\n const bytes = coerce(multihash)\n const [code, sizeOffset] = varint.decode(bytes)\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset))\n const digest = bytes.subarray(sizeOffset + digestOffset)\n\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\nexport function equals (a: MultihashDigest, b: unknown): b is MultihashDigest {\n if (a === b) {\n return true\n } else {\n const data = b as { code?: unknown, size?: unknown, bytes?: unknown }\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest<Code extends number, Size extends number> implements MultihashDigest {\n readonly code: Code\n readonly size: Size\n readonly digest: Uint8Array\n readonly bytes: Uint8Array\n\n /**\n * Creates a multihash digest.\n */\n constructor (code: Code, size: Size, digest: Uint8Array, bytes: Uint8Array) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n", "import { base32 } from './bases/base32.js'\nimport { base58btc } from './bases/base58.js'\nimport { coerce } from './bytes.js'\nimport * as Digest from './hashes/digest.js'\nimport * as varint from './varint.js'\nimport type * as API from './link/interface.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\nexport function format <T extends API.Link<unknown, number, number, API.Version>, Prefix extends string> (link: T, base?: API.MultibaseEncoder<Prefix>): API.ToString<T, Prefix> {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n base as API.MultibaseEncoder<'z'> ?? base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n (base ?? base32.encoder) as API.MultibaseEncoder<Prefix>\n )\n }\n}\n\nexport function toJSON <Link extends API.UnknownLink> (link: Link): API.LinkJSON<Link> {\n return {\n '/': format(link)\n }\n}\n\nexport function fromJSON <Link extends API.UnknownLink> (json: API.LinkJSON<Link>): CID<unknown, number, number, API.Version> {\n return CID.parse(json['/'])\n}\n\nconst cache = new WeakMap<API.UnknownLink, Map<string, string>>()\n\nfunction baseCache (cid: API.UnknownLink): Map<string, string> {\n const baseCache = cache.get(cid)\n if (baseCache == null) {\n const baseCache = new Map()\n cache.set(cid, baseCache)\n return baseCache\n }\n return baseCache\n}\n\nexport class CID<Data = unknown, Format extends number = number, Alg extends number = number, Version extends API.Version = API.Version> implements API.Link<Data, Format, Alg, Version> {\n readonly code: Format\n readonly version: Version\n readonly multihash: API.MultihashDigest<Alg>\n readonly bytes: Uint8Array\n readonly '/': Uint8Array\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor (version: Version, code: Format, multihash: API.MultihashDigest<Alg>, bytes: Uint8Array) {\n this.code = code\n this.version = version\n this.multihash = multihash\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes\n }\n\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID (): this {\n return this\n }\n\n // ArrayBufferView\n get byteOffset (): number {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength (): number {\n return this.bytes.byteLength\n }\n\n toV0 (): CID<Data, API.DAG_PB, API.SHA_256, 0> {\n switch (this.version) {\n case 0: {\n return this as CID<Data, API.DAG_PB, API.SHA_256, 0>\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\n\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')\n }\n\n return (\n CID.createV0(\n multihash as API.MultihashDigest<API.SHA_256>\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n toV1 (): CID<Data, Format, Alg, 1> {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash\n const multihash = Digest.create(code, digest)\n return (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return this as CID<Data, Format, Alg, 1>\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n equals (other: unknown): other is CID<Data, Format, Alg, Version> {\n return CID.equals(this, other)\n }\n\n static equals <Data, Format extends number, Alg extends number, Version extends API.Version>(self: API.Link<Data, Format, Alg, Version>, other: unknown): other is CID {\n const unknown = other as { code?: unknown, version?: unknown, multihash?: unknown }\n return (\n unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n toString (base?: API.MultibaseEncoder<string>): string {\n return format(this, base)\n }\n\n toJSON (): API.LinkJSON<this> {\n return { '/': format(this) }\n }\n\n link (): this {\n return this\n }\n\n readonly [Symbol.toStringTag] = 'CID';\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] (): string {\n return `CID(${this.toString()})`\n }\n\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID <Data, Format extends number, Alg extends number, Version extends API.Version, U>(input: API.Link<Data, Format, Alg, Version> | U): CID<Data, Format, Alg, Version> | null {\n if (input == null) {\n return null\n }\n\n const value = input as any\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\n } else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value\n return new CID(\n version,\n code,\n multihash as API.MultihashDigest<Alg>,\n bytes ?? encodeCID(version, code, multihash.bytes)\n )\n } else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value\n const digest = Digest.decode(multihash) as API.MultihashDigest<Alg>\n return CID.create(version, code, digest)\n } else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null\n }\n }\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create <Data, Format extends number, Alg extends number, Version extends API.Version>(version: Version, code: Format, digest: API.MultihashDigest<Alg>): CID<Data, Format, Alg, Version> {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`\n )\n } else {\n return new CID(version, code, digest, digest.bytes)\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes)\n return new CID(version, code, digest, bytes)\n }\n default: {\n throw new Error('Invalid version')\n }\n }\n }\n\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0 <T = unknown>(digest: API.MultihashDigest<typeof SHA_256_CODE>): CID<T, typeof DAG_PB_CODE, typeof SHA_256_CODE, 0> {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1 <Data, Code extends number, Alg extends number>(code: Code, digest: API.MultihashDigest<Alg>): CID<Data, Code, Alg, 1> {\n return CID.create(1, code, digest)\n }\n\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode <Data, Code extends number, Alg extends number, Version extends API.Version>(bytes: API.ByteView<API.Link<Data, Code, Alg, Version>>): CID<Data, Code, Alg, Version> {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length !== 0) {\n throw new Error('Incorrect length')\n }\n return cid\n }\n\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst <T, C extends number, A extends number, V extends API.Version>(bytes: API.ByteView<API.Link<T, C, A, V>>): [CID<T, C, A, V>, Uint8Array] {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(digest as API.MultihashDigest<API.SHA_256>)\n : CID.createV1(specs.codec, digest)\n return [cid as CID<T, C, A, V>, bytes.subarray(specs.size)]\n }\n\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes <T, C extends number, A extends number, V extends API.Version>(initialBytes: API.ByteView<API.Link<T, C, A, V>>): { version: V, codec: C, multihashCode: A, digestSize: number, multihashSize: number, size: number } {\n let offset = 0\n const next = (): number => {\n const [i, length] = varint.decode(initialBytes.subarray(offset))\n offset += length\n return i\n }\n\n let version = next() as V\n let codec = DAG_PB_CODE as C\n if (version as number === 18) {\n // CIDv0\n version = 0 as V\n offset = 0\n } else {\n codec = next() as C\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = next() as A // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\n\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse <Prefix extends string, Data, Code extends number, Alg extends number, Version extends API.Version>(source: API.ToString<API.Link<Data, Code, Alg, Version>, Prefix>, base?: API.MultibaseDecoder<Prefix>): CID<Data, Code, Alg, Version> {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\nfunction parseCIDtoBytes <Prefix extends string, Data, Code extends number, Alg extends number, Version extends API.Version> (source: API.ToString<API.Link<Data, Code, Alg, Version>, Prefix>, base?: API.MultibaseDecoder<Prefix>): [Prefix, API.ByteView<API.Link<Data, Code, Alg, Version>>] {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc\n return [\n base58btc.prefix as Prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc\n return [base58btc.prefix as Prefix, decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base ?? base32\n return [base32.prefix as Prefix, decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [source[0] as Prefix, base.decode(source)]\n }\n }\n}\n\nfunction toStringV0 (bytes: Uint8Array, cache: Map<string, string>, base: API.MultibaseEncoder<'z'>): string {\n const { prefix } = base\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n }\n\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes).slice(1)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nfunction toStringV1 <Prefix extends string> (bytes: Uint8Array, cache: Map<string, string>, base: API.MultibaseEncoder<Prefix>): string {\n const { prefix } = base\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\nfunction encodeCID (version: API.Version, code: number, multihash: Uint8Array): Uint8Array {\n const codeOffset = varint.encodingLength(version)\n const hashOffset = codeOffset + varint.encodingLength(code)\n const bytes = new Uint8Array(hashOffset + multihash.byteLength)\n varint.encodeTo(version, bytes, 0)\n varint.encodeTo(code, bytes, codeOffset)\n bytes.set(multihash, hashOffset)\n return bytes\n}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n", "import { varint } from 'multiformats';\n\nexport type MulticodecCode = number;\n\nexport type MulticodecDefinition<MulticodecCode> = {\n code: MulticodecCode;\n // codeBytes: Uint8Array;\n name: string;\n};\n\n/**\n * The `Multicodec` class provides an interface to prepend binary data\n * with a prefix that identifies the data that follows.\n * https://github.com/multiformats/multicodec/blob/master/table.csv\n *\n * Multicodec is a self-describing multiformat, it wraps other formats with\n * a tiny bit of self-description. A multicodec identifier is a\n * varint (variable integer) that indicates the format of the data.\n *\n * The canonical table of multicodecs can be access at the following URL:\n * https://github.com/multiformats/multicodec/blob/master/table.csv\n *\n * Example usage:\n *\n * ```ts\n * Multicodec.registerCodec({ code: 0xed, name: 'ed25519-pub' });\n * const prefixedData = Multicodec.addPrefix({ code: 0xed, data: new Uint8Array(32) });\n * ```\n */\nexport class Multicodec {\n /**\n * A static field containing a map of codec codes to their corresponding names.\n */\n static codeToName = new Map<MulticodecCode, string>();\n\n /**\n * A static field containing a map of codec names to their corresponding codes.\n */\n static nameToCode = new Map<string, MulticodecCode>();\n\n /**\n * Adds a multicodec prefix to input data.\n *\n * @param options - The options for adding a prefix.\n * @param options.code - The codec code. Either the code or name must be provided.\n * @param options.name - The codec name. Either the code or name must be provided.\n * @param options.data - The data to be prefixed.\n * @returns The data with the added prefix as a Uint8Array.\n */\n public static addPrefix(options: {\n code?: MulticodecCode,\n data: Uint8Array,\n name?: string,\n }): Uint8Array {\n let { code, data, name } = options;\n\n if (!(name ? !code : code)) {\n throw new Error(`Either 'name' or 'code' must be defined, but not both.`);\n }\n\n // If code was given, confirm it exists, or lookup code by name.\n code = Multicodec.codeToName.has(code!) ? code : Multicodec.nameToCode.get(name!);\n\n // Throw error if a registered Codec wasn't found.\n if (code === undefined) {\n throw new Error(`Unsupported multicodec: ${options.name ?? options.code}`);\n }\n\n // Create a new array to store the prefix and input data.\n const prefixLength = varint.encodingLength(code);\n const dataWithPrefix = new Uint8Array(prefixLength + data.byteLength);\n dataWithPrefix.set(data, prefixLength);\n\n // Prepend the prefix.\n varint.encodeTo(code, dataWithPrefix);\n\n return dataWithPrefix;\n }\n\n /**\n * Get the Multicodec code from given prefixed data.\n *\n * @param options - The options for getting the codec code.\n * @param options.prefixedData - The data to extract the codec code from.\n * @returns - The Multicodec code as a number.\n */\n public static getCodeFromData(options: {\n prefixedData: Uint8Array\n }): MulticodecCode {\n const { prefixedData } = options;\n const [code, _] = varint.decode(prefixedData);\n\n return code;\n }\n\n /**\n * Get the Multicodec code from given Multicodec name.\n *\n * @param options - The options for getting the codec code.\n * @param options.name - The name to lookup.\n * @returns - The Multicodec code as a number.\n */\n public static getCodeFromName(options: {\n name: string\n }): MulticodecCode {\n const { name } = options;\n\n // Throw error if a registered Codec wasn't found.\n const code = Multicodec.nameToCode.get(name);\n if (code === undefined) {\n throw new Error(`Unsupported multicodec: ${name}`);\n }\n\n return code;\n }\n\n /**\n * Get the Multicodec name from given Multicodec code.\n *\n * @param options - The options for getting the codec name.\n * @param options.name - The code to lookup.\n * @returns - The Multicodec name as a string.\n */\n public static getNameFromCode(options: {\n code: MulticodecCode\n }): string {\n const { code } = options;\n\n // Throw error if a registered Codec wasn't found.\n const name = Multicodec.codeToName.get(code);\n if (name === undefined) {\n throw new Error(`Unsupported multicodec: ${code}`);\n }\n\n return name;\n }\n\n /**\n * Registers a new codec in the Multicodec class.\n *\n * @param codec - The codec to be registered.\n */\n public static registerCodec(codec: MulticodecDefinition<MulticodecCode>): void {\n Multicodec.codeToName.set(codec.code, codec.name);\n Multicodec.nameToCode.set(codec.name, codec.code);\n }\n\n /**\n * Returns the data with the Multicodec prefix removed.\n *\n * @param refixedData - The data to extract the codec code from.\n * @returns {Uint8Array}\n */\n public static removePrefix(options: {\n prefixedData: Uint8Array\n }): { code: MulticodecCode, name: string, data: Uint8Array } {\n const { prefixedData } = options;\n const [code, codeByteLength] = varint.decode(prefixedData);\n\n // Throw error if a registered Codec wasn't found.\n const name = Multicodec.codeToName.get(code);\n if (name === undefined) {\n throw new Error(`Unsupported multicodec: ${code}`);\n }\n\n return { code, data: prefixedData.slice(codeByteLength), name };\n }\n}\n\n// Pre-defined registered codecs:\nMulticodec.registerCodec({ code: 0xed, name: 'ed25519-pub' });\nMulticodec.registerCodec({ code: 0x1300, name: 'ed25519-priv' });\nMulticodec.registerCodec({ code: 0xec, name: 'x25519-pub' });\nMulticodec.registerCodec({ code: 0x1302, name: 'x25519-priv' });\nMulticodec.registerCodec({ code: 0xe7, name: 'secp256k1-pub' });\nMulticodec.registerCodec({ code: 0x1301, name: 'secp256k1-priv' });", "/**\n * Checks whether the given object has any properties.\n */\nexport function isEmptyObject(obj: unknown): boolean {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n\n if (Object.getOwnPropertySymbols(obj).length > 0) {\n return false;\n }\n\n return Object.keys(obj).length === 0;\n}\n\n/**\n * Recursively removes all properties with an empty object or array as its value from the given object.\n */\nexport function removeEmptyObjects(obj: Record<string, unknown>): void {\n Object.keys(obj).forEach(key => {\n if (typeof(obj[key]) === 'object') {\n // recursive remove empty object or array properties in nested objects\n removeEmptyObjects(obj[key] as Record<string, unknown>);\n }\n\n if (isEmptyObject(obj[key])) {\n delete obj[key];\n }\n });\n}\n\n/**\n * Recursively removes all properties with `undefined` as its value from the given object.\n */\nexport function removeUndefinedProperties(obj: Record<string, unknown>): void {\n Object.keys(obj).forEach(key => {\n if (obj[key] === undefined) {\n delete obj[key];\n } else if (typeof(obj[key]) === 'object') {\n removeUndefinedProperties(obj[key] as Record<string, unknown>); // recursive remove `undefined` properties in nested objects\n }\n });\n}", "import type { AbstractLevel } from 'abstract-level';\n\nimport { Level } from 'level';\n\nimport type { KeyValueStore } from './types.js';\n\nexport class LevelStore<K = string, V = any> implements KeyValueStore<K, V> {\n private store: AbstractLevel<string | Buffer | Uint8Array, K, V>;\n\n constructor({ db, location = 'DATASTORE' }: {\n db?: AbstractLevel<string | Buffer | Uint8Array, K, V>;\n location?: string;\n } = {}) {\n this.store = db ?? new Level<K, V>(location);\n }\n\n async clear(): Promise<void> {\n await this.store.clear();\n }\n\n async close(): Promise<void> {\n await this.store.close();\n }\n\n async delete(key: K): Promise<void> {\n await this.store.del(key);\n }\n\n async get(key: K): Promise<V | undefined> {\n try {\n return await this.store.get(key);\n } catch (error: any) {\n // Don't throw when a key wasn't found.\n if (error.notFound) {return undefined;}\n throw error;\n }\n }\n\n async set(key: K, value: V): Promise<void> {\n await this.store.put(key, value);\n }\n}\n\n/**\n * The `MemoryStore` class is an implementation of\n * `KeyValueStore` that holds data in memory.\n *\n * It provides a basic key-value store that works synchronously and keeps all\n * data in memory. This can be used for testing, or for handling small amounts\n * of data with simple key-value semantics.\n *\n * Example usage:\n *\n * ```ts\n * const memoryStore = new MemoryStore<string, number>();\n * await memoryStore.set(\"key1\", 1);\n * const value = await memoryStore.get(\"key1\");\n * console.log(value); // 1\n * ```\n *\n * @public\n */\nexport class MemoryStore<K, V> implements KeyValueStore<K, V> {\n /**\n * A private field that contains the Map used as the key-value store.\n */\n private store: Map<K, V> = new Map();\n\n /**\n * Clears all entries in the key-value store.\n *\n * @returns A Promise that resolves when the operation is complete.\n */\n async clear(): Promise<void> {\n this.store.clear();\n }\n\n /**\n * This operation is no-op for `MemoryStore`\n * and will log a warning if called.\n */\n async close(): Promise<void> {\n /** no-op */\n }\n\n /**\n * Deletes an entry from the key-value store by its key.\n *\n * @param id - The key of the entry to delete.\n * @returns A Promise that resolves to a boolean indicating whether the entry was successfully deleted.\n */\n async delete(id: K): Promise<boolean> {\n return this.store.delete(id);\n }\n\n /**\n * Retrieves the value of an entry by its key.\n *\n * @param id - The key of the entry to retrieve.\n * @returns A Promise that resolves to the value of the entry, or `undefined` if the entry does not exist.\n */\n async get(id: K): Promise<V | undefined> {\n return this.store.get(id);\n }\n\n /**\n * Checks for the presence of an entry by key.\n *\n * @param id - The key to check for the existence of.\n * @returns A Promise that resolves to a boolean indicating whether an element with the specified key exists or not.\n */\n async has(id: K): Promise<boolean> {\n return this.store.has(id);\n }\n\n /**\n * Retrieves all values in the key-value store.\n *\n * @returns A Promise that resolves to an array of all values in the store.\n */\n async list(): Promise<V[]> {\n return Array.from(this.store.values());\n }\n\n /**\n * Sets the value of an entry in the key-value store.\n *\n * @param id - The key of the entry to set.\n * @param key - The new value for the entry.\n * @returns A Promise that resolves when the operation is complete.\n */\n async set(id: K, key: V): Promise<void> {\n this.store.set(id, key);\n }\n}", "/**\n * Base class for all cryptographic algorithm implementations.\n */\nexport abstract class CryptoAlgorithm {}", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nexport type Hex = Uint8Array | string; // hex strings are accepted for simplicity\nexport type PrivKey = Hex | bigint; // bigints are accepted to ease learning curve\nexport type CHash = {\n (message: Uint8Array | string): Uint8Array;\n blockLen: number;\n outputLen: number;\n create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array | string) => Uint8Array;\n\nexport function isBytes(a: unknown): a is Uint8Array {\n return (\n a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')\n );\n}\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n if (!isBytes(bytes)) throw new Error('Uint8Array expected');\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n}\n\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 } as const;\nfunction asciiToBase16(char: number): number | undefined {\n if (char >= asciis._0 && char <= asciis._9) return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F) return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f) return char - (asciis._a - 10);\n return;\n}\n\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes: Uint8Array): bigint {\n if (!isBytes(bytes)) throw new Error('Uint8Array expected');\n return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n: number | bigint, len: number): Uint8Array {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n: number | bigint): Uint8Array {\n return hexToBytes(numberToHexUnpadded(n));\n}\n\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array {\n let res: Uint8Array;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes(hex);\n } catch (e) {\n throw new Error(`${title} must be valid hex string, got \"${hex}\". Cause: ${e}`);\n }\n } else if (isBytes(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n } else {\n throw new Error(`${title} must be hex string or Uint8Array`);\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);\n return res;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n if (!isBytes(a)) throw new Error('Uint8Array expected');\n sum += a.length;\n }\n let res = new Uint8Array(sum);\n let pad = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a: Uint8Array, b: Uint8Array) {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n// Bit operations\n\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n */\nexport function bitLen(n: bigint) {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1);\n return len;\n}\n\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n: bigint, pos: number) {\n return (n >> BigInt(pos)) & _1n;\n}\n\n/**\n * Sets single bit at position.\n */\nexport const bitSet = (n: bigint, pos: number, value: boolean) => {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n};\n\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n: number) => (_2n << BigInt(n - 1)) - _1n;\n\n// DRBG\n\nconst u8n = (data?: any) => new Uint8Array(data); // creates Uint8Array\nconst u8fr = (arr: any) => Uint8Array.from(arr); // another shortcut\ntype Pred<T> = (v: Uint8Array) => T | undefined;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG<Key>(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg<T>(\n hashLen: number,\n qByteLen: number,\n hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array\n): (seed: Uint8Array, predicate: Pred<T>) => T {\n if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b: Uint8Array[]) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n()) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000) throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out: Uint8Array[] = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed: Uint8Array, pred: Pred<T>): T => {\n reset();\n reseed(seed); // Steps D-G\n let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen()))) reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n\n// Validating curves and fields\n\nconst validatorFns = {\n bigint: (val: any) => typeof val === 'bigint',\n function: (val: any) => typeof val === 'function',\n boolean: (val: any) => typeof val === 'boolean',\n string: (val: any) => typeof val === 'string',\n stringOrUint8Array: (val: any) => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val: any) => Number.isSafeInteger(val),\n array: (val: any) => Array.isArray(val),\n field: (val: any, object: any) => (object as any).Fp.isValid(val),\n hash: (val: any) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n} as const;\ntype Validator = keyof typeof validatorFns;\ntype ValMap<T extends Record<string, any>> = { [K in keyof T]?: Validator };\n// type Record<K extends string | number | symbol, T> = { [P in K]: T; }\n\nexport function validateObject<T extends Record<string, any>>(\n object: T,\n validators: ValMap<T>,\n optValidators: ValMap<T> = {}\n) {\n const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function')\n throw new Error(`Invalid validator \"${type}\", expected function`);\n\n const val = object[fieldName as keyof typeof object];\n if (isOptional && val === undefined) return;\n if (!checkVal(val, object)) {\n throw new Error(\n `Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`\n );\n }\n };\n for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type!, false);\n for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type!, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n", "function number(n: number) {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error(`Wrong positive integer: ${n}`);\n}\n\nfunction bool(b: boolean) {\n if (typeof b !== 'boolean') throw new Error(`Expected boolean, not ${b}`);\n}\n\n// copied from utils\nfunction isBytes(a: unknown): a is Uint8Array {\n return (\n a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')\n );\n}\n\nfunction bytes(b: Uint8Array | undefined, ...lengths: number[]) {\n if (!isBytes(b)) throw new Error('Expected Uint8Array');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);\n}\n\ntype Hash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\nfunction hash(hash: Hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\n\nfunction exists(instance: any, checkFinished = true) {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\nfunction output(out: any, instance: any) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\n\nexport { number, bool, bytes, hash, exists, output };\n\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n", "// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// See utils.ts for details.\ndeclare const globalThis: Record<string, any> | undefined;\nexport const crypto =\n typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n", "/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n// Cast array to different type\nexport const u8 = (arr: TypedArray) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr: TypedArray) =>\n new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n\nfunction isBytes(a: unknown): a is Uint8Array {\n return (\n a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')\n );\n}\n\n// Cast array to view\nexport const createView = (arr: TypedArray) =>\n new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word: number, shift: number) => (word << (32 - shift)) | (word >>> shift);\n\n// big-endian hardware is rare. Just in case someone still decides to run hashes:\n// early-throw an error because we don't support BE yet.\n// Other libraries would silently corrupt the data instead of throwing an error,\n// when they don't support it.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE) throw new Error('Non little-endian hardware is not supported');\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n if (!isBytes(bytes)) throw new Error('Uint8Array expected');\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 } as const;\nfunction asciiToBase16(char: number): number | undefined {\n if (char >= asciis._0 && char <= asciis._9) return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F) return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f) return char - (asciis._a - 10);\n return;\n}\n\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => {};\n\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters: number, tick: number, cb: (i: number) => void) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\nexport type Input = Uint8Array | string;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n if (!isBytes(data)) throw new Error(`expected Uint8Array, got ${typeof data}`);\n return data;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n if (!isBytes(a)) throw new Error('Uint8Array expected');\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\n// For runtime check if class implements interface\nexport abstract class Hash<T extends Hash<T>> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n /**\n * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n * when no options are passed.\n * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n * There are no guarantees for clean-up because it's impossible in JS.\n */\n abstract _cloneInto(to?: T): T;\n // Safe version that clones internal state\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\nconst toStr = {}.toString;\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\nexport type CHash = ReturnType<typeof wrapConstructor>;\n\nexport function wrapConstructor<T extends Hash<T>>(hashCons: () => Hash<T>) {\n const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n\nexport function wrapConstructorWithOpts<H extends Hash<H>, T extends Object>(\n hashCons: (opts?: T) => Hash<H>\n) {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts: T) => hashCons(opts);\n return hashC;\n}\n\nexport function wrapXOFConstructorWithOpts<H extends HashXOF<H>, T extends Object>(\n hashCons: (opts?: T) => HashXOF<H>\n) {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts: T) => hashCons(opts);\n return hashC;\n}\n\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n", "import { exists, output } from './_assert.js';\nimport { Hash, createView, Input, toBytes } from './utils.js';\n\n// Polyfill for Safari 14\nfunction setBigUint64(view: DataView, byteOffset: number, value: bigint, isLE: boolean): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n// Base SHA2 class (RFC 6234)\nexport abstract class SHA2<T extends SHA2<T>> extends Hash<T> {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(\n readonly blockLen: number,\n public outputLen: number,\n readonly padOffset: number,\n readonly isLE: boolean\n ) {\n super();\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n exists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array) {\n exists(this);\n output(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n}\n", "import { SHA2 } from './_sha2.js';\nimport { rotr, wrapConstructor } from './utils.js';\n\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^67 hashes/sec as per early 2023.\n\n// Choice: a ? b : c\nconst Chi = (a: number, b: number, c: number) => (a & b) ^ (~a & c);\n// Majority function, true if any two inpust is true\nconst Maj = (a: number, b: number, c: number) => (a & b) ^ (a & c) ^ (b & c);\n\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n// prettier-ignore\nconst IV = /* @__PURE__ */new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nclass SHA256 extends SHA2<SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n A = IV[0] | 0;\n B = IV[1] | 0;\n C = IV[2] | 0;\n D = IV[3] | 0;\n E = IV[4] | 0;\n F = IV[5] | 0;\n G = IV[6] | 0;\n H = IV[7] | 0;\n\n constructor() {\n super(64, 32, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n A = 0xc1059ed8 | 0;\n B = 0x367cd507 | 0;\n C = 0x3070dd17 | 0;\n D = 0xf70e5939 | 0;\n E = 0xffc00b31 | 0;\n F = 0x68581511 | 0;\n G = 0x64f98fa7 | 0;\n H = 0xbefa4fa4 | 0;\n constructor() {\n super();\n this.outputLen = 28;\n }\n}\n\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexport const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());\nexport const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Utilities for modular arithmetics and finite fields\nimport {\n bitMask,\n numberToBytesBE,\n numberToBytesLE,\n bytesToNumberBE,\n bytesToNumberLE,\n ensureBytes,\n validateObject,\n} from './utils.js';\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);\n// prettier-ignore\nconst _9n = BigInt(9), _16n = BigInt(16);\n\n// Calculates a modulo b\nexport function mod(a: bigint, b: bigint): bigint {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\n// TODO: use field version && remove\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n if (modulo <= _0n || power < _0n) throw new Error('Expected power/modulo > 0');\n if (modulo === _1n) return _0n;\n let res = _1n;\n while (power > _0n) {\n if (power & _1n) res = (res * num) % modulo;\n num = (num * num) % modulo;\n power >>= _1n;\n }\n return res;\n}\n\n// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)\nexport function pow2(x: bigint, power: bigint, modulo: bigint): bigint {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n\n// Inverses number over modulo\nexport function invert(number: bigint, modulo: bigint): bigint {\n if (number === _0n || modulo <= _0n) {\n throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);\n }\n // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n) throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * Will start an infinite loop if field order P is not prime.\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint) {\n // Legendre constant: used to calculate Legendre symbol (a | p),\n // which denotes the value of a^((p-1)/2) (mod p).\n // (a | p) \u2261 1 if a is a square (mod p)\n // (a | p) \u2261 -1 if a is not a square (mod p)\n // (a | p) \u2261 0 if a \u2261 0 (mod p)\n const legendreC = (P - _1n) / _2n;\n\n let Q: bigint, S: number, Z: bigint;\n // Step 1: By factoring out powers of 2 from p - 1,\n // find q and s such that p - 1 = q*(2^s) with q odd\n for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++);\n\n // Step 2: Select a non-square z such that (z | p) \u2261 -1 and set c \u2261 zq\n for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++);\n\n // Fast-path\n if (S === 1) {\n const p1div4 = (P + _1n) / _4n;\n return function tonelliFast<T>(Fp: IField<T>, n: T) {\n const root = Fp.pow(n, p1div4);\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // Slow-path\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow<T>(Fp: IField<T>, n: T): T {\n // Step 0: Check that n is indeed a square: (n | p) should not be \u2261 -1\n if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) throw new Error('Cannot find square root');\n let r = S;\n // TODO: will fail at Fp2/etc\n let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b\n let x = Fp.pow(n, Q1div2); // first guess at the square root\n let b = Fp.pow(n, Q); // first guess at the fudge factor\n\n while (!Fp.eql(b, Fp.ONE)) {\n if (Fp.eql(b, Fp.ZERO)) return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)\n // Find m such b^(2^m)==1\n let m = 1;\n for (let t2 = Fp.sqr(b); m < r; m++) {\n if (Fp.eql(t2, Fp.ONE)) break;\n t2 = Fp.sqr(t2); // t2 *= t2\n }\n // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow\n const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)\n g = Fp.sqr(ge); // g = ge * ge\n x = Fp.mul(x, ge); // x *= ge\n b = Fp.mul(b, g); // b *= g\n r = m;\n }\n return x;\n };\n}\n\nexport function FpSqrt(P: bigint) {\n // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.\n // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n\n // P \u2261 3 (mod 4)\n // \u221An = n^((P+1)/4)\n if (P % _4n === _3n) {\n // Not all roots possible!\n // const ORDER =\n // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;\n // const NUM = 72057594037927816n;\n const p1div4 = (P + _1n) / _4n;\n return function sqrt3mod4<T>(Fp: IField<T>, n: T) {\n const root = Fp.pow(n, p1div4);\n // Throw if root**2 != n\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // Atkin algorithm for q \u2261 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)\n if (P % _8n === _5n) {\n const c1 = (P - _5n) / _8n;\n return function sqrt5mod8<T>(Fp: IField<T>, n: T) {\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, c1);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // P \u2261 9 (mod 16)\n if (P % _16n === _9n) {\n // NOTE: tonelli is too slow for bls-Fp2 calculations even on start\n // Means we cannot use sqrt for constants at all!\n //\n // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n // sqrt = (x) => {\n // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4\n // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1\n // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1\n // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1\n // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x\n // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x\n // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x\n // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\n // }\n }\n\n // Other cases: Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num: bigint, modulo: bigint) => (mod(num, modulo) & _1n) === _1n;\n\n// Field is not always over prime: for example, Fp2 has ORDER(q)=p^m\nexport interface IField<T> {\n ORDER: bigint;\n BYTES: number;\n BITS: number;\n MASK: bigint;\n ZERO: T;\n ONE: T;\n // 1-arg\n create: (num: T) => T;\n isValid: (num: T) => boolean;\n is0: (num: T) => boolean;\n neg(num: T): T;\n inv(num: T): T;\n sqrt(num: T): T;\n sqr(num: T): T;\n // 2-args\n eql(lhs: T, rhs: T): boolean;\n add(lhs: T, rhs: T): T;\n sub(lhs: T, rhs: T): T;\n mul(lhs: T, rhs: T | bigint): T;\n pow(lhs: T, power: bigint): T;\n div(lhs: T, rhs: T | bigint): T;\n // N for NonNormalized (for now)\n addN(lhs: T, rhs: T): T;\n subN(lhs: T, rhs: T): T;\n mulN(lhs: T, rhs: T | bigint): T;\n sqrN(num: T): T;\n\n // Optional\n // Should be same as sgn0 function in\n // [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#section-4.1).\n // NOTE: sgn0 is 'negative in LE', which is same as odd. And negative in LE is kinda strange definition anyway.\n isOdd?(num: T): boolean; // Odd instead of even since we have it for Fp2\n // legendre?(num: T): T;\n pow(lhs: T, power: bigint): T;\n invertBatch: (lst: T[]) => T[];\n toBytes(num: T): Uint8Array;\n fromBytes(bytes: Uint8Array): T;\n // If c is False, CMOV returns a, otherwise it returns b.\n cmov(a: T, b: T, c: boolean): T;\n}\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n] as const;\nexport function validateField<T>(field: IField<T>) {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'isSafeInteger',\n BITS: 'isSafeInteger',\n } as Record<string, string>;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n return validateObject(field, opts);\n}\n\n// Generic field functions\n\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow<T>(f: IField<T>, num: T, power: bigint): T {\n // Should have same speed as pow for bigints\n // TODO: benchmark!\n if (power < _0n) throw new Error('Expected power > 0');\n if (power === _0n) return f.ONE;\n if (power === _1n) return num;\n let p = f.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = f.mul(p, d);\n d = f.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * `inv(0)` will return `undefined` here: make sure to throw an error.\n */\nexport function FpInvertBatch<T>(f: IField<T>, nums: T[]): T[] {\n const tmp = new Array(nums.length);\n // Walk from first to last, multiply them by each other MOD p\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (f.is0(num)) return acc;\n tmp[i] = acc;\n return f.mul(acc, num);\n }, f.ONE);\n // Invert last element\n const inverted = f.inv(lastMultiplied);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (f.is0(num)) return acc;\n tmp[i] = f.mul(acc, tmp[i]);\n return f.mul(acc, num);\n }, inverted);\n return tmp;\n}\n\nexport function FpDiv<T>(f: IField<T>, lhs: T, rhs: T | bigint): T {\n return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare<T>(f: IField<T>) {\n const legendreConst = (f.ORDER - _1n) / _2n; // Integer arithmetic\n return (x: T): boolean => {\n const p = f.pow(x, legendreConst);\n return f.eql(p, f.ZERO) || f.eql(p, f.ONE);\n };\n}\n\n// CURVE.n lengths\nexport function nLength(n: bigint, nBitLength?: number) {\n // Bit size, byte size of CURVE.n\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n\ntype FpField = IField<bigint> & Required<Pick<IField<bigint>, 'isOdd'>>;\n/**\n * Initializes a finite field over prime. **Non-primes are not supported.**\n * Do not init in loop: slow. Very fragile: always run a benchmark on a change.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) Object.freeze\n * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(\n ORDER: bigint,\n bitLen?: number,\n isLE = false,\n redef: Partial<IField<bigint>> = {}\n): Readonly<FpField> {\n if (ORDER <= _0n) throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n if (BYTES > 2048) throw new Error('Field lengths over 2048 bytes are not supported');\n const sqrtP = FpSqrt(ORDER);\n const f: Readonly<FpField> = Object.freeze({\n ORDER,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n\n inv: (num) => invert(num, ORDER),\n sqrt: redef.sqrt || ((n) => sqrtP(f, n)),\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // TODO: do we really need constant cmov?\n // We don't have const-time bigints anyway, so probably will be not very useful\n cmov: (a, b, c) => (c ? b : a),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes) => {\n if (bytes.length !== BYTES)\n throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);\n return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n },\n } as FpField);\n return Object.freeze(f);\n}\n\nexport function FpSqrtOdd<T>(Fp: IField<T>, elm: T) {\n if (!Fp.isOdd) throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\n\nexport function FpSqrtEven<T>(Fp: IField<T>, elm: T) {\n if (!Fp.isOdd) throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use mapKeyToField instead\n */\nexport function hashToPrivateScalar(\n hash: string | Uint8Array,\n groupOrder: bigint,\n isLE = false\n): bigint {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder: bigint): number {\n if (typeof fieldOrder !== 'bigint') throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder: bigint): number {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key: Uint8Array, fieldOrder: bigint, isLE = false): Uint8Array {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);\n const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Abelian group utilities\nimport { IField, validateField, nLength } from './modular.js';\nimport { validateObject } from './utils.js';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\nexport type AffinePoint<T> = {\n x: T;\n y: T;\n} & { z?: never; t?: never };\n\nexport interface Group<T extends Group<T>> {\n double(): T;\n negate(): T;\n add(other: T): T;\n subtract(other: T): T;\n equals(other: T): boolean;\n multiply(scalar: bigint): T;\n}\n\nexport type GroupConstructor<T> = {\n BASE: T;\n ZERO: T;\n};\nexport type Mapper<T> = (i: T[]) => T[];\n\n// Elliptic curve multiplication of Point by scalar. Fragile.\n// Scalars should always be less than curve order: this should be checked inside of a curve itself.\n// Creates precomputation tables for fast multiplication:\n// - private scalar is split by fixed size windows of W bits\n// - every window point is collected from window's table & added to accumulator\n// - since windows are different, same point inside tables won't be accessed more than once per calc\n// - each multiplication is 'Math.ceil(CURVE_ORDER / \uD835\uDC4A) + 1' point additions (fixed for any scalar)\n// - +1 window is neccessary for wNAF\n// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow\n// windows to be in different memory locations\nexport function wNAF<T extends Group<T>>(c: GroupConstructor<T>, bits: number) {\n const constTimeNegate = (condition: boolean, item: T): T => {\n const neg = item.negate();\n return condition ? neg : item;\n };\n const opts = (W: number) => {\n const windows = Math.ceil(bits / W) + 1; // +1, because\n const windowSize = 2 ** (W - 1); // -1 because we skip zero\n return { windows, windowSize };\n };\n return {\n constTimeNegate,\n // non-const time multiplication ladder\n unsafeLadder(elm: T, n: bigint) {\n let p = c.ZERO;\n let d: T = elm;\n while (n > _0n) {\n if (n & _1n) p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n },\n\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(\uD835\uDC4A\u22121) * (Math.ceil(\uD835\uDC5B / \uD835\uDC4A) + 1), where:\n * - \uD835\uDC4A is the window size\n * - \uD835\uDC5B is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(elm: T, W: number): Group<T>[] {\n const { windows, windowSize } = opts(W);\n const points: T[] = [];\n let p: T = elm;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // =1, because we skip zero\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n },\n\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @returns real and fake (for const-time) points\n */\n wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T } {\n // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise\n // But need to carefully remove other checks before wNAF. ORDER == bits here\n const { windows, windowSize } = opts(W);\n\n let p = c.ZERO;\n let f = c.BASE;\n\n const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n // Extract W bits.\n let wbits = Number(n & mask);\n\n // Shift number by W bits.\n n >>= shiftBy;\n\n // If the bits are bigger than max size, we'll split those.\n // +224 => 256 - 32\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n\n // Check if we're onto Zero point.\n // Add random point inside current window to f.\n const offset1 = offset;\n const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero\n const cond1 = window % 2 !== 0;\n const cond2 = wbits < 0;\n if (wbits === 0) {\n // The most important part for const-time getPublicKey\n f = f.add(constTimeNegate(cond1, precomputes[offset1]));\n } else {\n p = p.add(constTimeNegate(cond2, precomputes[offset2]));\n }\n }\n // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()\n // Even if the variable is still unused, there are some checks which will\n // throw an exception, so compiler needs to prove they won't happen, which is hard.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n },\n\n wNAFCached(P: T, precomputesMap: Map<T, T[]>, n: bigint, transform: Mapper<T>): { p: T; f: T } {\n // @ts-ignore\n const W: number = P._WINDOW_SIZE || 1;\n // Calculate precomputes on a first run, reuse them after\n let comp = precomputesMap.get(P);\n if (!comp) {\n comp = this.precomputeWindow(P, W) as T[];\n if (W !== 1) {\n precomputesMap.set(P, transform(comp));\n }\n }\n return this.wNAF(W, comp, n);\n },\n };\n}\n\n// Generic BasicCurve interface: works even for polynomial fields (BLS): P, n, h would be ok.\n// Though generator can be different (Fp2 / Fp6 for BLS).\nexport type BasicCurve<T> = {\n Fp: IField<T>; // Field over which we'll do calculations (Fp)\n n: bigint; // Curve order, total count of valid points in the field\n nBitLength?: number; // bit length of curve order\n nByteLength?: number; // byte length of curve order\n h: bigint; // cofactor. we can assign default=1, but users will just ignore it w/o validation\n hEff?: bigint; // Number to multiply to clear cofactor\n Gx: T; // base point X coordinate\n Gy: T; // base point Y coordinate\n allowInfinityPoint?: boolean; // bls12-381 requires it. ZERO point is valid, but invalid pubkey\n};\n\nexport function validateBasic<FP, T>(curve: BasicCurve<FP> & T) {\n validateField(curve.Fp);\n validateObject(\n curve,\n {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n },\n {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n }\n );\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n } as const);\n}\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Short Weierstrass curve. The formula is: y\u00B2 = x\u00B3 + ax + b\nimport * as mod from './modular.js';\nimport * as ut from './utils.js';\nimport { CHash, Hex, PrivKey, ensureBytes } from './utils.js';\nimport { Group, GroupConstructor, wNAF, BasicCurve, validateBasic, AffinePoint } from './curve.js';\n\nexport type { AffinePoint };\ntype HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array;\ntype EndomorphismOpts = {\n beta: bigint;\n splitScalar: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n};\nexport type BasicWCurve<T> = BasicCurve<T> & {\n // Params: a, b\n a: T;\n b: T;\n\n // Optional params\n allowedPrivateKeyLengths?: readonly number[]; // for P521\n wrapPrivateKey?: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n endo?: EndomorphismOpts; // Endomorphism options for Koblitz curves\n // When a cofactor != 1, there can be an effective methods to:\n // 1. Determine whether a point is torsion-free\n isTorsionFree?: (c: ProjConstructor<T>, point: ProjPointType<T>) => boolean;\n // 2. Clear torsion component\n clearCofactor?: (c: ProjConstructor<T>, point: ProjPointType<T>) => ProjPointType<T>;\n};\n\ntype Entropy = Hex | true;\nexport type SignOpts = { lowS?: boolean; extraEntropy?: Entropy; prehash?: boolean };\nexport type VerOpts = { lowS?: boolean; prehash?: boolean };\n\n/**\n * ### Design rationale for types\n *\n * * Interaction between classes from different curves should fail:\n * `k256.Point.BASE.add(p256.Point.BASE)`\n * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime\n * * Different calls of `curve()` would return different classes -\n * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,\n * it won't affect others\n *\n * TypeScript can't infer types for classes created inside a function. Classes is one instance of nominative types in TypeScript and interfaces only check for shape, so it's hard to create unique type for every function call.\n *\n * We can use generic types via some param, like curve opts, but that would:\n * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)\n * which is hard to debug.\n * 2. Params can be generic and we can't enforce them to be constant value:\n * if somebody creates curve from non-constant params,\n * it would be allowed to interact with other curves with non-constant params\n *\n * TODO: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol\n */\n\n// Instance for 3d XYZ points\nexport interface ProjPointType<T> extends Group<ProjPointType<T>> {\n readonly px: T;\n readonly py: T;\n readonly pz: T;\n get x(): T;\n get y(): T;\n multiply(scalar: bigint): ProjPointType<T>;\n toAffine(iz?: T): AffinePoint<T>;\n isTorsionFree(): boolean;\n clearCofactor(): ProjPointType<T>;\n assertValidity(): void;\n hasEvenY(): boolean;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n toHex(isCompressed?: boolean): string;\n\n multiplyUnsafe(scalar: bigint): ProjPointType<T>;\n multiplyAndAddUnsafe(Q: ProjPointType<T>, a: bigint, b: bigint): ProjPointType<T> | undefined;\n _setWindowSize(windowSize: number): void;\n}\n// Static methods for 3d XYZ points\nexport interface ProjConstructor<T> extends GroupConstructor<ProjPointType<T>> {\n new (x: T, y: T, z: T): ProjPointType<T>;\n fromAffine(p: AffinePoint<T>): ProjPointType<T>;\n fromHex(hex: Hex): ProjPointType<T>;\n fromPrivateKey(privateKey: PrivKey): ProjPointType<T>;\n normalizeZ(points: ProjPointType<T>[]): ProjPointType<T>[];\n}\n\nexport type CurvePointsType<T> = BasicWCurve<T> & {\n // Bytes\n fromBytes?: (bytes: Uint8Array) => AffinePoint<T>;\n toBytes?: (c: ProjConstructor<T>, point: ProjPointType<T>, isCompressed: boolean) => Uint8Array;\n};\n\nfunction validatePointOpts<T>(curve: CurvePointsType<T>) {\n const opts = validateBasic(curve);\n ut.validateObject(\n opts,\n {\n a: 'field',\n b: 'field',\n },\n {\n allowedPrivateKeyLengths: 'array',\n wrapPrivateKey: 'boolean',\n isTorsionFree: 'function',\n clearCofactor: 'function',\n allowInfinityPoint: 'boolean',\n fromBytes: 'function',\n toBytes: 'function',\n }\n );\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');\n }\n if (\n typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function'\n ) {\n throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');\n }\n }\n return Object.freeze({ ...opts } as const);\n}\n\nexport type CurvePointsRes<T> = {\n CURVE: ReturnType<typeof validatePointOpts<T>>;\n ProjectivePoint: ProjConstructor<T>;\n normPrivateKeyToScalar: (key: PrivKey) => bigint;\n weierstrassEquation: (x: T) => T;\n isWithinCurveOrder: (num: bigint) => boolean;\n};\n\n// ASN.1 DER encoding utilities\nconst { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;\nexport const DER = {\n // asn.1 DER encoding utils\n Err: class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n },\n _parseInt(data: Uint8Array): { d: bigint; l: Uint8Array } {\n const { Err: E } = DER;\n if (data.length < 2 || data[0] !== 0x02) throw new E('Invalid signature integer tag');\n const len = data[1];\n const res = data.subarray(2, len + 2);\n if (!len || res.length !== len) throw new E('Invalid signature integer: wrong length');\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n if (res[0] & 0b10000000) throw new E('Invalid signature integer: negative');\n if (res[0] === 0x00 && !(res[1] & 0b10000000))\n throw new E('Invalid signature integer: unnecessary leading zero');\n return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left\n },\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint } {\n // parse DER signature\n const { Err: E } = DER;\n const data = typeof hex === 'string' ? h2b(hex) : hex;\n if (!ut.isBytes(data)) throw new Error('ui8a expected');\n let l = data.length;\n if (l < 2 || data[0] != 0x30) throw new E('Invalid signature tag');\n if (data[1] !== l - 2) throw new E('Invalid signature: incorrect length');\n const { d: r, l: sBytes } = DER._parseInt(data.subarray(2));\n const { d: s, l: rBytesLeft } = DER._parseInt(sBytes);\n if (rBytesLeft.length) throw new E('Invalid signature: left bytes after parsing');\n return { r, s };\n },\n hexFromSig(sig: { r: bigint; s: bigint }): string {\n // Add leading zero if first byte has negative bit enabled. More details in '_parseInt'\n const slice = (s: string): string => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s);\n const h = (num: number | bigint) => {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n };\n const s = slice(h(sig.s));\n const r = slice(h(sig.r));\n const shl = s.length / 2;\n const rhl = r.length / 2;\n const sl = h(shl);\n const rl = h(rhl);\n return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`;\n },\n};\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\n\nexport function weierstrassPoints<T>(opts: CurvePointsType<T>): CurvePointsRes<T> {\n const CURVE = validatePointOpts(opts);\n const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ\n\n const toBytes =\n CURVE.toBytes ||\n ((_c: ProjConstructor<T>, point: ProjPointType<T>, _isCompressed: boolean) => {\n const a = point.toAffine();\n return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));\n });\n const fromBytes =\n CURVE.fromBytes ||\n ((bytes: Uint8Array) => {\n // const head = bytes[0];\n const tail = bytes.subarray(1);\n // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n });\n\n /**\n * y\u00B2 = x\u00B3 + ax + b: Short weierstrass curve formula\n * @returns y\u00B2\n */\n function weierstrassEquation(x: T): T {\n const { a, b } = CURVE;\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x2 * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b\n }\n // Validate whether the passed curve params are valid.\n // We check if curve equation works for generator point.\n // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.\n // ProjectivePoint class has not been initialized yet.\n if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))\n throw new Error('bad generator point: equation left != right');\n\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num: bigint): boolean {\n return typeof num === 'bigint' && _0n < num && num < CURVE.n;\n }\n function assertGE(num: bigint) {\n if (!isWithinCurveOrder(num)) throw new Error('Expected valid bigint: 0 < bigint < curve.n');\n }\n // Validates if priv key is valid and converts it to bigint.\n // Supports options allowedPrivateKeyLengths and wrapPrivateKey.\n function normPrivateKeyToScalar(key: PrivKey): bigint {\n const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE;\n if (lengths && typeof key !== 'bigint') {\n if (ut.isBytes(key)) key = ut.bytesToHex(key);\n // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes\n if (typeof key !== 'string' || !lengths.includes(key.length)) throw new Error('Invalid key');\n key = key.padStart(nByteLength * 2, '0');\n }\n let num: bigint;\n try {\n num =\n typeof key === 'bigint'\n ? key\n : ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength));\n } catch (error) {\n throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);\n }\n if (wrapPrivateKey) num = mod.mod(num, n); // disabled by default, enabled for BLS\n assertGE(num); // num in range [1..N-1]\n return num;\n }\n\n const pointPrecomputes = new Map<Point, Point[]>();\n function assertPrjPoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ProjectivePoint expected');\n }\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) \u220B (x=x/z, y=y/z)\n * Default Point works in 2d / affine coordinates: (x, y)\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point implements ProjPointType<T> {\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n\n constructor(\n readonly px: T,\n readonly py: T,\n readonly pz: T\n ) {\n if (px == null || !Fp.isValid(px)) throw new Error('x required');\n if (py == null || !Fp.isValid(py)) throw new Error('y required');\n if (pz == null || !Fp.isValid(pz)) throw new Error('z required');\n }\n\n // Does not validate if the point is on-curve.\n // Use fromHex instead, or call assertValidity() later.\n static fromAffine(p: AffinePoint<T>): Point {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error('invalid affine point');\n if (p instanceof Point) throw new Error('projective point not allowed');\n const is0 = (i: T) => Fp.eql(i, Fp.ZERO);\n // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)\n if (is0(x) && is0(y)) return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n\n get x(): T {\n return this.toAffine().x;\n }\n get y(): T {\n return this.toAffine().y;\n }\n\n /**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\n static normalizeZ(points: Point[]): Point[] {\n const toInv = Fp.invertBatch(points.map((p) => p.pz));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n\n /**\n * Converts hash string or Uint8Array to Point.\n * @param hex short/long ECDSA hex\n */\n static fromHex(hex: Hex): Point {\n const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));\n P.assertValidity();\n return P;\n }\n\n // Multiplies generator point by privateKey.\n static fromPrivateKey(privateKey: PrivKey) {\n return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));\n }\n\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n _WINDOW_SIZE?: number;\n\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize: number) {\n this._WINDOW_SIZE = windowSize;\n pointPrecomputes.delete(this);\n }\n\n // A point on curve is valid if it conforms to equation.\n assertValidity(): void {\n if (this.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is wrong representation of ZERO and is always invalid.\n if (CURVE.allowInfinityPoint && !Fp.is0(this.py)) return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = this.toAffine();\n // Check if x, y are valid field elements\n if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not FE');\n const left = Fp.sqr(y); // y\u00B2\n const right = weierstrassEquation(x); // x\u00B3 + ax + b\n if (!Fp.eql(left, right)) throw new Error('bad point: equation left != right');\n if (!this.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');\n }\n hasEvenY(): boolean {\n const { y } = this.toAffine();\n if (Fp.isOdd) return !Fp.isOdd(y);\n throw new Error(\"Field doesn't support isOdd\");\n }\n\n /**\n * Compare one point to another.\n */\n equals(other: Point): boolean {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n\n /**\n * Flips point to one corresponding to (x, -y) in Affine coordinates.\n */\n negate(): Point {\n return new Point(this.px, Fp.neg(this.py), this.pz);\n }\n\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { px: X1, py: Y1, pz: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other: Point): Point {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n\n subtract(other: Point) {\n return this.add(other.negate());\n }\n\n private is0() {\n return this.equals(Point.ZERO);\n }\n private wNAF(n: bigint): { p: Point; f: Point } {\n return wnaf.wNAFCached(this, pointPrecomputes, n, (comp: Point[]) => {\n const toInv = Fp.invertBatch(comp.map((p) => p.pz));\n return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n });\n }\n\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed private key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(n: bigint): Point {\n const I = Point.ZERO;\n if (n === _0n) return I;\n assertGE(n); // Will throw on 0\n if (n === _1n) return this;\n const { endo } = CURVE;\n if (!endo) return wnaf.unsafeLadder(this, n);\n\n // Apply endomorphism\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n let k1p = I;\n let k2p = I;\n let d: Point = this;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n) k1p = k1p.add(d);\n if (k2 & _1n) k2p = k2p.add(d);\n d = d.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n if (k1neg) k1p = k1p.negate();\n if (k2neg) k2p = k2p.negate();\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n return k1p.add(k2p);\n }\n\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar: bigint): Point {\n assertGE(scalar);\n let n = scalar;\n let point: Point, fake: Point; // Fake point is used to const-time mult\n const { endo } = CURVE;\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n let { p: k1p, f: f1p } = this.wNAF(k1);\n let { p: k2p, f: f2p } = this.wNAF(k2);\n k1p = wnaf.constTimeNegate(k1neg, k1p);\n k2p = wnaf.constTimeNegate(k2neg, k2p);\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n point = k1p.add(k2p);\n fake = f1p.add(f2p);\n } else {\n const { p, f } = this.wNAF(n);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return Point.normalizeZ([point, fake])[0];\n }\n\n /**\n * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.\n * Not using Strauss-Shamir trick: precomputation tables are faster.\n * The trick could be useful if both P and Q are not G (not in our case).\n * @returns non-zero affine point\n */\n multiplyAndAddUnsafe(Q: Point, a: bigint, b: bigint): Point | undefined {\n const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes\n const mul = (\n P: Point,\n a: bigint // Select faster multiply() method\n ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));\n const sum = mul(this, a).add(mul(Q, b));\n return sum.is0() ? undefined : sum;\n }\n\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) \u220B (x=x/z, y=y/z)\n toAffine(iz?: T): AffinePoint<T> {\n const { px: x, py: y, pz: z } = this;\n const is0 = this.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(z);\n const ax = Fp.mul(x, iz);\n const ay = Fp.mul(y, iz);\n const zz = Fp.mul(z, iz);\n if (is0) return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE)) throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n }\n isTorsionFree(): boolean {\n const { h: cofactor, isTorsionFree } = CURVE;\n if (cofactor === _1n) return true; // No subgroups, always torsion-free\n if (isTorsionFree) return isTorsionFree(Point, this);\n throw new Error('isTorsionFree() has not been declared for the elliptic curve');\n }\n clearCofactor(): Point {\n const { h: cofactor, clearCofactor } = CURVE;\n if (cofactor === _1n) return this; // Fast-path\n if (clearCofactor) return clearCofactor(Point, this) as Point;\n return this.multiplyUnsafe(CURVE.h);\n }\n\n toRawBytes(isCompressed = true): Uint8Array {\n this.assertValidity();\n return toBytes(Point, this, isCompressed);\n }\n\n toHex(isCompressed = true): string {\n return ut.bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n const _bits = CURVE.nBitLength;\n const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);\n // Validate if generator point is on curve\n return {\n CURVE,\n ProjectivePoint: Point as ProjConstructor<T>,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n };\n}\n\n// Instance\nexport interface SignatureType {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n assertValidity(): void;\n addRecoveryBit(recovery: number): RecoveredSignatureType;\n hasHighS(): boolean;\n normalizeS(): SignatureType;\n recoverPublicKey(msgHash: Hex): ProjPointType<bigint>;\n toCompactRawBytes(): Uint8Array;\n toCompactHex(): string;\n // DER-encoded\n toDERRawBytes(isCompressed?: boolean): Uint8Array;\n toDERHex(isCompressed?: boolean): string;\n}\nexport type RecoveredSignatureType = SignatureType & {\n readonly recovery: number;\n};\n// Static methods\nexport type SignatureConstructor = {\n new (r: bigint, s: bigint): SignatureType;\n fromCompact(hex: Hex): SignatureType;\n fromDER(hex: Hex): SignatureType;\n};\ntype SignatureLike = { r: bigint; s: bigint };\n\nexport type PubKey = Hex | ProjPointType<bigint>;\n\nexport type CurveType = BasicWCurve<bigint> & {\n hash: CHash; // CHash not FHash because we need outputLen for DRBG\n hmac: HmacFnSync;\n randomBytes: (bytesLength?: number) => Uint8Array;\n lowS?: boolean;\n bits2int?: (bytes: Uint8Array) => bigint;\n bits2int_modN?: (bytes: Uint8Array) => bigint;\n};\n\nfunction validateOpts(curve: CurveType) {\n const opts = validateBasic(curve);\n ut.validateObject(\n opts,\n {\n hash: 'hash',\n hmac: 'function',\n randomBytes: 'function',\n },\n {\n bits2int: 'function',\n bits2int_modN: 'function',\n lowS: 'boolean',\n }\n );\n return Object.freeze({ lowS: true, ...opts } as const);\n}\n\nexport type CurveFn = {\n CURVE: ReturnType<typeof validateOpts>;\n getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array;\n getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean) => Uint8Array;\n sign: (msgHash: Hex, privKey: PrivKey, opts?: SignOpts) => RecoveredSignatureType;\n verify: (signature: Hex | SignatureLike, msgHash: Hex, publicKey: Hex, opts?: VerOpts) => boolean;\n ProjectivePoint: ProjConstructor<bigint>;\n Signature: SignatureConstructor;\n utils: {\n normPrivateKeyToScalar: (key: PrivKey) => bigint;\n isValidPrivateKey(privateKey: PrivKey): boolean;\n randomPrivateKey: () => Uint8Array;\n precompute: (windowSize?: number, point?: ProjPointType<bigint>) => ProjPointType<bigint>;\n };\n};\n\nexport function weierstrass(curveDef: CurveType): CurveFn {\n const CURVE = validateOpts(curveDef) as ReturnType<typeof validateOpts>;\n const { Fp, n: CURVE_ORDER } = CURVE;\n const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32\n const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32\n\n function isValidFieldElement(num: bigint): boolean {\n return _0n < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE\n }\n function modN(a: bigint) {\n return mod.mod(a, CURVE_ORDER);\n }\n function invN(a: bigint) {\n return mod.invert(a, CURVE_ORDER);\n }\n\n const {\n ProjectivePoint: Point,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n } = weierstrassPoints({\n ...CURVE,\n toBytes(_c, point, isCompressed: boolean): Uint8Array {\n const a = point.toAffine();\n const x = Fp.toBytes(a.x);\n const cat = ut.concatBytes;\n if (isCompressed) {\n return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);\n } else {\n return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));\n }\n },\n fromBytes(bytes: Uint8Array) {\n const len = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // this.assertValidity() is done inside of fromHex\n if (len === compressedLen && (head === 0x02 || head === 0x03)) {\n const x = ut.bytesToNumberBE(tail);\n if (!isValidFieldElement(x)) throw new Error('Point is not on curve');\n const y2 = weierstrassEquation(x); // y\u00B2 = x\u00B3 + ax + b\n let y = Fp.sqrt(y2); // y = y\u00B2 ^ (p+1)/4\n const isYOdd = (y & _1n) === _1n;\n // ECDSA\n const isHeadOdd = (head & 1) === 1;\n if (isHeadOdd !== isYOdd) y = Fp.neg(y);\n return { x, y };\n } else if (len === uncompressedLen && head === 0x04) {\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n } else {\n throw new Error(\n `Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`\n );\n }\n },\n });\n const numToNByteStr = (num: bigint): string =>\n ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength));\n\n function isBiggerThanHalfOrder(number: bigint) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n\n function normalizeS(s: bigint) {\n return isBiggerThanHalfOrder(s) ? modN(-s) : s;\n }\n // slice bytes num\n const slcNum = (b: Uint8Array, from: number, to: number) => ut.bytesToNumberBE(b.slice(from, to));\n\n /**\n * ECDSA signature with its (r, s) properties. Supports DER & compact representations.\n */\n class Signature implements SignatureType {\n constructor(\n readonly r: bigint,\n readonly s: bigint,\n readonly recovery?: number\n ) {\n this.assertValidity();\n }\n\n // pair (bytes of r, bytes of s)\n static fromCompact(hex: Hex) {\n const l = CURVE.nByteLength;\n hex = ensureBytes('compactSignature', hex, l * 2);\n return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));\n }\n\n // DER encoded ECDSA signature\n // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script\n static fromDER(hex: Hex) {\n const { r, s } = DER.toSig(ensureBytes('DER', hex));\n return new Signature(r, s);\n }\n\n assertValidity(): void {\n // can use assertGE here\n if (!isWithinCurveOrder(this.r)) throw new Error('r must be 0 < r < CURVE.n');\n if (!isWithinCurveOrder(this.s)) throw new Error('s must be 0 < s < CURVE.n');\n }\n\n addRecoveryBit(recovery: number): RecoveredSignature {\n return new Signature(this.r, this.s, recovery) as RecoveredSignature;\n }\n\n recoverPublicKey(msgHash: Hex): typeof Point.BASE {\n const { r, s, recovery: rec } = this;\n const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash\n if (rec == null || ![0, 1, 2, 3].includes(rec)) throw new Error('recovery id invalid');\n const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;\n if (radj >= Fp.ORDER) throw new Error('recovery id 2 or 3 invalid');\n const prefix = (rec & 1) === 0 ? '02' : '03';\n const R = Point.fromHex(prefix + numToNByteStr(radj));\n const ir = invN(radj); // r^-1\n const u1 = modN(-h * ir); // -hr^-1\n const u2 = modN(s * ir); // sr^-1\n const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n if (!Q) throw new Error('point at infinify'); // unsafe is fine: no priv data leaked\n Q.assertValidity();\n return Q;\n }\n\n // Signatures should be low-s, to prevent malleability.\n hasHighS(): boolean {\n return isBiggerThanHalfOrder(this.s);\n }\n\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;\n }\n\n // DER-encoded\n toDERRawBytes() {\n return ut.hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig({ r: this.r, s: this.s });\n }\n\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return ut.hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n return numToNByteStr(this.r) + numToNByteStr(this.s);\n }\n }\n type RecoveredSignature = Signature & { recovery: number };\n\n const utils = {\n isValidPrivateKey(privateKey: PrivKey) {\n try {\n normPrivateKeyToScalar(privateKey);\n return true;\n } catch (error) {\n return false;\n }\n },\n normPrivateKeyToScalar: normPrivateKeyToScalar,\n\n /**\n * Produces cryptographically secure private key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n randomPrivateKey: (): Uint8Array => {\n const length = mod.getMinHashLength(CURVE.n);\n return mod.mapHashToField(CURVE.randomBytes(length), CURVE.n);\n },\n\n /**\n * Creates precompute table for an arbitrary EC point. Makes point \"cached\".\n * Allows to massively speed-up `point.multiply(scalar)`.\n * @returns cached point\n * @example\n * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));\n * fast.multiply(privKey); // much faster ECDH now\n */\n precompute(windowSize = 8, point = Point.BASE): typeof Point.BASE {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here\n return point;\n },\n };\n\n /**\n * Computes public key for a private key. Checks for validity of the private key.\n * @param privateKey private key\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(privateKey: PrivKey, isCompressed = true): Uint8Array {\n return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n }\n\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item: PrivKey | PubKey): boolean {\n const arr = ut.isBytes(item);\n const str = typeof item === 'string';\n const len = (arr || str) && (item as Hex).length;\n if (arr) return len === compressedLen || len === uncompressedLen;\n if (str) return len === 2 * compressedLen || len === 2 * uncompressedLen;\n if (item instanceof Point) return true;\n return false;\n }\n\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from private key and public key.\n * Checks: 1) private key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param privateA private key\n * @param publicB different public key\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(privateA: PrivKey, publicB: Hex, isCompressed = true): Uint8Array {\n if (isProbPub(privateA)) throw new Error('first arg must be private key');\n if (!isProbPub(publicB)) throw new Error('second arg must be public key');\n const b = Point.fromHex(publicB); // check for being on-curve\n return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);\n }\n\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int =\n CURVE.bits2int ||\n function (bytes: Uint8Array): bigint {\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = ut.bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN =\n CURVE.bits2int_modN ||\n function (bytes: Uint8Array): bigint {\n return modN(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // NOTE: pads output with zero as per spec\n const ORDER_MASK = ut.bitMask(CURVE.nBitLength);\n /**\n * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.\n */\n function int2octets(num: bigint): Uint8Array {\n if (typeof num !== 'bigint') throw new Error('bigint expected');\n if (!(_0n <= num && num < ORDER_MASK))\n throw new Error(`bigint expected < 2^${CURVE.nBitLength}`);\n // works with order, can have different size than numToField!\n return ut.numberToBytesBE(num, CURVE.nByteLength);\n }\n\n // Steps A, D of RFC6979 3.2\n // Creates RFC6979 seed; converts msg/privKey to numbers.\n // Used only in sign, not in verify.\n // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.\n // Also it can be bigger for P224 + SHA256\n function prepSig(msgHash: Hex, privateKey: PrivKey, opts = defaultSigOpts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { hash, randomBytes } = CURVE;\n let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default\n if (lowS == null) lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash\n msgHash = ensureBytes('msgHash', msgHash);\n if (prehash) msgHash = ensureBytes('prehashed msgHash', hash(msgHash));\n\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(msgHash);\n const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (ent != null) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is\n seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n }\n const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n function k2sig(kBytes: Uint8Array): RecoveredSignature | undefined {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!isWithinCurveOrder(k)) return; // Important: all mod() calls here must be done over N\n const ik = invN(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = Gk\n const r = modN(q.x); // r = q.x mod n\n if (r === _0n) return;\n // Can use scalar blinding b^-1(bm + bdr) where b \u2208 [1,q\u22121] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n const s = modN(ik * modN(m + r * d)); // Not using blinding here\n if (s === _0n) return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = normalizeS(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery) as RecoveredSignature; // use normS, not s\n }\n return { seed, k2sig };\n }\n const defaultSigOpts: SignOpts = { lowS: CURVE.lowS, prehash: false };\n const defaultVerOpts: VerOpts = { lowS: CURVE.lowS, prehash: false };\n\n /**\n * Signs message hash with a private key.\n * ```\n * sign(m, d, k) where\n * (x, y) = G \u00D7 k\n * r = x mod n\n * s = (m + dr)/k mod n\n * ```\n * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.\n * @param privKey private key\n * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.\n * @returns signature with recovery param\n */\n function sign(msgHash: Hex, privKey: PrivKey, opts = defaultSigOpts): RecoveredSignature {\n const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.\n const C = CURVE;\n const drbg = ut.createHmacDrbg<RecoveredSignature>(C.hash.outputLen, C.nByteLength, C.hmac);\n return drbg(seed, k2sig); // Steps B, C, D, E, F, G\n }\n\n // Enable precomputes. Slows down first publicKey computation by 20ms.\n Point.BASE._setWindowSize(8);\n // utils.precompute(8, ProjectivePoint.BASE)\n\n /**\n * Verifies a signature against message hash and public key.\n * Rejects lowS signatures by default: to override,\n * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * U1 = hs^-1 mod n\n * U2 = rs^-1 mod n\n * R = U1\u22C5G - U2\u22C5P\n * mod(R.x, n) == r\n * ```\n */\n function verify(\n signature: Hex | SignatureLike,\n msgHash: Hex,\n publicKey: Hex,\n opts = defaultVerOpts\n ): boolean {\n const sg = signature;\n msgHash = ensureBytes('msgHash', msgHash);\n publicKey = ensureBytes('publicKey', publicKey);\n if ('strict' in opts) throw new Error('options.strict was renamed to lowS');\n const { lowS, prehash } = opts;\n\n let _sig: Signature | undefined = undefined;\n let P: ProjPointType<bigint>;\n try {\n if (typeof sg === 'string' || ut.isBytes(sg)) {\n // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).\n // Since DER can also be 2*nByteLength bytes, we check for it first.\n try {\n _sig = Signature.fromDER(sg);\n } catch (derError) {\n if (!(derError instanceof DER.Err)) throw derError;\n _sig = Signature.fromCompact(sg);\n }\n } else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {\n const { r, s } = sg;\n _sig = new Signature(r, s);\n } else {\n throw new Error('PARSE');\n }\n P = Point.fromHex(publicKey);\n } catch (error) {\n if ((error as Error).message === 'PARSE')\n throw new Error(`signature must be Signature instance, Uint8Array or hex string`);\n return false;\n }\n if (lowS && _sig.hasHighS()) return false;\n if (prehash) msgHash = CURVE.hash(msgHash);\n const { r, s } = _sig;\n const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element\n const is = invN(s); // s^-1\n const u1 = modN(h * is); // u1 = hs^-1 mod n\n const u2 = modN(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1\u22C5G + u2\u22C5P\n if (!R) return false;\n const v = modN(R.x);\n return v === r;\n }\n return {\n CURVE,\n getPublicKey,\n getSharedSecret,\n sign,\n verify,\n ProjectivePoint: Point,\n Signature,\n utils,\n };\n}\n\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio<T>(Fp: mod.IField<T>, Z: T) {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n) l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u: T, v: T): { isValid: boolean; value: T } => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u: T, v: T) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU<T>(\n Fp: mod.IField<T>,\n opts: {\n A: T;\n B: T;\n Z: T;\n }\n) {\n mod.validateField(Fp);\n if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);\n if (!Fp.isOdd) throw new Error('Fp.isOdd is not implemented!');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u: T): { x: T; y: T } => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd!(u) === Fp.isOdd!(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n x = Fp.div(x, tv4); // 25. x = x / tv4\n return { x, y };\n };\n}\n", "import { hash as assertHash, bytes as assertBytes, exists as assertExists } from './_assert.js';\nimport { Hash, CHash, Input, toBytes } from './utils.js';\n// HMAC (RFC 2104)\nexport class HMAC<T extends Hash<T>> extends Hash<HMAC<T>> {\n oHash: T;\n iHash: T;\n blockLen: number;\n outputLen: number;\n private finished = false;\n private destroyed = false;\n\n constructor(hash: CHash, _key: Input) {\n super();\n assertHash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create() as T;\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create() as T;\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n pad.fill(0);\n }\n update(buf: Input) {\n assertExists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array) {\n assertExists(this);\n assertBytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to?: HMAC<T>): HMAC<T> {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to as this;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n */\nexport const hmac = (hash: CHash, key: Input, message: Input): Uint8Array =>\n new HMAC<any>(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Input) => new HMAC<any>(hash, key);\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac';\nimport { concatBytes, randomBytes } from '@noble/hashes/utils';\nimport { weierstrass, CurveType } from './abstract/weierstrass.js';\nimport { CHash } from './abstract/utils.js';\n\n// connects noble-curves to noble-hashes\nexport function getHash(hash: CHash) {\n return {\n hash,\n hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => hmac(hash, key, concatBytes(...msgs)),\n randomBytes,\n };\n}\n// Same API as @noble/hashes, with ability to create curve with custom hash\ntype CurveDef = Readonly<Omit<CurveType, 'hash' | 'hmac' | 'randomBytes'>>;\nexport function createCurve(curveDef: CurveDef, defHash: CHash) {\n const create = (hash: CHash) => weierstrass({ ...curveDef, ...getHash(hash) });\n return Object.freeze({ ...create(defHash), create });\n}\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha256';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { Field, mod, pow2 } from './abstract/modular.js';\nimport { ProjPointType as PointType, mapToCurveSimpleSWU } from './abstract/weierstrass.js';\nimport type { Hex, PrivKey } from './abstract/utils.js';\nimport { bytesToNumberBE, concatBytes, ensureBytes, numberToBytesBE } from './abstract/utils.js';\nimport { createHasher, isogenyMap } from './abstract/hash-to-curve.js';\nimport { createCurve } from './_shortw_utils.js';\n\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst divNearest = (a: bigint, b: bigint) => (a + b / _2n) / b;\n\n/**\n * \u221An = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y: bigint): bigint {\n const P = secp256k1P;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fp.eql(Fp.sqr(root), y)) throw new Error('Cannot find square root');\n return root;\n}\n\nconst Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });\n\nexport const secp256k1 = createCurve(\n {\n a: BigInt(0), // equation params: a, b\n b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975\n Fp, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n\n n: secp256k1N, // Curve order, total count of valid points in the field\n // Base point (x, y) aka generator point\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1), // Cofactor\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n /**\n * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066\n */\n endo: {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n splitScalar: (k: bigint) => {\n const n = secp256k1N;\n const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n const b2 = a1;\n const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)\n\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n let k1 = mod(k - c1 * a1 - c2 * a2, n);\n let k2 = mod(-c1 * b1 - c2 * b2, n);\n const k1neg = k1 > POW_2_128;\n const k2neg = k2 > POW_2_128;\n if (k1neg) k1 = n - k1;\n if (k2neg) k2 = n - k2;\n if (k1 > POW_2_128 || k2 > POW_2_128) {\n throw new Error('splitScalar: Endomorphism failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n },\n },\n },\n sha256\n);\n\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\nconst _0n = BigInt(0);\nconst fe = (x: bigint) => typeof x === 'bigint' && _0n < x && x < secp256k1P;\nconst ge = (x: bigint) => typeof x === 'bigint' && _0n < x && x < secp256k1N;\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES: { [tag: string]: Uint8Array } = {};\nfunction taggedHash(tag: string, ...messages: Uint8Array[]): Uint8Array {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point: PointType<bigint>) => point.toRawBytes(true).slice(1);\nconst numTo32b = (n: bigint) => numberToBytesBE(n, 32);\nconst modP = (x: bigint) => mod(x, secp256k1P);\nconst modN = (x: bigint) => mod(x, secp256k1N);\nconst Point = secp256k1.ProjectivePoint;\nconst GmulAdd = (Q: PointType<bigint>, a: bigint, b: bigint) =>\n Point.BASE.multiplyAndAddUnsafe(Q, a, b);\n\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv: PrivKey) {\n let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey\n let p = Point.fromPrivateKey(d_); // P = d'\u22C5G; 0 < d' < n check is done inside\n const scalar = p.hasEvenY() ? d_ : modN(-d_);\n return { scalar: scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x: bigint): PointType<bigint> {\n if (!fe(x)) throw new Error('bad x: need 0 < x < p'); // Fail if x \u2265 p.\n const xx = modP(x * x);\n const c = modP(xx * x + BigInt(7)); // Let c = x\u00B3 + 7 mod p.\n let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p.\n if (y % _2n !== _0n) y = modP(-y); // Return the unique point P such that x(P) = x and\n const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n p.assertValidity();\n return p;\n}\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args: Uint8Array[]): bigint {\n return modN(bytesToNumberBE(taggedHash('BIP0340/challenge', ...args)));\n}\n\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(privateKey: Hex): Uint8Array {\n return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'\u2265n. Ret bytes(d'\u22C5G)\n}\n\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(\n message: Hex,\n privateKey: PrivKey,\n auxRand: Hex = randomBytes(32)\n): Uint8Array {\n const m = ensureBytes('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder\n const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = numTo32b(d ^ bytesToNumberBE(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n const k_ = modN(bytesToNumberBE(rand)); // Let k' = int(rand) mod n\n if (k_ === _0n) throw new Error('sign failed: k is zero'); // Fail if k' = 0.\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'\u22C5G.\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(numTo32b(modN(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px)) throw new Error('sign: Invalid signature produced');\n return sig;\n}\n\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature: Hex, message: Hex, publicKey: Hex): boolean {\n const sig = ensureBytes('signature', signature, 64);\n const m = ensureBytes('message', message);\n const pub = ensureBytes('publicKey', publicKey, 32);\n try {\n const P = lift_x(bytesToNumberBE(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = bytesToNumberBE(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r \u2265 p.\n if (!fe(r)) return false;\n const s = bytesToNumberBE(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s \u2265 n.\n if (!ge(s)) return false;\n const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n const R = GmulAdd(P, s, modN(-e)); // R = s\u22C5G - e\u22C5P\n if (!R || !R.hasEvenY() || R.toAffine().x !== r) return false; // -eP == (n-e)P\n return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) \u2260 r.\n } catch (error) {\n return false;\n }\n}\n\nexport const schnorr = /* @__PURE__ */ (() => ({\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n utils: {\n randomPrivateKey: secp256k1.utils.randomPrivateKey,\n lift_x,\n pointToBytes,\n numberToBytesBE,\n bytesToNumberBE,\n taggedHash,\n mod,\n },\n}))();\n\nconst isoMap = /* @__PURE__ */ (() =>\n isogenyMap(\n Fp,\n [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n ].map((i) => i.map((j) => BigInt(j))) as [bigint[], bigint[], bigint[], bigint[]]\n ))();\nconst mapSWU = /* @__PURE__ */ (() =>\n mapToCurveSimpleSWU(Fp, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fp.create(BigInt('-11')),\n }))();\nconst htf = /* @__PURE__ */ (() =>\n createHasher(\n secp256k1.ProjectivePoint,\n (scalars: bigint[]) => {\n const { x, y } = mapSWU(Fp.create(scalars[0]));\n return isoMap(x, y);\n },\n {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n }\n ))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n", "function number(n: number) {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error(`positive integer expected, not ${n}`);\n}\n\nfunction bool(b: boolean) {\n if (typeof b !== 'boolean') throw new Error(`boolean expected, not ${b}`);\n}\n\n// copied from utils\nexport function isBytes(a: unknown): a is Uint8Array {\n return (\n a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')\n );\n}\n\nfunction bytes(b: Uint8Array | undefined, ...lengths: number[]) {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);\n}\n\ntype Hash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\nfunction hash(h: Hash) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(h.outputLen);\n number(h.blockLen);\n}\n\nfunction exists(instance: any, checkFinished = true) {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\nfunction output(out: any, instance: any) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\n\nexport { number, bool, bytes, hash, exists, output };\n\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n", "// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// See utils.ts for details.\ndeclare const globalThis: Record<string, any> | undefined;\nexport const crypto =\n typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n", "/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nimport { bytes as abytes } from './_assert.js';\n// export { isBytes } from './_assert.js';\n// We can't reuse isBytes from _assert, because somehow this causes huge perf issues\nexport function isBytes(a: unknown): a is Uint8Array {\n return (\n a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')\n );\n}\n\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n// Cast array to different type\nexport const u8 = (arr: TypedArray) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr: TypedArray) =>\n new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n\n// Cast array to view\nexport const createView = (arr: TypedArray) =>\n new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word: number, shift: number) => (word << (32 - shift)) | (word >>> shift);\n// The rotate left (circular left shift) operation for uint32\nexport const rotl = (word: number, shift: number) =>\n (word << shift) | ((word >>> (32 - shift)) >>> 0);\n\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\n// The byte swap operation for uint32\nexport const byteSwap = (word: number) =>\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n// Conditionally byte swap if on a big-endian platform\nexport const byteSwapIfBE = isLE ? (n: number) => n : (n: number) => byteSwap(n);\n\n// In place byte swap for Uint32Array\nexport function byteSwap32(arr: Uint32Array) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n}\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 } as const;\nfunction asciiToBase16(char: number): number | undefined {\n if (char >= asciis._0 && char <= asciis._9) return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F) return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f) return char - (asciis._a - 10);\n return;\n}\n\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => {};\n\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters: number, tick: number, cb: (i: number) => void) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\nexport type Input = Uint8Array | string;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\n// For runtime check if class implements interface\nexport abstract class Hash<T extends Hash<T>> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n /**\n * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n * when no options are passed.\n * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n * There are no guarantees for clean-up because it's impossible in JS.\n */\n abstract _cloneInto(to?: T): T;\n // Safe version that clones internal state\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\nconst toStr = {}.toString;\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\nexport type CHash = ReturnType<typeof wrapConstructor>;\n\nexport function wrapConstructor<T extends Hash<T>>(hashCons: () => Hash<T>) {\n const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n\nexport function wrapConstructorWithOpts<H extends Hash<H>, T extends Object>(\n hashCons: (opts?: T) => Hash<H>\n) {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts: T) => hashCons(opts);\n return hashC;\n}\n\nexport function wrapXOFConstructorWithOpts<H extends HashXOF<H>, T extends Object>(\n hashCons: (opts?: T) => HashXOF<H>\n) {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts: T) => hashCons(opts);\n return hashC;\n}\n\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n", "import { exists, output } from './_assert.js';\nimport { Hash, createView, Input, toBytes } from './utils.js';\n\n// Polyfill for Safari 14\nfunction setBigUint64(view: DataView, byteOffset: number, value: bigint, isLE: boolean): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n// Choice: a ? b : c\nexport const Chi = (a: number, b: number, c: number) => (a & b) ^ (~a & c);\n// Majority function, true if any two inpust is true\nexport const Maj = (a: number, b: number, c: number) => (a & b) ^ (a & c) ^ (b & c);\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD<T extends HashMD<T>> extends Hash<T> {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(\n readonly blockLen: number,\n public outputLen: number,\n readonly padOffset: number,\n readonly isLE: boolean\n ) {\n super();\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n exists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array) {\n exists(this);\n output(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n}\n", "import { HashMD, Chi, Maj } from './_md.js';\nimport { rotr, wrapConstructor } from './utils.js';\n\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^67 hashes/sec as per early 2023.\n\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n// Initial state:\n// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19\n// prettier-ignore\nconst SHA256_IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nclass SHA256 extends HashMD<SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n A = SHA256_IV[0] | 0;\n B = SHA256_IV[1] | 0;\n C = SHA256_IV[2] | 0;\n D = SHA256_IV[3] | 0;\n E = SHA256_IV[4] | 0;\n F = SHA256_IV[5] | 0;\n G = SHA256_IV[6] | 0;\n H = SHA256_IV[7] | 0;\n\n constructor() {\n super(64, 32, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n A = 0xc1059ed8 | 0;\n B = 0x367cd507 | 0;\n C = 0x3070dd17 | 0;\n D = 0xf70e5939 | 0;\n E = 0xffc00b31 | 0;\n F = 0x68581511 | 0;\n G = 0x64f98fa7 | 0;\n H = 0xbefa4fa4 | 0;\n constructor() {\n super();\n this.outputLen = 28;\n }\n}\n\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexport const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());\nexport const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n", "/**\n * Canonicalizes a given object according to RFC 8785 (https://tools.ietf.org/html/rfc8785),\n * which describes JSON Canonicalization Scheme (JCS). This function sorts the keys of the\n * object and its nested objects alphabetically and then returns a stringified version of it.\n * This method handles nested objects, array values, and null values appropriately.\n *\n * @param obj - The object to canonicalize.\n * @returns The stringified version of the input object with its keys sorted alphabetically\n * per RFC 8785.\n */\nexport function canonicalize(obj: { [key: string]: any }): string {\n /**\n * Recursively sorts the keys of an object.\n *\n * @param obj - The object whose keys are to be sorted.\n * @returns A new object with sorted keys.\n */\n const sortObjKeys = (obj: { [key: string]: any }): { [key: string]: any } => {\n if (obj !== null && typeof obj === 'object' && !Array.isArray(obj)) {\n const sortedKeys = Object.keys(obj).sort();\n const sortedObj: { [key: string]: any } = {};\n for (const key of sortedKeys) {\n // Recursively sort keys of nested objects.\n sortedObj[key] = sortObjKeys(obj[key]);\n }\n return sortedObj;\n }\n return obj;\n };\n\n // Stringify and return the final sorted object.\n const sortedObj = sortObjKeys(obj);\n return JSON.stringify(sortedObj);\n}", "import { sha256 } from '@noble/hashes/sha256';\n\n/**\n * The `Sha256` class provides an interface for generating SHA-256 hash digests.\n *\n * This class utilizes the '@noble/hashes/sha256' function to generate hash digests\n * of the provided data. The SHA-256 algorithm is widely used in cryptographic\n * applications to produce a fixed-size 256-bit (32-byte) hash.\n *\n * The methods of this class are asynchronous and return Promises. They use the Uint8Array\n * type for input data and the resulting digest, ensuring a consistent interface\n * for binary data processing.\n *\n * @example\n * ```ts\n * const data = new Uint8Array([...]);\n * const hash = await Sha256.digest({ data });\n * ```\n */\nexport class Sha256 {\n /**\n * Generates a SHA-256 hash digest for the given data.\n *\n * @remarks\n * This method produces a hash digest using the SHA-256 algorithm. The resultant digest\n * is deterministic, meaning the same data will always produce the same hash, but\n * is computationally infeasible to regenerate the original data from the hash.\n *\n * @example\n * ```ts\n * const data = new Uint8Array([...]);\n * const hash = await Sha256.digest({ data });\n * ```\n *\n * @param params - The parameters for the hashing operation.\n * @param params.data - The data to hash, represented as a Uint8Array.\n *\n * @returns A Promise that resolves to the SHA-256 hash digest of the provided data as a Uint8Array.\n */\n public static async digest({ data }: {\n data: Uint8Array;\n }): Promise<Uint8Array> {\n const hash = sha256(data);\n\n return hash;\n }\n}", "import { Convert, removeUndefinedProperties } from '@enbox/common';\n\nimport { canonicalize } from './utils.js';\nimport { Sha256 } from '../primitives/sha256.js';\n\n/**\n * Constant defining the prefix for JSON Web Keys (JWK) key URIs in this library.\n *\n * The prefix 'urn:jwk:' makes it explicit that a string represents a JWK, referenced by a\n * {@link https://datatracker.ietf.org/doc/html/rfc3986 | URI} (Uniform Resource Identifier),\n * which ensures consistent key referencing across all Web5 Key Management System (KMS)\n * implementations.\n *\n * These key URIs take the form `urn:jwk:<JWK thumbprint>`, where the\n * {@link https://datatracker.ietf.org/doc/html/rfc7638 | JWK thumbprint}, derived from the JWK, is\n * unique to the key's material, unaffected by the order or optional properties in the JWK.\n */\nexport const KEY_URI_PREFIX_JWK = 'urn:jwk:';\n\n/**\n * JSON Web Key Operations\n *\n * The \"key_ops\" (key operations) parameter identifies the operation(s)\n * for which the key is intended to be used. The \"key_ops\" parameter is\n * intended for use cases in which public, private, or symmetric keys\n * may be present.\n *\n * Its value is an array of key operation values. Values defined by\n * {@link https://www.rfc-editor.org/rfc/rfc7517.html#section-4.3 | RFC 7517 Section 4.3} are:\n *\n * - \"decrypt\" : Decrypt content and validate decryption, if applicable\n * - \"deriveBits\" : Derive bits not to be used as a key\n * - \"deriveKey\" : Derive key\n * - \"encrypt\" : Encrypt content\n * - \"sign\" : Compute digital signature or MAC\n * - \"unwrapKey\" : Decrypt key and validate decryption, if applicable\n * - \"verify\" : Verify digital signature or MAC\n * - \"wrapKey\" : Encrypt key\n *\n * Other values MAY be used. The key operation values are case-\n * sensitive strings. Duplicate key operation values MUST NOT be\n * present in the array. Use of the \"key_ops\" member is OPTIONAL,\n * unless the application requires its presence.\n *\n * The \"use\" and \"key_ops\" JWK members SHOULD NOT be used together;\n * however, if both are used, the information they convey MUST be\n * consistent. Applications should specify which of these members they\n * use, if either is to be used by the application.\n */\nexport type JwkOperation = 'encrypt' | 'decrypt' | 'sign' | 'verify' | 'deriveKey' | 'deriveBits' | 'wrapKey' | 'unwrapKey';\n\n/**\n * JSON Web Key Use\n *\n * The \"use\" (public key use) parameter identifies the intended use of\n * the public key. The \"use\" parameter is employed to indicate whether\n * a public key is used for encrypting data or verifying the signature\n * on data.\n *\n * Values defined by {@link https://datatracker.ietf.org/doc/html/rfc7517#section-4.2 | RFC 7517 Section 4.2} are:\n *\n * - \"sig\" (signature)\n * - \"enc\" (encryption)\n *\n * Other values MAY be used. The \"use\" value is a case-sensitive\n * string. Use of the \"use\" member is OPTIONAL, unless the application\n * requires its presence.\n *\n * The \"use\" and \"key_ops\" JWK members SHOULD NOT be used together;\n * however, if both are used, the information they convey MUST be\n * consistent. Applications should specify which of these members they\n * use, if either is to be used by the application.\n *\n * When a key is used to wrap another key and a public key use\n * designation for the first key is desired, the \"enc\" (encryption) key\n * use value is used, since key wrapping is a kind of encryption. The\n * \"enc\" value is also to be used for public keys used for key agreement\n * operations.\n */\nexport type JwkUse = 'sig' | 'enc' | string;\n\n/**\n * JSON Web Key Types\n */\nexport type JwkType =\n /**\n * Elliptic Curve\n * Used with Elliptic Curve Digital Signature Algorithm (ECDSA) and Elliptic\n * Curve Diffie-Hellman (ECDH), including secp256k1, P-256, P-384, and P-521.\n */\n | 'EC'\n /**\n * RSA\n * Widely used for encryption and digital signatures. RSA keys are used in\n * various algorithms like RS256, RS384, RS512, etc.\n */\n | 'RSA'\n /**\n * Octet sequence\n * Used with symmetric signing (e.g., HMAC HS256, HS512, etc.) and\n * symmetric encryption (e.g., A256CBC-HS512, A256GCM, etc.) algorithms.\n */\n | 'oct'\n /**\n * Octet string key pairs (OKP)\n * A type of public key that is used with algorithms such as EdDSA (Ed25519 and\n * Ed448 curves) and ECDH (X25519 and X448 curves).\n */\n | 'OKP';\n\n/**\n * JSON Web Key Elliptic Curve\n */\nexport type JwkNamedCurves =\n // P-256 Curve\n | 'P-256'\n // P-384 Curve\n | 'P-384'\n // P-521 Curve\n | 'P-521'\n // Ed25519 signature algorithm key pairs\n | 'Ed25519'\n // Ed448 signature algorithm key pairs\n | 'Ed448'\n // X25519 function key pairs\n | 'X25519'\n // X448 function key pairs\n | 'X448'\n // SECG secp256k1 curve\n | 'secp256k1';\n\n/**\n * JSON Web Key Parameters\n */\n\n/** Parameters used with any \"kty\" (key type) value. */\nexport type JwkParamsAnyKeyType = {\n /** JWK Algorithm Parameter. The algorithm intended for use with the key. */\n alg?: string;\n /** JWK Extractable Parameter */\n ext?: 'true' | 'false';\n /** JWK Key Operations Parameter */\n key_ops?: JwkOperation[];\n /** JWK Key ID Parameter */\n kid?: string;\n /** JWK Key Type Parameter */\n kty: JwkType;\n /** JWK Public Key Use Parameter */\n use?: JwkUse;\n /** JWK X.509 Certificate Chain Parameter */\n x5c?: string;\n /** JWK X.509 Certificate SHA-1 Thumbprint Parameter */\n x5t?: string;\n /** JWK X.509 Certificate SHA-256 Thumbprint Parameter */\n 'x5t#S256'?: string;\n /** JWK X.509 URL Parameter */\n x5u?: string;\n};\n\n/** Parameters used with \"EC\" (elliptic curve) public keys. */\nexport type JwkParamsEcPublic = Omit<JwkParamsAnyKeyType, 'alg' | 'kty'> & {\n /**\n * The algorithm intended for use with the key.\n * ES256 : ECDSA using P-256 and SHA-256\n * ES256K : ECDSA using secp256k1 curve and SHA-256\n * ES384 : ECDSA using P-384 and SHA-384\n * ES512 : ECDSA using P-521 and SHA-512\n */\n alg?: 'ES256' | 'ES256K' | 'ES384' | 'ES512';\n\n /**\n * Elliptic Curve key pair.\n */\n kty: 'EC';\n\n /**\n * The cryptographic curve used with the key.\n * MUST be present for all EC public keys.\n */\n crv: 'secp256k1' | 'P-256' | 'P-384' | 'P-521';\n\n /**\n * The x-coordinate for the Elliptic Curve point.\n * Represented as the base64url encoding of the octet string\n * representation of the coordinate.\n * MUST be present for all EC public keys\n */\n x: string;\n\n /**\n * The y-coordinate for the Elliptic Curve point.\n * Represented as the base64url encoding of the octet string\n * representation of the coordinate.\n * MUST be present only for secp256k1 public keys.\n */\n y?: string;\n};\n\n/** Parameters used with \"EC\" (elliptic curve) private keys. */\nexport type JwkParamsEcPrivate = JwkParamsEcPublic & {\n /**\n * The d-coordinate for the Elliptic Curve point.\n * Represented as the base64url encoding of the octet string\n * representation of the coordinate.\n * MUST be present for all EC private keys.\n */\n d: string;\n};\n\n/** Parameters used with \"OKP\" (octet key pair) public keys. */\nexport type JwkParamsOkpPublic =\n Omit<JwkParamsAnyKeyType, 'kty' | 'alg' | 'crv'> &\n Pick<JwkParamsEcPublic, 'x'> & {\n /**\n * The algorithm intended for use with the key.\n * EdDSA: Edwards Curve Digital Signature Algorithm\n */\n alg?: 'EdDSA';\n\n /**\n * The cryptographic curve used with the key.\n * MUST be present for all OKP public keys.\n */\n crv: 'Ed25519' | 'Ed448' | 'X25519' | 'X448';\n\n /**\n * Key type\n * OKP (Octet Key Pair) is defined for public key algorithms that use octet\n * strings as private and public keys.\n */\n kty: 'OKP';\n};\n\n/** Parameters used with \"OKP\" (octet key pair) private keys. */\nexport type JwkParamsOkpPrivate = JwkParamsOkpPublic & {\n /**\n * The d-coordinate for the Edwards Curve point.\n * Represented as the base64url encoding of the octet string\n * representation of the coordinate.\n * MUST be present for all EC private keys.\n */\n d: string;\n};\n\n/** Parameters used with \"oct\" (octet sequence) private keys. */\nexport type JwkParamsOctPrivate = Omit<JwkParamsAnyKeyType, 'alg' | 'kty'> & {\n /**\n * The algorithm intended for use with the key.\n * Used with symmetric signing (e.g., HMAC HS256, etc.) and\n * symmetric encryption (e.g., A256GCM, etc.) algorithms.\n */\n alg?:\n // AES CBC using 128-bit key\n | 'A128CBC'\n // AES CBC using 192-bit key\n | 'A192CBC'\n // AES CBC using 256-bit key\n | 'A256CBC'\n // AES CTR using 128-bit key\n | 'A128CTR'\n // AES CTR using 192-bit key\n | 'A192CTR'\n // AES CTR using 256-bit key\n | 'A256CTR'\n // AES GCM using a 128-bit key\n | 'A128GCM'\n // AES GCM using a 192-bit key\n | 'A192GCM'\n // AES GCM using a 256-bit key\n | 'A256GCM'\n // HMAC using SHA-256\n | 'HS256'\n // HMAC using SHA-384\n | 'HS384'\n // HMAC using SHA-512\n | 'HS512'\n\n /**\n * The \"k\" (key value) parameter contains the value of the symmetric\n * (or other single-valued) key. It is represented as the base64url\n * encoding of the octet sequence containing the key value.\n */\n k: string;\n\n /**\n * Key type\n * oct (Octet Sequence) is defined for symmetric encryption and\n * symmetric signature algorithms.\n */\n kty: 'oct';\n};\n\n/** Parameters Used with \"RSA\" public keys. */\nexport type JwkParamsRsaPublic = Omit<JwkParamsAnyKeyType, 'kty'> & {\n /** Public exponent for RSA */\n e: string;\n\n /**\n * Key type\n * RSA is widely used for encryption and digital signatures.\n */\n kty: 'RSA';\n\n /** Modulus for RSA */\n n: string;\n};\n\n/** Parameters used with \"RSA\" private keys. */\nexport type JwkParamsRsaPrivate = JwkParamsRsaPublic & {\n /** Private exponent for RSA */\n d: string;\n /** First prime factor for RSA */\n p?: string;\n /** Second prime factor for RSA */\n q?: string;\n /** First factor's CRT exponent for RSA */\n dp?: string;\n /** Second factor's CRT exponent for RSA */\n dq?: string;\n /** First CRT coefficient for RSA */\n qi?: string;\n /** Other primes information (optional in RFC 7518) */\n oth?: {\n /** Other primes' factor */\n r: string;\n /** Other primes' CRT exponent */\n d: string;\n /** Other primes' CRT coefficient */\n t: string;\n }[];\n};\n\n/** Parameters used with public keys in JWK format. */\nexport type PublicKeyJwk = JwkParamsEcPublic | JwkParamsOkpPublic | JwkParamsRsaPublic;\n\n/** Parameters used with private keys in JWK format. */\nexport type PrivateKeyJwk = JwkParamsEcPrivate | JwkParamsOkpPrivate | JwkParamsOctPrivate | JwkParamsRsaPrivate;\n\n/**\n * JSON Web Key ({@link https://datatracker.ietf.org/doc/html/rfc7517 | JWK}).\n * \"RSA\", \"EC\", \"OKP\", and \"oct\" key types are supported.\n */\nexport interface Jwk {\n // Common properties that apply to all key types.\n\n /** JWK Algorithm Parameter. The algorithm intended for use with the key. */\n alg?: string;\n /** JWK Extractable Parameter */\n ext?: 'true' | 'false';\n /** JWK Key Operations Parameter */\n key_ops?: JwkOperation[];\n /** JWK Key ID Parameter */\n kid?: string;\n /** JWK Key Type Parameter */\n kty: JwkType;\n /** JWK Public Key Use Parameter */\n use?: JwkUse;\n /** JWK X.509 Certificate Chain Parameter */\n x5c?: string;\n /** JWK X.509 Certificate SHA-1 Thumbprint Parameter */\n x5t?: string;\n /** JWK X.509 Certificate SHA-256 Thumbprint Parameter */\n 'x5t#S256'?: string;\n /** JWK X.509 URL Parameter */\n x5u?: string;\n\n // Elliptic Curve (EC or OKP) public key properties.\n\n /** The cryptographic curve used with the key. */\n crv?: string;\n /** The x-coordinate for the Elliptic Curve point. */\n x?: string;\n /** The y-coordinate for the Elliptic Curve point. */\n y?: string;\n\n // Symmetric key properties.\n\n /** The \"k\" (key value) parameter contains the value of the symmetric (or other single-valued) key. */\n k?: string;\n\n // RSA public key properties.\n\n /** Public exponent for RSA */\n e?: string;\n /** Modulus for RSA */\n n?: string;\n /** First prime factor for RSA */\n p?: string;\n /** Second prime factor for RSA */\n q?: string;\n /** First factor's CRT exponent for RSA */\n dp?: string;\n /** Second factor's CRT exponent for RSA */\n dq?: string;\n /** First CRT coefficient for RSA */\n qi?: string;\n /** Other primes information (optional in RFC 7518) */\n oth?: {\n /** Other primes' factor */\n r: string;\n /** Other primes' CRT exponent */\n d: string;\n /** Other primes' CRT coefficient */\n t: string;\n }[];\n\n // Elliptic Curve and RSA private key properties.\n\n /** Private key component for EC, OKP, or RSA keys. */\n d?: string;\n\n // Additional public or private properties.\n [key: string]: unknown;\n}\n\n/**\n * JSON Web Key Set ({@link https://datatracker.ietf.org/doc/html/rfc7517 | JWK Set})\n *\n * @remarks\n * A JWK Set is a JSON object that represents a set of JWKs. The JSON object MUST have a \"keys\"\n * member, with its value being an array of JWKs.\n *\n * Additional members can be present in the JWK Set but member names MUST be unique. If not\n * understood by implementations encountering them, they MUST be ignored. Parameters for\n * representing additional properties of JWK Sets should either be registered in the IANA\n * \"JSON Web Key Set Parameters\" registry or be a value that contains a Collision-Resistant Name.\n */\nexport interface JwkSet {\n /** Array of JWKs */\n keys: Jwk[]\n}\n\n/**\n * Computes the thumbprint of a JSON Web Key (JWK) using the method\n * specified in RFC 7638. This function accepts RSA, EC, OKP, and oct keys\n * and returns the thumbprint as a base64url encoded SHA-256 hash of the\n * JWK's required members, serialized and sorted lexicographically.\n *\n * Purpose:\n * - Uniquely Identifying Keys: The thumbprint allows the unique\n * identification of a specific JWK within a set of JWKs. It provides a\n * deterministic way to generate a value that can be used as a key\n * identifier (kid) or to match a specific key.\n *\n * - Simplifying Key Management: In systems where multiple keys are used,\n * managing and identifying individual keys can become complex. The\n * thumbprint method simplifies this by creating a standardized, unique\n * identifier for each key.\n *\n * - Enabling Interoperability: By standardizing the method to compute a\n * thumbprint, different systems can compute the same thumbprint value for\n * a given JWK. This enables interoperability among systems that use JWKs.\n *\n * - Secure Comparison: The thumbprint provides a way to securely compare\n * JWKs to determine if they are equivalent.\n *\n * @example\n * ```ts\n * const jwk: PublicKeyJwk = {\n * 'kty': 'EC',\n * 'crv': 'secp256k1',\n * 'x': '61iPYuGefxotzBdQZtDvv6cWHZmXrTTscY-u7Y2pFZc',\n * 'y': '88nPCVLfrAY9i-wg5ORcwVbHWC_tbeAd1JE2e0co0lU'\n * };\n *\n * const thumbprint = jwkThumbprint(jwk);\n * console.log(`JWK thumbprint: ${thumbprint}`);\n * ```\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc7638 | RFC7638} for\n * the specification of JWK thumbprint computation.\n *\n * @param jwk - The JSON Web Key for which the thumbprint will be computed.\n * This must be an RSA, EC, OKP, or oct key.\n * @returns The thumbprint as a base64url encoded string.\n * @throws Throws an `Error` if the provided key type is unsupported.\n */\nexport async function computeJwkThumbprint({ jwk }: {\n jwk: Jwk\n}): Promise<string> {\n /** Step 1 - Normalization: The JWK is normalized to include only specific\n * members and in lexicographic order.\n */\n const keyType = jwk.kty;\n let normalizedJwk: Jwk;\n if (keyType === 'EC') {\n normalizedJwk = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };\n } else if (keyType === 'oct') {\n normalizedJwk = { k: jwk.k, kty: jwk.kty };\n } else if (keyType === 'OKP') {\n normalizedJwk = { crv: jwk.crv, kty: jwk.kty, x: jwk.x };\n } else if (keyType === 'RSA') {\n normalizedJwk = { e: jwk.e, kty: jwk.kty, n: jwk.n };\n } else {\n throw new Error(`Unsupported key type: ${keyType}`);\n }\n removeUndefinedProperties(normalizedJwk);\n\n /** Step 2 - Serialization: The normalized JWK is serialized to a UTF-8\n * representation of its JSON encoding. */\n const serializedJwk = canonicalize(normalizedJwk);\n\n /** Step 3 - Digest Calculation: A cryptographic hash function\n * (SHA-256 is recommended) is applied to the serialized JWK,\n * resulting in the thumbprint. */\n const utf8Bytes = Convert.string(serializedJwk).toUint8Array();\n const digest = await Sha256.digest({ data: utf8Bytes });\n\n // Encode as Base64Url.\n const thumbprint = Convert.uint8Array(digest).toBase64Url();\n\n return thumbprint;\n}\n\n/**\n * Checks if the provided object is a valid elliptic curve private key in JWK format.\n *\n * @param obj - The object to check.\n * @returns True if the object is a valid EC private JWK; otherwise, false.\n */\nexport function isEcPrivateJwk(obj: unknown): obj is JwkParamsEcPrivate {\n if (!obj || typeof obj !== 'object') {return false;}\n if (!('kty' in obj && 'crv' in obj && 'x' in obj && 'd' in obj)) {return false;}\n if (obj.kty !== 'EC') {return false;}\n if (typeof obj.d !== 'string') {return false;}\n if (typeof obj.x !== 'string') {return false;}\n return true;\n}\n\n/**\n * Checks if the provided object is a valid elliptic curve public key in JWK format.\n *\n * @param obj - The object to check.\n * @returns True if the object is a valid EC public JWK; otherwise, false.\n */\nexport function isEcPublicJwk(obj: unknown): obj is JwkParamsEcPublic {\n if (!obj || typeof obj !== 'object') {return false;}\n if (!('kty' in obj && 'crv' in obj && 'x' in obj)) {return false;}\n if ('d' in obj) {return false;}\n if (obj.kty !== 'EC') {return false;}\n if (typeof obj.x !== 'string') {return false;}\n return true;\n}\n\n/**\n * Checks if the provided object is a valid octet sequence (symmetric key) in JWK format.\n *\n * @param obj - The object to check.\n * @returns True if the object is a valid oct private JWK; otherwise, false.\n */\nexport function isOctPrivateJwk(obj: unknown): obj is JwkParamsOctPrivate {\n if (!obj || typeof obj !== 'object') {return false;}\n if (!('kty' in obj && 'k' in obj)) {return false;}\n if (obj.kty !== 'oct') {return false;}\n if (typeof obj.k !== 'string') {return false;}\n return true;\n}\n\n/**\n * Checks if the provided object is a valid octet key pair private key in JWK format.\n *\n * @param obj - The object to check.\n * @returns True if the object is a valid OKP private JWK; otherwise, false.\n */\nexport function isOkpPrivateJwk(obj: unknown): obj is JwkParamsOkpPrivate {\n if (!obj || typeof obj !== 'object') {return false;}\n if (!('kty' in obj && 'crv' in obj && 'x' in obj && 'd' in obj)) {return false;}\n if (obj.kty !== 'OKP') {return false;}\n if (typeof obj.d !== 'string') {return false;}\n if (typeof obj.x !== 'string') {return false;}\n return true;\n}\n\n/**\n * Checks if the provided object is a valid octet key pair public key in JWK format.\n *\n * @param obj - The object to check.\n * @returns True if the object is a valid OKP public JWK; otherwise, false.\n */\nexport function isOkpPublicJwk(obj: unknown): obj is JwkParamsOkpPublic {\n if (!obj || typeof obj !== 'object') {return false;}\n if ('d' in obj) {return false;}\n if (!('kty' in obj && 'crv' in obj && 'x' in obj)) {return false;}\n if (obj.kty !== 'OKP') {return false;}\n if (typeof obj.x !== 'string') {return false;}\n return true;\n}\n\n/**\n * Checks if the provided object is a valid private key in JWK format of any supported type.\n *\n * @param obj - The object to check.\n * @returns True if the object is a valid private JWK; otherwise, false.\n */\nexport function isPrivateJwk(obj: unknown): obj is PrivateKeyJwk {\n if (!obj || typeof obj !== 'object') {return false;}\n\n const kty = (obj as { kty: string }).kty;\n\n switch (kty) {\n case 'EC':\n case 'OKP':\n case 'RSA':\n return 'd' in obj;\n case 'oct':\n return 'k' in obj;\n default:\n return false;\n }\n}\n\n/**\n * Checks if the provided object is a valid public key in JWK format of any supported type.\n *\n * @param obj - The object to check.\n * @returns True if the object is a valid public JWK; otherwise, false.\n */\nexport function isPublicJwk(obj: unknown): obj is PublicKeyJwk {\n if (!obj || typeof obj !== 'object') {return false;}\n\n const kty = (obj as { kty: string }).kty;\n\n switch (kty) {\n case 'EC':\n case 'OKP':\n return 'x' in obj && !('d' in obj);\n case 'RSA':\n return 'n' in obj && 'e' in obj && !('d' in obj);\n default:\n return false;\n }\n}", "import type { AffinePoint } from '@noble/curves/abstract/weierstrass';\n\nimport { Convert } from '@enbox/common';\nimport { numberToBytesBE } from '@noble/curves/abstract/utils';\nimport { secp256k1 } from '@noble/curves/secp256k1';\nimport { sha256 } from '@noble/hashes/sha256';\n\nimport type { Jwk } from '../jose/jwk.js';\nimport type { ComputePublicKeyParams, GetPublicKeyParams, SignParams, VerifyParams } from '../types/params-direct.js';\n\nimport { computeJwkThumbprint, isEcPrivateJwk, isEcPublicJwk } from '../jose/jwk.js';\n\n/**\n * The `Secp256k1` class provides a comprehensive suite of utilities for working with\n * the secp256k1 elliptic curve, commonly used in blockchain and cryptographic applications.\n * This class includes methods for key generation, conversion, signing, verification, and\n * Elliptic Curve Diffie-Hellman (ECDH) key agreement.\n *\n * The class supports conversions between raw byte formats and JSON Web Key (JWK) formats. It\n * adheres to RFC6979 for ECDSA signing and verification and RFC6090 for ECDH.\n *\n * Key Features:\n * - Key Generation: Generate secp256k1 private keys in JWK format.\n * - Key Conversion: Transform keys between raw byte arrays and JWK formats.\n * - Public Key Derivation: Derive public keys from private keys.\n * - ECDH Shared Secret Computation: Securely derive shared secrets using private and public keys.\n * - ECDSA Signing and Verification: Sign data and verify signatures with secp256k1 keys.\n * - Key Validation: Validate the mathematical correctness of secp256k1 keys.\n *\n * The methods in this class are asynchronous, returning Promises to accommodate various\n * JavaScript environments, and use `Uint8Array` for binary data handling.\n *\n * @example\n * ```ts\n * // Key Generation\n * const privateKey = await Secp256k1.generateKey();\n *\n * // Public Key Derivation\n * const publicKey = await Secp256k1.computePublicKey({ key: privateKey });\n * console.log(publicKey === await Secp256k1.getPublicKey({ key: privateKey })); // Output: true\n *\n * // ECDH Shared Secret Computation\n * const sharedSecret = await Secp256k1.sharedSecret({\n * privateKeyA: privateKey,\n * publicKeyB: anotherPublicKey\n * });\n *\n * // ECDSA Signing\n * const signature = await Secp256k1.sign({\n * key: privateKey,\n * data: new TextEncoder().encode('Message')\n * });\n *\n * // ECDSA Signature Verification\n * const isValid = await Secp256k1.verify({\n * key: publicKey,\n * signature: signature,\n * data: new TextEncoder().encode('Message')\n * });\n *\n * // Key Conversion\n * const publicKeyBytes = await Secp256k1.publicKeyToBytes({ publicKey });\n * const privateKeyBytes = await Secp256k1.privateKeyToBytes({ privateKey });\n * const compressedPublicKey = await Secp256k1.compressPublicKey({ publicKeyBytes });\n * const uncompressedPublicKey = await Secp256k1.decompressPublicKey({ publicKeyBytes });\n *\n * // Key Validation\n * const isPrivateKeyValid = await Secp256k1.validatePrivateKey({ privateKeyBytes });\n * const isPublicKeyValid = await Secp256k1.validatePublicKey({ publicKeyBytes });\n * ```\n */\nexport class Secp256k1 {\n /**\n * Adjusts an ECDSA signature to a normalized, low-S form.\n *\n * @remarks\n * All ECDSA signatures, regardless of the curve, consist of two components, `r` and `s`, both of\n * which are integers. The curve's order (the total number of points on the curve) is denoted by\n * `n`. In a valid ECDSA signature, both `r` and `s` must be in the range [1, n-1]. However, due\n * to the mathematical properties of ECDSA, if `(r, s)` is a valid signature, then `(r, n - s)` is\n * also a valid signature for the same message and public key. In other words, for every\n * signature, there's a \"mirror\" signature that's equally valid. For these elliptic curves:\n *\n * - Low S Signature: A signature where the `s` component is in the lower half of the range,\n * specifically less than or equal to `n/2`.\n *\n * - High S Signature: This is where the `s` component is in the upper half of the range, greater\n * than `n/2`.\n *\n * The practical implication is that a third-party can forge a second valid signature for the same\n * message by negating the `s` component of the original signature, without any knowledge of the\n * private key. This is known as a \"signature malleability\" attack.\n *\n * This type of forgery is not a problem in all systems, but it can be an issue in systems that\n * rely on digital signature uniqueness to ensure transaction integrity. For example, in Bitcoin,\n * transaction malleability is an issue because it allows for the modification of transaction\n * identifiers (and potentially, transactions themselves) after they're signed but before they're\n * confirmed in a block. By enforcing low `s` values, the Bitcoin network reduces the likelihood of\n * this occurring, making the system more secure and predictable.\n *\n * For this reason, it's common practice to normalize ECDSA signatures to a low-S form. This\n * form is considered standard and preferable in some systems and is known as the \"normalized\"\n * form of the signature.\n *\n * This method takes a signature, and if it's high-S, returns the normalized low-S form. If the\n * signature is already low-S, it's returned unmodified. It's important to note that this\n * method does not change the validity of the signature but makes it compliant with systems that\n * enforce low-S signatures.\n *\n * @example\n * ```ts\n * const signature = new Uint8Array([...]); // Your ECDSA signature\n * const adjustedSignature = await Secp256k1.adjustSignatureToLowS({ signature });\n * // Now 'adjustedSignature' is in the low-S form.\n * ```\n *\n * @param params - The parameters for the signature adjustment.\n * @param params.signature - The ECDSA signature as a `Uint8Array`.\n *\n * @returns A Promise that resolves to the adjusted signature in low-S form as a `Uint8Array`.\n */\n public static async adjustSignatureToLowS({ signature }: {\n signature: Uint8Array;\n }): Promise<Uint8Array> {\n // Convert the signature to a `secp256k1.Signature` object.\n const signatureObject = secp256k1.Signature.fromCompact(signature);\n\n if (signatureObject.hasHighS()) {\n // Adjust the signature to low-S format if it's high-S.\n const adjustedSignatureObject = signatureObject.normalizeS();\n\n // Convert the adjusted signature object back to a byte array.\n const adjustedSignature = adjustedSignatureObject.toCompactRawBytes();\n\n return adjustedSignature;\n\n } else {\n // Return the unmodified signature if it is already in low-S format.\n return signature;\n }\n }\n\n /**\n * Converts a raw private key in bytes to its corresponding JSON Web Key (JWK) format.\n *\n * @remarks\n * This method takes a private key represented as a byte array (Uint8Array) and\n * converts it into a JWK object. The conversion involves extracting the\n * elliptic curve point (x and y coordinates) from the private key and encoding\n * them into base64url format, alongside other JWK parameters.\n *\n * The resulting JWK object includes the following properties:\n * - `kty`: Key Type, set to 'EC' for Elliptic Curve.\n * - `crv`: Curve Name, set to 'secp256k1'.\n * - `d`: The private key component, base64url-encoded.\n * - `x`: The x-coordinate of the public key point, base64url-encoded.\n * - `y`: The y-coordinate of the public key point, base64url-encoded.\n *\n * This method is useful for converting raw public keys into a standardized\n * JSON format, facilitating their use in cryptographic operations and making\n * them easy to share and store.\n *\n * @example\n * ```ts\n * const privateKeyBytes = new Uint8Array([...]); // Replace with actual private key bytes\n * const privateKey = await Secp256k1.bytesToPrivateKey({ privateKeyBytes });\n * ```\n *\n * @param params - The parameters for the private key conversion.\n * @param params.privateKeyBytes - The raw private key as a Uint8Array.\n *\n * @returns A Promise that resolves to the private key in JWK format.\n */\n public static async bytesToPrivateKey({ privateKeyBytes }: {\n privateKeyBytes: Uint8Array;\n }): Promise<Jwk> {\n // Get the elliptic curve point (x and y coordinates) for the provided private key.\n const point = await Secp256k1.getCurvePoint({ keyBytes: privateKeyBytes });\n\n // Construct the private key in JWK format.\n const privateKey: Jwk = {\n kty : 'EC',\n crv : 'secp256k1',\n d : Convert.uint8Array(privateKeyBytes).toBase64Url(),\n x : Convert.uint8Array(point.x).toBase64Url(),\n y : Convert.uint8Array(point.y).toBase64Url()\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n return privateKey;\n }\n\n /**\n * Converts a raw public key in bytes to its corresponding JSON Web Key (JWK) format.\n *\n * @remarks\n * This method accepts a public key in a byte array (Uint8Array) format and\n * transforms it to a JWK object. It involves decoding the elliptic curve point\n * (x and y coordinates) from the raw public key bytes and encoding them into\n * base64url format, along with setting appropriate JWK parameters.\n *\n * The resulting JWK object includes the following properties:\n * - `kty`: Key Type, set to 'EC' for Elliptic Curve.\n * - `crv`: Curve Name, set to 'secp256k1'.\n * - `x`: The x-coordinate of the public key point, base64url-encoded.\n * - `y`: The y-coordinate of the public key point, base64url-encoded.\n *\n * This method is useful for converting raw public keys into a standardized\n * JSON format, facilitating their use in cryptographic operations and making\n * them easy to share and store.\n *\n * @example\n * ```ts\n * const publicKeyBytes = new Uint8Array([...]); // Replace with actual public key bytes\n * const publicKey = await Secp256k1.bytesToPublicKey({ publicKeyBytes });\n * ```\n *\n * @param params - The parameters for the public key conversion.\n * @param params.publicKeyBytes - The raw public key as a Uint8Array.\n *\n * @returns A Promise that resolves to the public key in JWK format.\n */\n public static async bytesToPublicKey({ publicKeyBytes }: {\n publicKeyBytes: Uint8Array;\n }): Promise<Jwk> {\n // Get the elliptic curve point (x and y coordinates) for the provided public key.\n const point = await Secp256k1.getCurvePoint({ keyBytes: publicKeyBytes });\n\n // Construct the public key in JWK format.\n const publicKey: Jwk = {\n kty : 'EC',\n crv : 'secp256k1',\n x : Convert.uint8Array(point.x).toBase64Url(),\n y : Convert.uint8Array(point.y).toBase64Url()\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n publicKey.kid = await computeJwkThumbprint({ jwk: publicKey });\n\n return publicKey;\n }\n\n /**\n * Converts a public key to its compressed form.\n *\n * @remarks\n * This method takes a public key represented as a byte array and compresses it. Public key\n * compression is a process that reduces the size of the public key by removing the y-coordinate,\n * making it more efficient for storage and transmission. The compressed key retains the same\n * level of security as the uncompressed key.\n *\n * @example\n * ```ts\n * const uncompressedPublicKeyBytes = new Uint8Array([...]); // Replace with actual uncompressed public key bytes\n * const compressedPublicKey = await Secp256k1.compressPublicKey({\n * publicKeyBytes: uncompressedPublicKeyBytes\n * });\n * ```\n *\n * @param params - The parameters for the public key compression.\n * @param params.publicKeyBytes - The public key as a Uint8Array.\n *\n * @returns A Promise that resolves to the compressed public key as a Uint8Array.\n */\n public static async compressPublicKey({ publicKeyBytes }: {\n publicKeyBytes: Uint8Array;\n }): Promise<Uint8Array> {\n // Decode Weierstrass points from the public key byte array.\n const point = secp256k1.ProjectivePoint.fromHex(publicKeyBytes);\n\n // Return the compressed form of the public key.\n return point.toRawBytes(true);\n }\n\n /**\n * Derives the public key in JWK format from a given private key.\n *\n * @remarks\n * This method takes a private key in JWK format and derives its corresponding public key,\n * also in JWK format. The derivation process involves converting the private key to a raw\n * byte array, then computing the elliptic curve point (x and y coordinates) from this private\n * key. These coordinates are then encoded into base64url format to construct the public key in\n * JWK format.\n *\n * The process ensures that the derived public key correctly corresponds to the given private key,\n * adhering to the secp256k1 elliptic curve standards. This method is useful in cryptographic\n * operations where a public key is needed for operations like signature verification, but only\n * the private key is available.\n *\n * @example\n * ```ts\n * const privateKey = { ... }; // A Jwk object representing a secp256k1 private key\n * const publicKey = await Secp256k1.computePublicKey({ key: privateKey });\n * ```\n *\n * @param params - The parameters for the public key derivation.\n * @param params.key - The private key in JWK format from which to derive the public key.\n *\n * @returns A Promise that resolves to the derived public key in JWK format.\n */\n public static async computePublicKey({ key }:\n ComputePublicKeyParams\n ): Promise<Jwk> {\n // Convert the provided private key to a byte array.\n const privateKeyBytes = await Secp256k1.privateKeyToBytes({ privateKey: key });\n\n // Get the elliptic curve point (x and y coordinates) for the provided private key.\n const point = await Secp256k1.getCurvePoint({ keyBytes: privateKeyBytes });\n\n // Construct the public key in JWK format.\n const publicKey: Jwk = {\n kty : 'EC',\n crv : 'secp256k1',\n x : Convert.uint8Array(point.x).toBase64Url(),\n y : Convert.uint8Array(point.y).toBase64Url()\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n publicKey.kid = await computeJwkThumbprint({ jwk: publicKey });\n\n return publicKey;\n }\n\n /**\n * Converts an ASN.1 DER encoded ECDSA signature to a compact R+S format.\n *\n * @remarks\n * This method is used for converting an ECDSA signature from the ASN.1 DER encoding to the more\n * compact R+S format. This conversion is often required when dealing with ECDSA signatures in\n * certain cryptographic standards such as JWS (JSON Web Signature).\n *\n * The method decodes the DER-encoded signature, extracts the R and S values, and concatenates\n * them into a single byte array. This process involves handling the ASN.1 structure to correctly\n * parse the R and S values, considering padding and integer encoding specifics of DER.\n *\n * @example\n * ```ts\n * const derSignature = new Uint8Array([...]); // Replace with your DER-encoded signature\n * const signature = await Secp256k1.convertDerToCompactSignature({ derSignature });\n * ```\n *\n * @param params - The parameters for the signature conversion.\n * @param params.derSignature - The signature in ASN.1 DER format as a `Uint8Array`.\n *\n * @returns A Promise that resolves to the signature in compact R+S format as a `Uint8Array`.\n */\n public static async convertDerToCompactSignature({ derSignature }: {\n derSignature: Uint8Array;\n }): Promise<Uint8Array> {\n // Convert the DER-encoded signature into a `secp256k1.Signature` object.\n // This involves parsing the ASN.1 DER structure to extract the R and S components.\n const signatureObject = secp256k1.Signature.fromDER(derSignature);\n\n // Convert the signature object into compact R+S format, which concatenates the R and S values\n // into a single byte array.\n const compactSignature = signatureObject.toCompactRawBytes();\n\n return compactSignature;\n }\n\n /**\n * Converts a public key to its uncompressed form.\n *\n * @remarks\n * This method takes a compressed public key represented as a byte array and decompresses it.\n * Public key decompression involves reconstructing the y-coordinate from the x-coordinate,\n * resulting in the full public key. This method is used when the uncompressed key format is\n * required for certain cryptographic operations or interoperability.\n *\n * @example\n * ```ts\n * const compressedPublicKeyBytes = new Uint8Array([...]); // Replace with actual compressed public key bytes\n * const decompressedPublicKey = await Secp256k1.decompressPublicKey({\n * publicKeyBytes: compressedPublicKeyBytes\n * });\n * ```\n *\n * @param params - The parameters for the public key decompression.\n * @param params.publicKeyBytes - The public key as a Uint8Array.\n *\n * @returns A Promise that resolves to the uncompressed public key as a Uint8Array.\n */\n public static async decompressPublicKey({ publicKeyBytes }: {\n publicKeyBytes: Uint8Array;\n }): Promise<Uint8Array> {\n // Decode Weierstrass points from the public key byte array.\n const point = secp256k1.ProjectivePoint.fromHex(publicKeyBytes);\n\n // Return the uncompressed form of the public key.\n return point.toRawBytes(false);\n }\n\n /**\n * Generates a secp256k1 private key in JSON Web Key (JWK) format.\n *\n * @remarks\n * This method creates a new private key suitable for use with the secp256k1\n * elliptic curve. The key is generated using cryptographically secure random\n * number generation to ensure its uniqueness and security. The resulting\n * private key adheres to the JWK format, specifically tailored for secp256k1,\n * making it compatible with common cryptographic standards and easy to use in\n * various cryptographic processes.\n *\n * The private key generated by this method includes the following components:\n * - `kty`: Key Type, set to 'EC' for Elliptic Curve.\n * - `crv`: Curve Name, set to 'secp256k1'.\n * - `d`: The private key component, base64url-encoded.\n * - `x`: The x-coordinate of the public key point, derived from the private key, base64url-encoded.\n * - `y`: The y-coordinate of the public key point, derived from the private key, base64url-encoded.\n *\n * The key is returned in a format suitable for direct use in signin and key agreement operations.\n *\n * @example\n * ```ts\n * const privateKey = await Secp256k1.generateKey();\n * ```\n *\n * @returns A Promise that resolves to the generated private key in JWK format.\n */\n public static async generateKey(): Promise<Jwk> {\n // Generate a random private key.\n const privateKeyBytes = secp256k1.utils.randomPrivateKey();\n\n // Convert private key from bytes to JWK format.\n const privateKey = await Secp256k1.bytesToPrivateKey({ privateKeyBytes });\n\n // Compute the JWK thumbprint and set as the key ID.\n privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n return privateKey;\n }\n\n /**\n * Retrieves the public key properties from a given private key in JWK format.\n *\n * @remarks\n * This method extracts the public key portion from a secp256k1 private key in JWK format. It does\n * so by removing the private key property 'd' and making a shallow copy, effectively yielding the\n * public key. The method sets the 'kid' (key ID) property using the JWK thumbprint if it is not\n * already defined. This approach is used under the assumption that a private key in JWK format\n * always contains the corresponding public key properties.\n *\n * Note: This method offers a significant performance advantage, being about 200 times faster\n * than `computePublicKey()`. However, it does not mathematically validate the private key, nor\n * does it derive the public key from the private key. It simply extracts existing public key\n * properties from the private key object. This makes it suitable for scenarios where speed is\n * critical and the private key's integrity is already assured.\n *\n * @example\n * ```ts\n * const privateKey = { ... }; // A Jwk object representing a secp256k1 private key\n * const publicKey = await Secp256k1.getPublicKey({ key: privateKey });\n * ```\n *\n * @param params - The parameters for retrieving the public key properties.\n * @param params.key - The private key in JWK format.\n *\n * @returns A Promise that resolves to the public key in JWK format.\n */\n public static async getPublicKey({ key }:\n GetPublicKeyParams\n ): Promise<Jwk> {\n // Verify the provided JWK represents an elliptic curve (EC) secp256k1 private key.\n if (!(isEcPrivateJwk(key) && key.crv === 'secp256k1')) {\n throw new Error(`Secp256k1: The provided key is not a secp256k1 private JWK.`);\n }\n\n // Remove the private key property ('d') and make a shallow copy of the provided key.\n const { d, ...publicKey } = key;\n\n // If the key ID is undefined, set it to the JWK thumbprint.\n publicKey.kid ??= await computeJwkThumbprint({ jwk: publicKey });\n\n return publicKey;\n }\n\n /**\n * Converts a private key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n *\n * @remarks\n * This method takes a private key in JWK format and extracts its raw byte representation.\n * It specifically focuses on the 'd' parameter of the JWK, which represents the private\n * key component in base64url encoding. The method decodes this value into a byte array.\n *\n * This conversion is essential for operations that require the private key in its raw\n * binary form, such as certain low-level cryptographic operations or when interfacing\n * with systems and libraries that expect keys in a byte array format.\n *\n * @example\n * ```ts\n * const privateKey = { ... }; // An X25519 private key in JWK format\n * const privateKeyBytes = await Secp256k1.privateKeyToBytes({ privateKey });\n * ```\n *\n * @param params - The parameters for the private key conversion.\n * @param params.privateKey - The private key in JWK format.\n *\n * @returns A Promise that resolves to the private key as a Uint8Array.\n */\n public static async privateKeyToBytes({ privateKey }: {\n privateKey: Jwk;\n }): Promise<Uint8Array> {\n // Verify the provided JWK represents a valid EC secp256k1 private key.\n if (!isEcPrivateJwk(privateKey)) {\n throw new Error(`Secp256k1: The provided key is not a valid EC private key.`);\n }\n\n // Decode the provided private key to bytes.\n const privateKeyBytes = Convert.base64Url(privateKey.d).toUint8Array();\n\n return privateKeyBytes;\n }\n\n /**\n * Converts a public key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n *\n * @remarks\n * This method accepts a public key in JWK format and converts it into its raw binary\n * form. The conversion process involves decoding the 'x' and 'y' parameters of the JWK\n * (which represent the x and y coordinates of the elliptic curve point, respectively)\n * from base64url format into a byte array. The method then concatenates these values,\n * along with a prefix indicating the key format, to form the full public key.\n *\n * This function is particularly useful for use cases where the public key is needed\n * in its raw byte format, such as for certain cryptographic operations or when\n * interfacing with systems that require raw key formats.\n *\n * @example\n * ```ts\n * const publicKey = { ... }; // A Jwk public key object\n * const publicKeyBytes = await Secp256k1.publicKeyToBytes({ publicKey });\n * ```\n *\n * @param params - The parameters for the public key conversion.\n * @param params.publicKey - The public key in JWK format.\n *\n * @returns A Promise that resolves to the public key as a Uint8Array.\n */\n public static async publicKeyToBytes({ publicKey }: {\n publicKey: Jwk;\n }): Promise<Uint8Array> {\n // Verify the provided JWK represents a valid EC secp256k1 public key, which must have a 'y' value.\n if (!(isEcPublicJwk(publicKey) && publicKey.y)) {\n throw new Error(`Secp256k1: The provided key is not a valid EC public key.`);\n }\n\n // Decode the provided public key to bytes.\n const prefix = new Uint8Array([0x04]); // Designates an uncompressed key.\n const x = Convert.base64Url(publicKey.x).toUint8Array();\n const y = Convert.base64Url(publicKey.y).toUint8Array();\n\n // Concatenate the prefix, x-coordinate, and y-coordinate as a single byte array.\n const publicKeyBytes = new Uint8Array([...prefix, ...x, ...y]);\n\n return publicKeyBytes;\n }\n\n /**\n * Computes an RFC6090-compliant Elliptic Curve Diffie-Hellman (ECDH) shared secret\n * using secp256k1 private and public keys in JSON Web Key (JWK) format.\n *\n * @remarks\n * This method facilitates the ECDH key agreement protocol, which is a method of securely\n * deriving a shared secret between two parties based on their private and public keys.\n * It takes the private key of one party (privateKeyA) and the public key of another\n * party (publicKeyB) to compute a shared secret. The shared secret is derived from the\n * x-coordinate of the elliptic curve point resulting from the multiplication of the\n * public key with the private key.\n *\n * Note: When performing Elliptic Curve Diffie-Hellman (ECDH) key agreement,\n * the resulting shared secret is a point on the elliptic curve, which\n * consists of an x-coordinate and a y-coordinate. With a 256-bit curve like\n * secp256k1, each of these coordinates is 32 bytes (256 bits) long. However,\n * in the ECDH process, it's standard practice to use only the x-coordinate\n * of the shared secret point as the resulting shared key. This is because\n * the y-coordinate does not add to the entropy of the key, and both parties\n * can independently compute the x-coordinate. Consquently, this implementation\n * omits the y-coordinate for simplicity and standard compliance.\n *\n * @example\n * ```ts\n * const privateKeyA = { ... }; // A Jwk private key object for party A\n * const publicKeyB = { ... }; // A Jwk public key object for party B\n * const sharedSecret = await Secp256k1.sharedSecret({\n * privateKeyA,\n * publicKeyB\n * });\n * ```\n *\n * @param params - The parameters for the shared secret computation.\n * @param params.privateKeyA - The private key in JWK format of one party.\n * @param params.publicKeyB - The public key in JWK format of the other party.\n *\n * @returns A Promise that resolves to the computed shared secret as a Uint8Array.\n */\n public static async sharedSecret({ privateKeyA, publicKeyB }: {\n privateKeyA: Jwk;\n publicKeyB: Jwk;\n }): Promise<Uint8Array> {\n // Ensure that keys from the same key pair are not specified.\n if ('x' in privateKeyA && 'x' in publicKeyB && privateKeyA.x === publicKeyB.x) {\n throw new Error(`Secp256k1: ECDH shared secret cannot be computed from a single key pair's public and private keys.`);\n }\n\n // Convert the provided private and public keys to bytes.\n const privateKeyABytes = await Secp256k1.privateKeyToBytes({ privateKey: privateKeyA });\n const publicKeyBBytes = await Secp256k1.publicKeyToBytes({ publicKey: publicKeyB });\n\n // Compute the compact representation shared secret between the public and private keys.\n const sharedSecret = secp256k1.getSharedSecret(privateKeyABytes, publicKeyBBytes, true);\n\n // Remove the leading byte that indicates the sign of the y-coordinate\n // of the point on the elliptic curve. See note above.\n return sharedSecret.slice(1);\n }\n\n /**\n * Generates an RFC6979-compliant ECDSA signature of given data using a secp256k1 private key.\n *\n * @remarks\n * This method signs the provided data with a specified private key using the ECDSA\n * (Elliptic Curve Digital Signature Algorithm) signature algorithm, as defined in RFC6979.\n * The data to be signed is first hashed using the SHA-256 algorithm, and this hash is then\n * signed using the private key. The output is a digital signature in the form of a\n * Uint8Array, which uniquely corresponds to both the data and the private key used for signing.\n *\n * This method is commonly used in cryptographic applications to ensure data integrity and\n * authenticity. The signature can later be verified by parties with access to the corresponding\n * public key, ensuring that the data has not been tampered with and was indeed signed by the\n * holder of the private key.\n *\n * @example\n * ```ts\n * const data = new TextEncoder().encode('Messsage'); // Data to be signed\n * const privateKey = { ... }; // A Jwk object representing a secp256k1 private key\n * const signature = await Secp256k1.sign({\n * key: privateKey,\n * data\n * });\n * ```\n *\n * @param params - The parameters for the signing operation.\n * @param params.key - The private key to use for signing, represented in JWK format.\n * @param params.data - The data to sign, represented as a Uint8Array.\n *\n * @returns A Promise that resolves to the signature as a Uint8Array.\n */\n public static async sign({ data, key }:\n SignParams\n ): Promise<Uint8Array> {\n // Convert the private key from JWK format to bytes.\n const privateKeyBytes = await Secp256k1.privateKeyToBytes({ privateKey: key });\n\n // Generate a digest of the data using the SHA-256 hash function.\n const digest = sha256(data);\n\n // Sign the provided data using the ECDSA algorithm.\n // The `secp256k1.sign` operation returns a signature object with { r, s, recovery } properties.\n const signatureObject = secp256k1.sign(digest, privateKeyBytes);\n\n // Convert the signature object to Uint8Array.\n const signature = signatureObject.toCompactRawBytes();\n\n return signature;\n }\n\n /**\n * Validates a given private key to ensure its compliance with the secp256k1 curve standards.\n *\n * @remarks\n * This method checks whether a provided private key is a valid 32-byte number and falls within\n * the range defined by the secp256k1 curve's order. It is essential for ensuring the private\n * key's mathematical correctness in the context of secp256k1-based cryptographic operations.\n *\n * Note that this validation strictly pertains to the key's format and numerical validity; it does\n * not assess whether the key corresponds to a known entity or its security status (e.g., whether\n * it has been compromised).\n *\n * @example\n * ```ts\n * const privateKeyBytes = new Uint8Array([...]); // A 32-byte private key\n * const isValid = await Secp256k1.validatePrivateKey({ privateKeyBytes });\n * console.log(isValid); // true or false based on the key's validity\n * ```\n *\n * @param params - The parameters for the key validation.\n * @param params.privateKeyBytes - The private key to validate, represented as a Uint8Array.\n *\n * @returns A Promise that resolves to a boolean indicating whether the private key is valid.\n */\n public static async validatePrivateKey({ privateKeyBytes }: {\n privateKeyBytes: Uint8Array;\n }): Promise<boolean> {\n return secp256k1.utils.isValidPrivateKey(privateKeyBytes);\n }\n\n /**\n * Validates a given public key to confirm its mathematical correctness on the secp256k1 curve.\n *\n * @remarks\n * This method checks if the provided public key represents a valid point on the secp256k1 curve.\n * It decodes the key's Weierstrass points (x and y coordinates) and verifies their validity\n * against the curve's parameters. A valid point must lie on the curve and meet specific\n * mathematical criteria defined by the curve's equation.\n *\n * It's important to note that this method does not verify the key's ownership or whether it has\n * been compromised; it solely focuses on the key's adherence to the curve's mathematical\n * principles.\n *\n * @example\n * ```ts\n * const publicKeyBytes = new Uint8Array([...]); // A public key in byte format\n * const isValid = await Secp256k1.validatePublicKey({ publicKeyBytes });\n * console.log(isValid); // true if the key is valid on the secp256k1 curve, false otherwise\n * ```\n *\n * @param params - The parameters for the key validation.\n * @param params.publicKeyBytes - The public key to validate, represented as a Uint8Array.\n *\n * @returns A Promise that resolves to a boolean indicating the public key's validity on\n * the secp256k1 curve.\n */\n public static async validatePublicKey({ publicKeyBytes }: {\n publicKeyBytes: Uint8Array;\n }): Promise<boolean> {\n try {\n // Decode Weierstrass points from key bytes.\n const point = secp256k1.ProjectivePoint.fromHex(publicKeyBytes);\n\n // Check if points are on the Short Weierstrass curve.\n point.assertValidity();\n\n } catch {\n return false;\n }\n\n return true;\n }\n\n /**\n * Verifies an RFC6979-compliant ECDSA signature against given data and a secp256k1 public key.\n *\n * @remarks\n * This method validates a digital signature to ensure that it was generated by the holder of the\n * corresponding private key and that the signed data has not been altered. The signature\n * verification is performed using the ECDSA (Elliptic Curve Digital Signature Algorithm) as\n * specified in RFC6979. The data to be verified is first hashed using the SHA-256 algorithm, and\n * this hash is then used along with the public key to verify the signature.\n *\n * The method returns a boolean value indicating whether the signature is valid. A valid signature\n * proves that the signed data was indeed signed by the owner of the private key corresponding to\n * the provided public key and that the data has not been tampered with since it was signed.\n *\n * Note: The verification process does not consider the malleability of low-s signatures, which\n * may be relevant in certain contexts, such as Bitcoin transactions.\n *\n * @example\n * ```ts\n * const data = new TextEncoder().encode('Messsage'); // Data that was signed\n * const publicKey = { ... }; // Public key in JWK format corresponding to the private key that signed the data\n * const signature = new Uint8Array([...]); // Signature to verify\n * const isSignatureValid = await Secp256k1.verify({\n * key: publicKey,\n * signature,\n * data\n * });\n * console.log(isSignatureValid); // true if the signature is valid, false otherwise\n * ```\n *\n * @param params - The parameters for the signature verification.\n * @param params.key - The public key used for verification, represented in JWK format.\n * @param params.signature - The signature to verify, represented as a Uint8Array.\n * @param params.data - The data that was signed, represented as a Uint8Array.\n *\n * @returns A Promise that resolves to a boolean indicating whether the signature is valid.\n */\n public static async verify({ key, signature, data }:\n VerifyParams\n ): Promise<boolean> {\n // Convert the public key from JWK format to bytes.\n const publicKeyBytes = await Secp256k1.publicKeyToBytes({ publicKey: key });\n\n // Generate a digest of the data using the SHA-256 hash function.\n const digest = sha256(data);\n\n /** Perform the verification of the signature.\n * This verify operation has the malleability check disabled. Guaranteed support\n * for low-s signatures across languages is unlikely especially in the context\n * of SSI. Notable Cloud KMS providers do not natively support it either. It is\n * also worth noting that low-s signatures are a requirement for Bitcoin. */\n const isValid = secp256k1.verify(signature, digest, publicKeyBytes, { lowS: false });\n\n return isValid;\n }\n\n /**\n * Returns the elliptic curve point (x and y coordinates) for a given secp256k1 key.\n *\n * @remarks\n * This method extracts the elliptic curve point from a given secp256k1 key, whether\n * it's a private or a public key. For a private key, the method first computes the\n * corresponding public key and then extracts the x and y coordinates. For a public key,\n * it directly returns these coordinates. The coordinates are represented as Uint8Array.\n *\n * The x and y coordinates represent the key's position on the elliptic curve and can be\n * used in various cryptographic operations, such as digital signatures or key agreement\n * protocols.\n *\n * @example\n * ```ts\n * // For a private key\n * const privateKey = new Uint8Array([...]); // A 32-byte private key\n * const { x: xFromPrivateKey, y: yFromPrivateKey } = await Secp256k1.getCurvePoint({ keyBytes: privateKey });\n *\n * // For a public key\n * const publicKey = new Uint8Array([...]); // A 33-byte or 65-byte public key\n * const { x: xFromPublicKey, y: yFromPublicKey } = await Secp256k1.getCurvePoint({ keyBytes: publicKey });\n * ```\n *\n * @param params - The parameters for the curve point decoding operation.\n * @param params.keyBytes - The key for which to get the elliptic curve point.\n * Can be either a private key or a public key.\n * The key should be passed as a `Uint8Array`.\n *\n * @returns A Promise that resolves to an object with properties 'x' and 'y',\n * each being a Uint8Array representing the x and y coordinates of the key point on the\n * elliptic curve.\n */\n private static async getCurvePoint({ keyBytes }: {\n keyBytes: Uint8Array;\n }): Promise<AffinePoint<Uint8Array>> {\n // If key is a private key, first compute the public key.\n if (keyBytes.byteLength === 32) {\n keyBytes = secp256k1.getPublicKey(keyBytes);\n }\n\n // Decode Weierstrass affine point from key bytes.\n const point = secp256k1.ProjectivePoint.fromHex(keyBytes);\n\n // Get x- and y-coordinate values and convert to Uint8Array.\n const x = numberToBytesBE(point.x, 32);\n const y = numberToBytesBE(point.y, 32);\n\n return { x, y };\n }\n}", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { createCurve } from './_shortw_utils.js';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { Field } from './abstract/modular.js';\nimport { mapToCurveSimpleSWU } from './abstract/weierstrass.js';\nimport { createHasher } from './abstract/hash-to-curve.js';\n\n// NIST secp256r1 aka p256\n// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-256\n\nconst Fp = Field(BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'));\nconst CURVE_A = Fp.create(BigInt('-3'));\nconst CURVE_B = BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b');\n\n// prettier-ignore\nexport const p256 = createCurve({\n a: CURVE_A, // Equation params: a, b\n b: CURVE_B,\n Fp, // Field: 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n-1n\n // Curve order, total count of valid points in the field\n n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),\n // Base (generator) point (x, y)\n Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),\n Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),\n h: BigInt(1),\n lowS: false,\n} as const, sha256);\nexport const secp256r1 = p256;\n\nconst mapSWU = /* @__PURE__ */ (() =>\n mapToCurveSimpleSWU(Fp, {\n A: CURVE_A,\n B: CURVE_B,\n Z: Fp.create(BigInt('-10')),\n }))();\n\nconst htf = /* @__PURE__ */ (() =>\n createHasher(secp256r1.ProjectivePoint, (scalars: bigint[]) => mapSWU(scalars[0]), {\n DST: 'P256_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'P256_XMD:SHA-256_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n }))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n", "import type { AffinePoint } from '@noble/curves/abstract/weierstrass';\n\nimport { Convert } from '@enbox/common';\nimport { numberToBytesBE } from '@noble/curves/abstract/utils';\nimport { secp256r1 } from '@noble/curves/p256';\nimport { sha256 } from '@noble/hashes/sha256';\n\nimport type { Jwk } from '../jose/jwk.js';\nimport type { ComputePublicKeyParams, GetPublicKeyParams, SignParams, VerifyParams } from '../types/params-direct.js';\n\nimport { computeJwkThumbprint, isEcPrivateJwk, isEcPublicJwk } from '../jose/jwk.js';\n\n/**\n * The `Secp256r1` class provides a comprehensive suite of utilities for working with\n * the secp256r1 (aka P-256) elliptic curve, commonly used in blockchain and cryptographic\n * applications. This class includes methods for key generation, conversion, signing, verification,\n * and Elliptic Curve Diffie-Hellman (ECDH) key agreement.\n *\n * The class supports conversions between raw byte formats and JSON Web Key (JWK) formats. It\n * adheres to RFC6979 for ECDSA signing and verification and RFC6090 for ECDH.\n *\n * Key Features:\n * - Key Generation: Generate secp256r1 private keys in JWK format.\n * - Key Conversion: Transform keys between raw byte arrays and JWK formats.\n * - Public Key Derivation: Derive public keys from private keys.\n * - ECDH Shared Secret Computation: Securely derive shared secrets using private and public keys.\n * - ECDSA Signing and Verification: Sign data and verify signatures with secp256r1 keys.\n * - Key Validation: Validate the mathematical correctness of secp256r1 keys.\n *\n * The methods in this class are asynchronous, returning Promises to accommodate various\n * JavaScript environments, and use `Uint8Array` for binary data handling.\n *\n * @example\n * ```ts\n * // Key Generation\n * const privateKey = await Secp256r1.generateKey();\n *\n * // Public Key Derivation\n * const publicKey = await Secp256r1.computePublicKey({ key: privateKey });\n * console.log(publicKey === await Secp256r1.getPublicKey({ key: privateKey })); // Output: true\n *\n * // ECDH Shared Secret Computation\n * const sharedSecret = await Secp256r1.sharedSecret({\n * privateKeyA: privateKey,\n * publicKeyB: anotherPublicKey\n * });\n *\n * // ECDSA Signing\n * const signature = await Secp256r1.sign({\n * key: privateKey,\n * data: new TextEncoder().encode('Message')\n * });\n *\n * // ECDSA Signature Verification\n * const isValid = await Secp256r1.verify({\n * key: publicKey,\n * signature: signature,\n * data: new TextEncoder().encode('Message')\n * });\n *\n * // Key Conversion\n * const publicKeyBytes = await Secp256r1.publicKeyToBytes({ publicKey });\n * const privateKeyBytes = await Secp256r1.privateKeyToBytes({ privateKey });\n * const compressedPublicKey = await Secp256r1.compressPublicKey({ publicKeyBytes });\n * const uncompressedPublicKey = await Secp256r1.decompressPublicKey({ publicKeyBytes });\n *\n * // Key Validation\n * const isPrivateKeyValid = await Secp256r1.validatePrivateKey({ privateKeyBytes });\n * const isPublicKeyValid = await Secp256r1.validatePublicKey({ publicKeyBytes });\n * ```\n */\nexport class Secp256r1 {\n/**\n * Adjusts an ECDSA signature to a normalized, low-S form.\n *\n * @remarks\n * All ECDSA signatures, regardless of the curve, consist of two components, `r` and `s`, both of\n * which are integers. The curve's order (the total number of points on the curve) is denoted by\n * `n`. In a valid ECDSA signature, both `r` and `s` must be in the range [1, n-1]. However, due\n * to the mathematical properties of ECDSA, if `(r, s)` is a valid signature, then `(r, n - s)` is\n * also a valid signature for the same message and public key. In other words, for every\n * signature, there's a \"mirror\" signature that's equally valid. For these elliptic curves:\n *\n * - Low S Signature: A signature where the `s` component is in the lower half of the range,\n * specifically less than or equal to `n/2`.\n *\n * - High S Signature: This is where the `s` component is in the upper half of the range, greater\n * than `n/2`.\n *\n * The practical implication is that a third-party can forge a second valid signature for the same\n * message by negating the `s` component of the original signature, without any knowledge of the\n * private key. This is known as a \"signature malleability\" attack.\n *\n * This type of forgery is not a problem in all systems, but it can be an issue in systems that\n * rely on digital signature uniqueness to ensure transaction integrity. For example, in Bitcoin,\n * transaction malleability is an issue because it allows for the modification of transaction\n * identifiers (and potentially, transactions themselves) after they're signed but before they're\n * confirmed in a block. By enforcing low `s` values, the Bitcoin network reduces the likelihood of\n * this occurring, making the system more secure and predictable.\n *\n * For this reason, it's common practice to normalize ECDSA signatures to a low-S form. This\n * form is considered standard and preferable in some systems and is known as the \"normalized\"\n * form of the signature.\n *\n * This method takes a signature, and if it's high-S, returns the normalized low-S form. If the\n * signature is already low-S, it's returned unmodified. It's important to note that this\n * method does not change the validity of the signature but makes it compliant with systems that\n * enforce low-S signatures.\n *\n * @example\n * ```ts\n * const signature = new Uint8Array([...]); // Your ECDSA signature\n * const adjustedSignature = await Secp256r1.adjustSignatureToLowS({ signature });\n * // Now 'adjustedSignature' is in the low-S form.\n * ```\n *\n * @param params - The parameters for the signature adjustment.\n * @param params.signature - The ECDSA signature as a `Uint8Array`.\n *\n * @returns A Promise that resolves to the adjusted signature in low-S form as a `Uint8Array`.\n */\n public static async adjustSignatureToLowS({ signature }: {\n signature: Uint8Array;\n }): Promise<Uint8Array> {\n // Convert the signature to a `Secp256r1.Signature` object.\n const signatureObject = secp256r1.Signature.fromCompact(signature);\n\n if (signatureObject.hasHighS()) {\n // Adjust the signature to low-S format if it's high-S.\n const adjustedSignatureObject = signatureObject.normalizeS();\n\n // Convert the adjusted signature object back to a byte array.\n const adjustedSignature = adjustedSignatureObject.toCompactRawBytes();\n\n return adjustedSignature;\n\n } else {\n // Return the unmodified signature if it is already in low-S format.\n return signature;\n }\n }\n\n /**\n * Converts a raw private key in bytes to its corresponding JSON Web Key (JWK) format.\n *\n * @remarks\n * This method takes a private key represented as a byte array (Uint8Array) and\n * converts it into a JWK object. The conversion involves extracting the\n * elliptic curve point (x and y coordinates) from the private key and encoding\n * them into base64url format, alongside other JWK parameters.\n *\n * The resulting JWK object includes the following properties:\n * - `kty`: Key Type, set to 'EC' for Elliptic Curve.\n * - `crv`: Curve Name, set to 'P-256'.\n * - `d`: The private key component, base64url-encoded.\n * - `x`: The x-coordinate of the public key point, base64url-encoded.\n * - `y`: The y-coordinate of the public key point, base64url-encoded.\n *\n * This method is useful for converting raw public keys into a standardized\n * JSON format, facilitating their use in cryptographic operations and making\n * them easy to share and store.\n *\n * @example\n * ```ts\n * const privateKeyBytes = new Uint8Array([...]); // Replace with actual private key bytes\n * const privateKey = await Secp256r1.bytesToPrivateKey({ privateKeyBytes });\n * ```\n *\n * @param params - The parameters for the private key conversion.\n * @param params.privateKeyBytes - The raw private key as a Uint8Array.\n *\n * @returns A Promise that resolves to the private key in JWK format.\n */\n public static async bytesToPrivateKey({ privateKeyBytes }: {\n privateKeyBytes: Uint8Array;\n }): Promise<Jwk> {\n // Get the elliptic curve points (x and y coordinates) for the provided private key.\n const point = await Secp256r1.getCurvePoint({ keyBytes: privateKeyBytes });\n\n // Construct the private key in JWK format.\n const privateKey: Jwk = {\n kty : 'EC',\n crv : 'P-256',\n d : Convert.uint8Array(privateKeyBytes).toBase64Url(),\n x : Convert.uint8Array(point.x).toBase64Url(),\n y : Convert.uint8Array(point.y).toBase64Url()\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n return privateKey;\n }\n\n /**\n * Converts a raw public key in bytes to its corresponding JSON Web Key (JWK) format.\n *\n * @remarks\n * This method accepts a public key in a byte array (Uint8Array) format and\n * transforms it to a JWK object. It involves decoding the elliptic curve point\n * (x and y coordinates) from the raw public key bytes and encoding them into\n * base64url format, along with setting appropriate JWK parameters.\n *\n * The resulting JWK object includes the following properties:\n * - `kty`: Key Type, set to 'EC' for Elliptic Curve.\n * - `crv`: Curve Name, set to 'P-256'.\n * - `x`: The x-coordinate of the public key point, base64url-encoded.\n * - `y`: The y-coordinate of the public key point, base64url-encoded.\n *\n * This method is useful for converting raw public keys into a standardized\n * JSON format, facilitating their use in cryptographic operations and making\n * them easy to share and store.\n *\n * @example\n * ```ts\n * const publicKeyBytes = new Uint8Array([...]); // Replace with actual public key bytes\n * const publicKey = await Secp256r1.bytesToPublicKey({ publicKeyBytes });\n * ```\n *\n * @param params - The parameters for the public key conversion.\n * @param params.publicKeyBytes - The raw public key as a Uint8Array.\n *\n * @returns A Promise that resolves to the public key in JWK format.\n */\n public static async bytesToPublicKey({ publicKeyBytes }: {\n publicKeyBytes: Uint8Array;\n }): Promise<Jwk> {\n // Get the elliptic curve point (x and y coordinates) for the provided public key.\n const point = await Secp256r1.getCurvePoint({ keyBytes: publicKeyBytes });\n\n // Construct the public key in JWK format.\n const publicKey: Jwk = {\n kty : 'EC',\n crv : 'P-256',\n x : Convert.uint8Array(point.x).toBase64Url(),\n y : Convert.uint8Array(point.y).toBase64Url()\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n publicKey.kid = await computeJwkThumbprint({ jwk: publicKey });\n\n return publicKey;\n }\n\n /**\n * Converts a public key to its compressed form.\n *\n * @remarks\n * This method takes a public key represented as a byte array and compresses it. Public key\n * compression is a process that reduces the size of the public key by removing the y-coordinate,\n * making it more efficient for storage and transmission. The compressed key retains the same\n * level of security as the uncompressed key.\n *\n * @example\n * ```ts\n * const uncompressedPublicKeyBytes = new Uint8Array([...]); // Replace with actual uncompressed public key bytes\n * const compressedPublicKey = await Secp256r1.compressPublicKey({\n * publicKeyBytes: uncompressedPublicKeyBytes\n * });\n * ```\n *\n * @param params - The parameters for the public key compression.\n * @param params.publicKeyBytes - The public key as a Uint8Array.\n *\n * @returns A Promise that resolves to the compressed public key as a Uint8Array.\n */\n public static async compressPublicKey({ publicKeyBytes }: {\n publicKeyBytes: Uint8Array;\n }): Promise<Uint8Array> {\n // Decode Weierstrass points from the public key byte array.\n const point = secp256r1.ProjectivePoint.fromHex(publicKeyBytes);\n\n // Return the compressed form of the public key.\n return point.toRawBytes(true);\n }\n\n /**\n * Derives the public key in JWK format from a given private key.\n *\n * @remarks\n * This method takes a private key in JWK format and derives its corresponding public key,\n * also in JWK format. The derivation process involves converting the private key to a raw\n * byte array, then computing the elliptic curve point (x and y coordinates) from this private\n * key. These coordinates are then encoded into base64url format to construct the public key in\n * JWK format.\n *\n * The process ensures that the derived public key correctly corresponds to the given private key,\n * adhering to the secp256r1 elliptic curve standards. This method is useful in cryptographic\n * operations where a public key is needed for operations like signature verification, but only\n * the private key is available.\n *\n * @example\n * ```ts\n * const privateKey = { ... }; // A Jwk object representing a secp256r1 private key\n * const publicKey = await Secp256r1.computePublicKey({ key: privateKey });\n * ```\n *\n * @param params - The parameters for the public key derivation.\n * @param params.key - The private key in JWK format from which to derive the public key.\n *\n * @returns A Promise that resolves to the derived public key in JWK format.\n */\n public static async computePublicKey({ key }:\n ComputePublicKeyParams\n ): Promise<Jwk> {\n // Convert the provided private key to a byte array.\n const privateKeyBytes = await Secp256r1.privateKeyToBytes({ privateKey: key });\n\n // Get the elliptic curve point (x and y coordinates) for the provided private key.\n const point = await Secp256r1.getCurvePoint({ keyBytes: privateKeyBytes });\n\n // Construct the public key in JWK format.\n const publicKey: Jwk = {\n kty : 'EC',\n crv : 'P-256',\n x : Convert.uint8Array(point.x).toBase64Url(),\n y : Convert.uint8Array(point.y).toBase64Url()\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n publicKey.kid = await computeJwkThumbprint({ jwk: publicKey });\n\n return publicKey;\n }\n\n /**\n * Converts an ASN.1 DER encoded ECDSA signature to a compact R+S format.\n *\n * @remarks\n * This method is used for converting an ECDSA signature from the ASN.1 DER encoding to the more\n * compact R+S format. This conversion is often required when dealing with ECDSA signatures in\n * certain cryptographic standards such as JWS (JSON Web Signature).\n *\n * The method decodes the DER-encoded signature, extracts the R and S values, and concatenates\n * them into a single byte array. This process involves handling the ASN.1 structure to correctly\n * parse the R and S values, considering padding and integer encoding specifics of DER.\n *\n * @example\n * ```ts\n * const derSignature = new Uint8Array([...]); // Replace with your DER-encoded signature\n * const signature = await Secp256r1.convertDerToCompactSignature({ derSignature });\n * ```\n *\n * @param params - The parameters for the signature conversion.\n * @param params.derSignature - The signature in ASN.1 DER format as a `Uint8Array`.\n *\n * @returns A Promise that resolves to the signature in compact R+S format as a `Uint8Array`.\n */\n public static async convertDerToCompactSignature({ derSignature }: {\n derSignature: Uint8Array;\n }): Promise<Uint8Array> {\n // Convert the DER-encoded signature into a `Secp256r1.Signature` object.\n // This involves parsing the ASN.1 DER structure to extract the R and S components.\n const signatureObject = secp256r1.Signature.fromDER(derSignature);\n\n // Convert the signature object into compact R+S format, which concatenates the R and S values\n // into a single byte array.\n const compactSignature = signatureObject.toCompactRawBytes();\n\n return compactSignature;\n }\n\n /**\n * Converts a public key to its uncompressed form.\n *\n * @remarks\n * This method takes a compressed public key represented as a byte array and decompresses it.\n * Public key decompression involves reconstructing the y-coordinate from the x-coordinate,\n * resulting in the full public key. This method is used when the uncompressed key format is\n * required for certain cryptographic operations or interoperability.\n *\n * @example\n * ```ts\n * const compressedPublicKeyBytes = new Uint8Array([...]); // Replace with actual compressed public key bytes\n * const decompressedPublicKey = await Secp256r1.decompressPublicKey({\n * publicKeyBytes: compressedPublicKeyBytes\n * });\n * ```\n *\n * @param params - The parameters for the public key decompression.\n * @param params.publicKeyBytes - The public key as a Uint8Array.\n *\n * @returns A Promise that resolves to the uncompressed public key as a Uint8Array.\n */\n public static async decompressPublicKey({ publicKeyBytes }: {\n publicKeyBytes: Uint8Array;\n }): Promise<Uint8Array> {\n // Decode Weierstrass points from the public key byte array.\n const point = secp256r1.ProjectivePoint.fromHex(publicKeyBytes);\n\n // Return the uncompressed form of the public key.\n return point.toRawBytes(false);\n }\n\n /**\n * Generates a secp256r1 private key in JSON Web Key (JWK) format.\n *\n * @remarks\n * This method creates a new private key suitable for use with the secp256r1\n * elliptic curve. The key is generated using cryptographically secure random\n * number generation to ensure its uniqueness and security. The resulting\n * private key adheres to the JWK format, specifically tailored for secp256r1,\n * making it compatible with common cryptographic standards and easy to use in\n * various cryptographic processes.\n *\n * The private key generated by this method includes the following components:\n * - `kty`: Key Type, set to 'EC' for Elliptic Curve.\n * - `crv`: Curve Name, set to 'P-256'.\n * - `d`: The private key component, base64url-encoded.\n * - `x`: The x-coordinate of the public key point, derived from the private key, base64url-encoded.\n * - `y`: The y-coordinate of the public key point, derived from the private key, base64url-encoded.\n *\n * The key is returned in a format suitable for direct use in signin and key agreement operations.\n *\n * @example\n * ```ts\n * const privateKey = await Secp256r1.generateKey();\n * ```\n *\n * @returns A Promise that resolves to the generated private key in JWK format.\n */\n public static async generateKey(): Promise<Jwk> {\n // Generate a random private key.\n const privateKeyBytes = secp256r1.utils.randomPrivateKey();\n\n // Convert private key from bytes to JWK format.\n const privateKey = await Secp256r1.bytesToPrivateKey({ privateKeyBytes });\n\n // Compute the JWK thumbprint and set as the key ID.\n privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n return privateKey;\n }\n\n /**\n * Retrieves the public key properties from a given private key in JWK format.\n *\n * @remarks\n * This method extracts the public key portion from a secp256r1 private key in JWK format. It does\n * so by removing the private key property 'd' and making a shallow copy, effectively yielding the\n * public key. The method sets the 'kid' (key ID) property using the JWK thumbprint if it is not\n * already defined. This approach is used under the assumption that a private key in JWK format\n * always contains the corresponding public key properties.\n *\n * Note: This method offers a significant performance advantage, being about 200 times faster\n * than `computePublicKey()`. However, it does not mathematically validate the private key, nor\n * does it derive the public key from the private key. It simply extracts existing public key\n * properties from the private key object. This makes it suitable for scenarios where speed is\n * critical and the private key's integrity is already assured.\n *\n * @example\n * ```ts\n * const privateKey = { ... }; // A Jwk object representing a secp256r1 private key\n * const publicKey = await Secp256r1.getPublicKey({ key: privateKey });\n * ```\n *\n * @param params - The parameters for retrieving the public key properties.\n * @param params.key - The private key in JWK format.\n *\n * @returns A Promise that resolves to the public key in JWK format.\n */\n public static async getPublicKey({ key }:\n GetPublicKeyParams\n ): Promise<Jwk> {\n // Verify the provided JWK represents an elliptic curve (EC) secp256r1 private key.\n if (!(isEcPrivateJwk(key) && key.crv === 'P-256')) {\n throw new Error(`Secp256r1: The provided key is not a 'P-256' private JWK.`);\n }\n\n // Remove the private key property ('d') and make a shallow copy of the provided key.\n const { d, ...publicKey } = key;\n\n // If the key ID is undefined, set it to the JWK thumbprint.\n publicKey.kid ??= await computeJwkThumbprint({ jwk: publicKey });\n\n return publicKey;\n }\n\n /**\n * Converts a private key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n *\n * @remarks\n * This method takes a private key in JWK format and extracts its raw byte representation.\n * It specifically focuses on the 'd' parameter of the JWK, which represents the private\n * key component in base64url encoding. The method decodes this value into a byte array.\n *\n * This conversion is essential for operations that require the private key in its raw\n * binary form, such as certain low-level cryptographic operations or when interfacing\n * with systems and libraries that expect keys in a byte array format.\n *\n * @example\n * ```ts\n * const privateKey = { ... }; // An X25519 private key in JWK format\n * const privateKeyBytes = await Secp256r1.privateKeyToBytes({ privateKey });\n * ```\n *\n * @param params - The parameters for the private key conversion.\n * @param params.privateKey - The private key in JWK format.\n *\n * @returns A Promise that resolves to the private key as a Uint8Array.\n */\n public static async privateKeyToBytes({ privateKey }: {\n privateKey: Jwk;\n }): Promise<Uint8Array> {\n // Verify the provided JWK represents a valid EC P-256 private key.\n if (!isEcPrivateJwk(privateKey)) {\n throw new Error(`Secp256r1: The provided key is not a valid EC private key.`);\n }\n\n // Decode the provided private key to bytes.\n const privateKeyBytes = Convert.base64Url(privateKey.d).toUint8Array();\n\n return privateKeyBytes;\n }\n\n /**\n * Converts a public key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n *\n * @remarks\n * This method accepts a public key in JWK format and converts it into its raw binary\n * form. The conversion process involves decoding the 'x' and 'y' parameters of the JWK\n * (which represent the x and y coordinates of the elliptic curve point, respectively)\n * from base64url format into a byte array. The method then concatenates these values,\n * along with a prefix indicating the key format, to form the full public key.\n *\n * This function is particularly useful for use cases where the public key is needed\n * in its raw byte format, such as for certain cryptographic operations or when\n * interfacing with systems that require raw key formats.\n *\n * @example\n * ```ts\n * const publicKey = { ... }; // A Jwk public key object\n * const publicKeyBytes = await Secp256r1.publicKeyToBytes({ publicKey });\n * ```\n *\n * @param params - The parameters for the public key conversion.\n * @param params.publicKey - The public key in JWK format.\n *\n * @returns A Promise that resolves to the public key as a Uint8Array.\n */\n public static async publicKeyToBytes({ publicKey }: {\n publicKey: Jwk;\n }): Promise<Uint8Array> {\n // Verify the provided JWK represents a valid EC P-256 public key, which must have a 'y' value.\n if (!(isEcPublicJwk(publicKey) && publicKey.y)) {\n throw new Error(`Secp256r1: The provided key is not a valid EC public key.`);\n }\n\n // Decode the provided public key to bytes.\n const prefix = new Uint8Array([0x04]); // Designates an uncompressed key.\n const x = Convert.base64Url(publicKey.x).toUint8Array();\n const y = Convert.base64Url(publicKey.y).toUint8Array();\n\n // Concatenate the prefix, x-coordinate, and y-coordinate as a single byte array.\n const publicKeyBytes = new Uint8Array([...prefix, ...x, ...y]);\n\n return publicKeyBytes;\n }\n\n /**\n * Computes an RFC6090-compliant Elliptic Curve Diffie-Hellman (ECDH) shared secret\n * using secp256r1 private and public keys in JSON Web Key (JWK) format.\n *\n * @remarks\n * This method facilitates the ECDH key agreement protocol, which is a method of securely\n * deriving a shared secret between two parties based on their private and public keys.\n * It takes the private key of one party (privateKeyA) and the public key of another\n * party (publicKeyB) to compute a shared secret. The shared secret is derived from the\n * x-coordinate of the elliptic curve point resulting from the multiplication of the\n * public key with the private key.\n *\n * Note: When performing Elliptic Curve Diffie-Hellman (ECDH) key agreement,\n * the resulting shared secret is a point on the elliptic curve, which\n * consists of an x-coordinate and a y-coordinate. With a 256-bit curve like\n * secp256r1, each of these coordinates is 32 bytes (256 bits) long. However,\n * in the ECDH process, it's standard practice to use only the x-coordinate\n * of the shared secret point as the resulting shared key. This is because\n * the y-coordinate does not add to the entropy of the key, and both parties\n * can independently compute the x-coordinate. Consquently, this implementation\n * omits the y-coordinate for simplicity and standard compliance.\n *\n * @example\n * ```ts\n * const privateKeyA = { ... }; // A Jwk private key object for party A\n * const publicKeyB = { ... }; // A Jwk public key object for party B\n * const sharedSecret = await Secp256r1.sharedSecret({\n * privateKeyA,\n * publicKeyB\n * });\n * ```\n *\n * @param params - The parameters for the shared secret computation.\n * @param params.privateKeyA - The private key in JWK format of one party.\n * @param params.publicKeyB - The public key in JWK format of the other party.\n *\n * @returns A Promise that resolves to the computed shared secret as a Uint8Array.\n */\n public static async sharedSecret({ privateKeyA, publicKeyB }: {\n privateKeyA: Jwk;\n publicKeyB: Jwk;\n }): Promise<Uint8Array> {\n // Ensure that keys from the same key pair are not specified.\n if ('x' in privateKeyA && 'x' in publicKeyB && privateKeyA.x === publicKeyB.x) {\n throw new Error(`Secp256r1: ECDH shared secret cannot be computed from a single key pair's public and private keys.`);\n }\n\n // Convert the provided private and public keys to bytes.\n const privateKeyABytes = await Secp256r1.privateKeyToBytes({ privateKey: privateKeyA });\n const publicKeyBBytes = await Secp256r1.publicKeyToBytes({ publicKey: publicKeyB });\n\n // Compute the compact representation shared secret between the public and private keys.\n const sharedSecret = secp256r1.getSharedSecret(privateKeyABytes, publicKeyBBytes, true);\n\n // Remove the leading byte that indicates the sign of the y-coordinate\n // of the point on the elliptic curve. See note above.\n return sharedSecret.slice(1);\n }\n\n /**\n * Generates an RFC6979-compliant ECDSA signature of given data using a secp256r1 private key.\n *\n * @remarks\n * This method signs the provided data with a specified private key using the ECDSA\n * (Elliptic Curve Digital Signature Algorithm) signature algorithm, as defined in RFC6979.\n * The data to be signed is first hashed using the SHA-256 algorithm, and this hash is then\n * signed using the private key. The output is a digital signature in the form of a\n * Uint8Array, which uniquely corresponds to both the data and the private key used for signing.\n *\n * This method is commonly used in cryptographic applications to ensure data integrity and\n * authenticity. The signature can later be verified by parties with access to the corresponding\n * public key, ensuring that the data has not been tampered with and was indeed signed by the\n * holder of the private key.\n *\n * @example\n * ```ts\n * const data = new TextEncoder().encode('Messsage'); // Data to be signed\n * const privateKey = { ... }; // A Jwk object representing a secp256r1 private key\n * const signature = await Secp256r1.sign({\n * key: privateKey,\n * data\n * });\n * ```\n *\n * @param params - The parameters for the signing operation.\n * @param params.key - The private key to use for signing, represented in JWK format.\n * @param params.data - The data to sign, represented as a Uint8Array.\n *\n * @returns A Promise that resolves to the signature as a Uint8Array.\n */\n public static async sign({ data, key }:\n SignParams\n ): Promise<Uint8Array> {\n // Convert the private key from JWK format to bytes.\n const privateKeyBytes = await Secp256r1.privateKeyToBytes({ privateKey: key });\n\n // Generate a digest of the data using the SHA-256 hash function.\n const digest = sha256(data);\n\n // Sign the provided data using the ECDSA algorithm.\n // The `Secp256r1.sign` operation returns a signature object with { r, s, recovery } properties.\n const signatureObject = secp256r1.sign(digest, privateKeyBytes);\n\n // Convert the signature object to Uint8Array.\n const signature = signatureObject.toCompactRawBytes();\n\n return signature;\n }\n\n /**\n * Validates a given private key to ensure its compliance with the secp256r1 curve standards.\n *\n * @remarks\n * This method checks whether a provided private key is a valid 32-byte number and falls within\n * the range defined by the secp256r1 curve's order. It is essential for ensuring the private\n * key's mathematical correctness in the context of secp256r1-based cryptographic operations.\n *\n * Note that this validation strictly pertains to the key's format and numerical validity; it does\n * not assess whether the key corresponds to a known entity or its security status (e.g., whether\n * it has been compromised).\n *\n * @example\n * ```ts\n * const privateKeyBytes = new Uint8Array([...]); // A 32-byte private key\n * const isValid = await Secp256r1.validatePrivateKey({ privateKeyBytes });\n * console.log(isValid); // true or false based on the key's validity\n * ```\n *\n * @param params - The parameters for the key validation.\n * @param params.privateKeyBytes - The private key to validate, represented as a Uint8Array.\n *\n * @returns A Promise that resolves to a boolean indicating whether the private key is valid.\n */\n public static async validatePrivateKey({ privateKeyBytes }: {\n privateKeyBytes: Uint8Array;\n }): Promise<boolean> {\n return secp256r1.utils.isValidPrivateKey(privateKeyBytes);\n }\n\n /**\n * Validates a given public key to confirm its mathematical correctness on the secp256r1 curve.\n *\n * @remarks\n * This method checks if the provided public key represents a valid point on the secp256r1 curve.\n * It decodes the key's Weierstrass points (x and y coordinates) and verifies their validity\n * against the curve's parameters. A valid point must lie on the curve and meet specific\n * mathematical criteria defined by the curve's equation.\n *\n * It's important to note that this method does not verify the key's ownership or whether it has\n * been compromised; it solely focuses on the key's adherence to the curve's mathematical\n * principles.\n *\n * @example\n * ```ts\n * const publicKeyBytes = new Uint8Array([...]); // A public key in byte format\n * const isValid = await Secp256r1.validatePublicKey({ publicKeyBytes });\n * console.log(isValid); // true if the key is valid on the secp256r1 curve, false otherwise\n * ```\n *\n * @param params - The parameters for the key validation.\n * @param params.publicKeyBytes - The public key to validate, represented as a Uint8Array.\n *\n * @returns A Promise that resolves to a boolean indicating the public key's validity on\n * the secp256r1 curve.\n */\n public static async validatePublicKey({ publicKeyBytes }: {\n publicKeyBytes: Uint8Array;\n }): Promise<boolean> {\n try {\n // Decode Weierstrass points from key bytes.\n const point = secp256r1.ProjectivePoint.fromHex(publicKeyBytes);\n\n // Check if points are on the Short Weierstrass curve.\n point.assertValidity();\n\n } catch {\n return false;\n }\n\n return true;\n }\n\n /**\n * Verifies an RFC6979-compliant ECDSA signature against given data and a secp256r1 public key.\n *\n * @remarks\n * This method validates a digital signature to ensure that it was generated by the holder of the\n * corresponding private key and that the signed data has not been altered. The signature\n * verification is performed using the ECDSA (Elliptic Curve Digital Signature Algorithm) as\n * specified in RFC6979. The data to be verified is first hashed using the SHA-256 algorithm, and\n * this hash is then used along with the public key to verify the signature.\n *\n * The method returns a boolean value indicating whether the signature is valid. A valid signature\n * proves that the signed data was indeed signed by the owner of the private key corresponding to\n * the provided public key and that the data has not been tampered with since it was signed.\n *\n * Note: The verification process does not consider the malleability of low-s signatures, which\n * may be relevant in certain contexts, such as Bitcoin transactions.\n *\n * @example\n * ```ts\n * const data = new TextEncoder().encode('Messsage'); // Data that was signed\n * const publicKey = { ... }; // Public key in JWK format corresponding to the private key that signed the data\n * const signature = new Uint8Array([...]); // Signature to verify\n * const isSignatureValid = await Secp256r1.verify({\n * key: publicKey,\n * signature,\n * data\n * });\n * console.log(isSignatureValid); // true if the signature is valid, false otherwise\n * ```\n *\n * @param params - The parameters for the signature verification.\n * @param params.key - The public key used for verification, represented in JWK format.\n * @param params.signature - The signature to verify, represented as a Uint8Array.\n * @param params.data - The data that was signed, represented as a Uint8Array.\n *\n * @returns A Promise that resolves to a boolean indicating whether the signature is valid.\n */\n public static async verify({ key, signature, data }:\n VerifyParams\n ): Promise<boolean> {\n // Convert the public key from JWK format to bytes.\n const publicKeyBytes = await Secp256r1.publicKeyToBytes({ publicKey: key });\n\n // Generate a digest of the data using the SHA-256 hash function.\n const digest = sha256(data);\n\n /** Perform the verification of the signature.\n * This verify operation has the malleability check disabled. Guaranteed support\n * for low-s signatures across languages is unlikely especially in the context\n * of SSI. Notable Cloud KMS providers do not natively support it either. It is\n * also worth noting that low-s signatures are a requirement for Bitcoin. */\n const isValid = secp256r1.verify(signature, digest, publicKeyBytes, { lowS: false });\n\n return isValid;\n }\n\n /**\n * Returns the elliptic curve point (x and y coordinates) for a given secp256r1 key.\n *\n * @remarks\n * This method extracts the elliptic curve point from a given secp256r1 key, whether\n * it's a private or a public key. For a private key, the method first computes the\n * corresponding public key and then extracts the x and y coordinates. For a public key,\n * it directly returns these coordinates. The coordinates are represented as Uint8Array.\n *\n * The x and y coordinates represent the key's position on the elliptic curve and can be\n * used in various cryptographic operations, such as digital signatures or key agreement\n * protocols.\n *\n * @example\n * ```ts\n * // For a private key\n * const privateKey = new Uint8Array([...]); // A 32-byte private key\n * const { x: xFromPrivateKey, y: yFromPrivateKey } = await Secp256r1.getCurvePoint({ keyBytes: privateKey });\n *\n * // For a public key\n * const publicKey = new Uint8Array([...]); // A 33-byte or 65-byte public key\n * const { x: xFromPublicKey, y: yFromPublicKey } = await Secp256r1.getCurvePoint({ keyBytes: publicKey });\n * ```\n *\n * @param params - The parameters for the curve point decoding operation.\n * @param params.keyBytes - The key for which to get the elliptic curve point.\n * Can be either a private key or a public key.\n * The key should be passed as a `Uint8Array`.\n *\n * @returns A Promise that resolves to an object with properties 'x' and 'y',\n * each being a Uint8Array representing the x and y coordinates of the key point on the\n * elliptic curve.\n */\n private static async getCurvePoint({ keyBytes }: {\n keyBytes: Uint8Array;\n }): Promise<AffinePoint<Uint8Array>> {\n // If key is a private key, first compute the public key.\n if (keyBytes.byteLength === 32) {\n keyBytes = secp256r1.getPublicKey(keyBytes);\n }\n\n // Decode Weierstrass affine point from key bytes.\n const point = secp256r1.ProjectivePoint.fromHex(keyBytes);\n\n // Get x- and y-coordinate values and convert to Uint8Array.\n const x = numberToBytesBE(point.x, 32);\n const y = numberToBytesBE(point.y, 32);\n\n return { x, y };\n }\n}\n\nexport { Secp256r1 as P256 };", "import type { AsymmetricKeyGenerator } from '../types/key-generator.js';\nimport type { Jwk } from '../jose/jwk.js';\nimport type { Signer } from '../types/signer.js';\nimport type {\n ComputePublicKeyParams,\n GenerateKeyParams,\n GetPublicKeyParams,\n SignParams,\n VerifyParams,\n} from '../types/params-direct.js';\n\nimport { CryptoAlgorithm } from './crypto-algorithm.js';\nimport { Secp256k1 } from '../primitives/secp256k1.js';\nimport { Secp256r1 } from '../primitives/secp256r1.js';\nimport { isEcPrivateJwk, isEcPublicJwk } from '../jose/jwk.js';\n\n/**\n * The `EcdsaGenerateKeyParams` interface defines the algorithm-specific parameters that should be\n * passed into the `generateKey()` method when using the ECDSA algorithm.\n */\nexport interface EcdsaGenerateKeyParams extends GenerateKeyParams {\n /**\n * A string defining the type of key to generate. The value must be one of the following:\n * - `\"ES256\"`: ECDSA using the secp256r1 (P-256) curve and SHA-256.\n * - `\"ES256K\"`: ECDSA using the secp256k1 curve and SHA-256.\n * - `\"secp256k1\"`: ECDSA using the secp256k1 curve and SHA-256.\n * - `\"secp256r1\"`: ECDSA using the secp256r1 (P-256) curve and SHA-256.\n */\n algorithm: 'ES256' | 'ES256K' | 'secp256k1' | 'secp256r1';\n}\n\n/**\n * The `EcdsaAlgorithm` class provides a concrete implementation for cryptographic operations using\n * the Elliptic Curve Digital Signature Algorithm (ECDSA). This class implements both\n * {@link Signer | `Signer`} and { @link AsymmetricKeyGenerator | `AsymmetricKeyGenerator`}\n * interfaces, providing private key generation, public key derivation, and creation/verification\n * of signatures.\n *\n * This class is typically accessed through implementations that extend the\n * {@link CryptoApi | `CryptoApi`} interface.\n */\nexport class EcdsaAlgorithm extends CryptoAlgorithm\n implements AsymmetricKeyGenerator<EcdsaGenerateKeyParams, Jwk, GetPublicKeyParams>,\n Signer<SignParams, VerifyParams> {\n\n /**\n * Derives the public key in JWK format from a given private key.\n *\n * @remarks\n * This method takes a private key in JWK format and derives its corresponding public key,\n * also in JWK format. The process ensures that the derived public key correctly corresponds to\n * the given private key.\n *\n * @example\n * ```ts\n * const ecdsa = new EcdsaAlgorithm();\n * const privateKey = { ... }; // A Jwk object representing a private key\n * const publicKey = await ecdsa.computePublicKey({ key: privateKey });\n * ```\n *\n * @param params - The parameters for the public key derivation.\n * @param params.key - The private key in JWK format from which to derive the public key.\n *\n * @returns A Promise that resolves to the derived public key in JWK format.\n */\n public async computePublicKey({ key }:\n ComputePublicKeyParams\n ): Promise<Jwk> {\n if (!isEcPrivateJwk(key)) {throw new TypeError('Invalid key provided. Must be an elliptic curve (EC) private key.');}\n\n switch (key.crv) {\n\n case 'secp256k1': {\n const publicKey = await Secp256k1.computePublicKey({ key });\n publicKey.alg = 'ES256K';\n return publicKey;\n }\n\n case 'P-256': {\n const publicKey = await Secp256r1.computePublicKey({ key });\n publicKey.alg = 'ES256';\n return publicKey;\n }\n\n default: {\n throw new Error(`Unsupported curve: ${key.crv}`);\n }\n }\n }\n\n /**\n * Generates a new private key with the specified algorithm in JSON Web Key (JWK) format.\n *\n * @example\n * ```ts\n * const ecdsa = new EcdsaAlgorithm();\n * const privateKey = await ecdsa.generateKey({ algorithm: 'ES256K' });\n * ```\n *\n * @param params - The parameters for key generation.\n * @param params.algorithm - The algorithm to use for key generation.\n *\n * @returns A Promise that resolves to the generated private key in JWK format.\n */\n public async generateKey({ algorithm }:\n EcdsaGenerateKeyParams\n ): Promise<Jwk> {\n switch (algorithm) {\n\n case 'ES256K':\n case 'secp256k1': {\n const privateKey = await Secp256k1.generateKey();\n privateKey.alg = 'ES256K';\n return privateKey;\n }\n\n case 'ES256':\n case 'secp256r1': {\n const privateKey = await Secp256r1.generateKey();\n privateKey.alg = 'ES256';\n return privateKey;\n }\n }\n }\n\n /**\n * Retrieves the public key properties from a given private key in JWK format.\n *\n * @remarks\n * This method extracts the public key portion from an ECDSA private key in JWK format. It does\n * so by removing the private key property 'd' and making a shallow copy, effectively yielding the\n * public key.\n *\n * Note: This method offers a significant performance advantage, being about 200 times faster\n * than `computePublicKey()`. However, it does not mathematically validate the private key, nor\n * does it derive the public key from the private key. It simply extracts existing public key\n * properties from the private key object. This makes it suitable for scenarios where speed is\n * critical and the private key's integrity is already assured.\n *\n * @example\n * ```ts\n * const ecdsa = new EcdsaAlgorithm();\n * const privateKey = { ... }; // A Jwk object representing a private key\n * const publicKey = await ecdsa.getPublicKey({ key: privateKey });\n * ```\n *\n * @param params - The parameters for retrieving the public key properties.\n * @param params.key - The private key in JWK format.\n *\n * @returns A Promise that resolves to the public key in JWK format.\n */\n public async getPublicKey({ key }:\n GetPublicKeyParams\n ): Promise<Jwk> {\n if (!isEcPrivateJwk(key)) {throw new TypeError('Invalid key provided. Must be an elliptic curve (EC) private key.');}\n\n switch (key.crv) {\n\n case 'secp256k1': {\n const publicKey = await Secp256k1.getPublicKey({ key });\n publicKey.alg = 'ES256K';\n return publicKey;\n }\n\n case 'P-256': {\n const publicKey = await Secp256r1.getPublicKey({ key });\n publicKey.alg = 'ES256';\n return publicKey;\n }\n\n default: {\n throw new Error(`Unsupported curve: ${key.crv}`);\n }\n }\n }\n\n /**\n * Generates an ECDSA signature of given data using a private key.\n *\n * @remarks\n * This method uses the signature algorithm determined by the given `algorithm` to sign the\n * provided data.\n *\n * The signature can later be verified by parties with access to the corresponding\n * public key, ensuring that the data has not been tampered with and was indeed signed by the\n * holder of the private key.\n *\n * @example\n * ```ts\n * const ecdsa = new EcdsaAlgorithm();\n * const data = new TextEncoder().encode('Message');\n * const privateKey = { ... }; // A Jwk object representing a private key\n * const signature = await ecdsa.sign({\n * key: privateKey,\n * data\n * });\n * ```\n *\n * @param params - The parameters for the signing operation.\n * @param params.key - The private key to use for signing, represented in JWK format.\n * @param params.data - The data to sign.\n *\n * @returns A Promise resolving to the digital signature as a `Uint8Array`.\n */\n public async sign({ key, data }:\n SignParams\n ): Promise<Uint8Array> {\n if (!isEcPrivateJwk(key)) {throw new TypeError('Invalid key provided. Must be an elliptic curve (EC) private key.');}\n\n switch (key.crv) {\n\n case 'secp256k1': {\n return await Secp256k1.sign({ key, data });\n }\n\n case 'P-256': {\n return await Secp256r1.sign({ key, data });\n }\n\n default: {\n throw new Error(`Unsupported curve: ${key.crv}`);\n }\n }\n }\n\n /**\n * Verifies an ECDSA signature associated with the provided data using the provided key.\n *\n * @remarks\n * This method uses the signature algorithm determined by the `crv` property of the provided key\n * to check the validity of a digital signature against the original data. It confirms whether the\n * signature was created by the holder of the corresponding private key and that the data has not\n * been tampered with.\n *s\n * @example\n * ```ts\n * const ecdsa = new EcdsaAlgorithm();\n * const publicKey = { ... }; // Public key in JWK format corresponding to the private key that signed the data\n * const signature = new Uint8Array([...]); // Signature to verify\n * const data = new TextEncoder().encode('Message');\n * const isValid = await ecdsa.verify({\n * key: publicKey,\n * signature,\n * data\n * });\n * ```\n *\n * @param params - The parameters for the verification operation.\n * @param params.key - The key to use for verification.\n * @param params.signature - The signature to verify.\n * @param params.data - The data to verify.\n *\n * @returns A Promise resolving to a boolean indicating whether the signature is valid.\n */\n public async verify({ key, signature, data }:\n VerifyParams\n ): Promise<boolean> {\n if (!isEcPublicJwk(key)) {throw new TypeError('Invalid key provided. Must be an elliptic curve (EC) public key.');}\n\n switch (key.crv) {\n\n case 'secp256k1': {\n return await Secp256k1.verify({ key, signature, data });\n }\n\n case 'P-256': {\n return await Secp256r1.verify({ key, signature, data });\n }\n\n default: {\n throw new Error(`Unsupported curve: ${key.crv}`);\n }\n }\n }\n}", "const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\n// We are not using BigUint64Array, because they are extremely slow as per 2022\nfunction fromBig(n: bigint, le = false) {\n if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n\nfunction split(lst: bigint[], le = false) {\n let Ah = new Uint32Array(lst.length);\n let Al = new Uint32Array(lst.length);\n for (let i = 0; i < lst.length; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n\nconst toBig = (h: number, l: number) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number) => h >>> s;\nconst shrSL = (h: number, l: number, s: number) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h: number, l: number, s: number) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number) => l;\nconst rotr32L = (h: number, _l: number) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h: number, l: number, s: number) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number) => (h << (s - 32)) | (l >>> (64 - s));\n\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah: number, Al: number, Bh: number, Bl: number) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al: number, Bl: number, Cl: number) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number) =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number) =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number) =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number) =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n", "import { SHA2 } from './_sha2.js';\nimport u64 from './_u64.js';\nimport { wrapConstructor } from './utils.js';\n\n// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):\n// prettier-ignore\nconst [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\n\n// Temporary buffer, not used to store anything between runs\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends SHA2<SHA512> {\n // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.\n // Also looks cleaner and easier to verify with spec.\n // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n // h -- high 32 bits, l -- low 32 bits\n Ah = 0x6a09e667 | 0;\n Al = 0xf3bcc908 | 0;\n Bh = 0xbb67ae85 | 0;\n Bl = 0x84caa73b | 0;\n Ch = 0x3c6ef372 | 0;\n Cl = 0xfe94f82b | 0;\n Dh = 0xa54ff53a | 0;\n Dl = 0x5f1d36f1 | 0;\n Eh = 0x510e527f | 0;\n El = 0xade682d1 | 0;\n Fh = 0x9b05688c | 0;\n Fl = 0x2b3e6c1f | 0;\n Gh = 0x1f83d9ab | 0;\n Gl = 0xfb41bd6b | 0;\n Hh = 0x5be0cd19 | 0;\n Hl = 0x137e2179 | 0;\n\n constructor() {\n super(128, 64, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean() {\n SHA512_W_H.fill(0);\n SHA512_W_L.fill(0);\n }\n destroy() {\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\nclass SHA512_224 extends SHA512 {\n // h -- high 32 bits, l -- low 32 bits\n Ah = 0x8c3d37c8 | 0;\n Al = 0x19544da2 | 0;\n Bh = 0x73e19966 | 0;\n Bl = 0x89dcd4d6 | 0;\n Ch = 0x1dfab7ae | 0;\n Cl = 0x32ff9c82 | 0;\n Dh = 0x679dd514 | 0;\n Dl = 0x582f9fcf | 0;\n Eh = 0x0f6d2b69 | 0;\n El = 0x7bd44da8 | 0;\n Fh = 0x77e36f73 | 0;\n Fl = 0x04c48942 | 0;\n Gh = 0x3f9d85a8 | 0;\n Gl = 0x6a1d36c8 | 0;\n Hh = 0x1112e6ad | 0;\n Hl = 0x91d692a1 | 0;\n\n constructor() {\n super();\n this.outputLen = 28;\n }\n}\n\nclass SHA512_256 extends SHA512 {\n // h -- high 32 bits, l -- low 32 bits\n Ah = 0x22312194 | 0;\n Al = 0xfc2bf72c | 0;\n Bh = 0x9f555fa3 | 0;\n Bl = 0xc84c64c2 | 0;\n Ch = 0x2393b86b | 0;\n Cl = 0x6f53b151 | 0;\n Dh = 0x96387719 | 0;\n Dl = 0x5940eabd | 0;\n Eh = 0x96283ee2 | 0;\n El = 0xa88effe3 | 0;\n Fh = 0xbe5e1e25 | 0;\n Fl = 0x53863992 | 0;\n Gh = 0x2b0199fc | 0;\n Gl = 0x2c85b8aa | 0;\n Hh = 0x0eb72ddc | 0;\n Hl = 0x81c52ca2 | 0;\n\n constructor() {\n super();\n this.outputLen = 32;\n }\n}\n\nclass SHA384 extends SHA512 {\n // h -- high 32 bits, l -- low 32 bits\n Ah = 0xcbbb9d5d | 0;\n Al = 0xc1059ed8 | 0;\n Bh = 0x629a292a | 0;\n Bl = 0x367cd507 | 0;\n Ch = 0x9159015a | 0;\n Cl = 0x3070dd17 | 0;\n Dh = 0x152fecd8 | 0;\n Dl = 0xf70e5939 | 0;\n Eh = 0x67332667 | 0;\n El = 0xffc00b31 | 0;\n Fh = 0x8eb44a87 | 0;\n Fl = 0x68581511 | 0;\n Gh = 0xdb0c2e0d | 0;\n Gl = 0x64f98fa7 | 0;\n Hh = 0x47b5481d | 0;\n Hl = 0xbefa4fa4 | 0;\n\n constructor() {\n super();\n this.outputLen = 48;\n }\n}\n\nexport const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());\nexport const sha512_224 = /* @__PURE__ */ wrapConstructor(() => new SHA512_224());\nexport const sha512_256 = /* @__PURE__ */ wrapConstructor(() => new SHA512_256());\nexport const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384());\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Twisted Edwards curve. The formula is: ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2\nimport { mod } from './modular.js';\nimport * as ut from './utils.js';\nimport { ensureBytes, FHash, Hex } from './utils.js';\nimport { Group, GroupConstructor, wNAF, BasicCurve, validateBasic, AffinePoint } from './curve.js';\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\n\n// Edwards curves must declare params a & d.\nexport type CurveType = BasicCurve<bigint> & {\n a: bigint; // curve param a\n d: bigint; // curve param d\n hash: FHash; // Hashing\n randomBytes: (bytesLength?: number) => Uint8Array; // CSPRNG\n adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; // clears bits to get valid field elemtn\n domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; // Used for hashing\n uvRatio?: (u: bigint, v: bigint) => { isValid: boolean; value: bigint }; // Ratio \u221A(u/v)\n prehash?: FHash; // RFC 8032 pre-hashing of messages to sign() / verify()\n mapToCurve?: (scalar: bigint[]) => AffinePoint<bigint>; // for hash-to-curve standard\n};\n\n// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\nconst VERIFY_DEFAULT = { zip215: true };\n\nfunction validateOpts(curve: CurveType) {\n const opts = validateBasic(curve);\n ut.validateObject(\n curve,\n {\n hash: 'function',\n a: 'bigint',\n d: 'bigint',\n randomBytes: 'function',\n },\n {\n adjustScalarBytes: 'function',\n domain: 'function',\n uvRatio: 'function',\n mapToCurve: 'function',\n }\n );\n // Set defaults\n return Object.freeze({ ...opts } as const);\n}\n\n// Instance of Extended Point with coordinates in X, Y, Z, T\nexport interface ExtPointType extends Group<ExtPointType> {\n readonly ex: bigint;\n readonly ey: bigint;\n readonly ez: bigint;\n readonly et: bigint;\n get x(): bigint;\n get y(): bigint;\n assertValidity(): void;\n multiply(scalar: bigint): ExtPointType;\n multiplyUnsafe(scalar: bigint): ExtPointType;\n isSmallOrder(): boolean;\n isTorsionFree(): boolean;\n clearCofactor(): ExtPointType;\n toAffine(iz?: bigint): AffinePoint<bigint>;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n toHex(isCompressed?: boolean): string;\n}\n// Static methods of Extended Point with coordinates in X, Y, Z, T\nexport interface ExtPointConstructor extends GroupConstructor<ExtPointType> {\n new (x: bigint, y: bigint, z: bigint, t: bigint): ExtPointType;\n fromAffine(p: AffinePoint<bigint>): ExtPointType;\n fromHex(hex: Hex): ExtPointType;\n fromPrivateKey(privateKey: Hex): ExtPointType;\n}\n\nexport type CurveFn = {\n CURVE: ReturnType<typeof validateOpts>;\n getPublicKey: (privateKey: Hex) => Uint8Array;\n sign: (message: Hex, privateKey: Hex, options?: { context?: Hex }) => Uint8Array;\n verify: (\n sig: Hex,\n message: Hex,\n publicKey: Hex,\n options?: { context?: Hex; zip215: boolean }\n ) => boolean;\n ExtendedPoint: ExtPointConstructor;\n utils: {\n randomPrivateKey: () => Uint8Array;\n getExtendedPublicKey: (key: Hex) => {\n head: Uint8Array;\n prefix: Uint8Array;\n scalar: bigint;\n point: ExtPointType;\n pointBytes: Uint8Array;\n };\n };\n};\n\n// It is not generic twisted curve for now, but ed25519/ed448 generic implementation\nexport function twistedEdwards(curveDef: CurveType): CurveFn {\n const CURVE = validateOpts(curveDef) as ReturnType<typeof validateOpts>;\n const {\n Fp,\n n: CURVE_ORDER,\n prehash: prehash,\n hash: cHash,\n randomBytes,\n nByteLength,\n h: cofactor,\n } = CURVE;\n const MASK = _2n << (BigInt(nByteLength * 8) - _1n);\n const modP = Fp.create; // Function overrides\n\n // sqrt(u/v)\n const uvRatio =\n CURVE.uvRatio ||\n ((u: bigint, v: bigint) => {\n try {\n return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) };\n } catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes: Uint8Array) => bytes); // NOOP\n const domain =\n CURVE.domain ||\n ((data: Uint8Array, ctx: Uint8Array, phflag: boolean) => {\n if (ctx.length || phflag) throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n const inBig = (n: bigint) => typeof n === 'bigint' && _0n < n; // n in [1..]\n const inRange = (n: bigint, max: bigint) => inBig(n) && inBig(max) && n < max; // n in [1..max-1]\n const in0MaskRange = (n: bigint) => n === _0n || inRange(n, MASK); // n in [0..MASK-1]\n function assertInRange(n: bigint, max: bigint) {\n // n in [1..max-1]\n if (inRange(n, max)) return n;\n throw new Error(`Expected valid scalar < ${max}, got ${typeof n} ${n}`);\n }\n function assertGE0(n: bigint) {\n // n in [0..CURVE_ORDER-1]\n return n === _0n ? n : assertInRange(n, CURVE_ORDER); // GE = prime subgroup, not full group\n }\n const pointPrecomputes = new Map<Point, Point[]>();\n function isPoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ExtendedPoint expected');\n }\n // Extended Point works in extended coordinates: (x, y, z, t) \u220B (x=x/z, y=y/z, t=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point implements ExtPointType {\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n static readonly ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n\n constructor(\n readonly ex: bigint,\n readonly ey: bigint,\n readonly ez: bigint,\n readonly et: bigint\n ) {\n if (!in0MaskRange(ex)) throw new Error('x required');\n if (!in0MaskRange(ey)) throw new Error('y required');\n if (!in0MaskRange(ez)) throw new Error('z required');\n if (!in0MaskRange(et)) throw new Error('t required');\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\n }\n\n static fromAffine(p: AffinePoint<bigint>): Point {\n if (p instanceof Point) throw new Error('extended point not allowed');\n const { x, y } = p || {};\n if (!in0MaskRange(x) || !in0MaskRange(y)) throw new Error('invalid affine point');\n return new Point(x, y, _1n, modP(x * y));\n }\n static normalizeZ(points: Point[]): Point[] {\n const toInv = Fp.invertBatch(points.map((p) => p.ez));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n _WINDOW_SIZE?: number;\n\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize: number) {\n this._WINDOW_SIZE = windowSize;\n pointPrecomputes.delete(this);\n }\n // Not required for fromHex(), which always creates valid points.\n // Could be useful for fromAffine().\n assertValidity(): void {\n const { a, d } = CURVE;\n if (this.is0()) throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX\u00B2 + Y\u00B2)Z\u00B2 = Z\u2074 + dX\u00B2Y\u00B2\n const { ex: X, ey: Y, ez: Z, et: T } = this;\n const X2 = modP(X * X); // X\u00B2\n const Y2 = modP(Y * Y); // Y\u00B2\n const Z2 = modP(Z * Z); // Z\u00B2\n const Z4 = modP(Z2 * Z2); // Z\u2074\n const aX2 = modP(X2 * a); // aX\u00B2\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX\u00B2 + Y\u00B2)Z\u00B2\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z\u2074 + dX\u00B2Y\u00B2\n if (left !== right) throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT) throw new Error('bad point: equation left != right (2)');\n }\n\n // Compare one point to another.\n equals(other: Point): boolean {\n isPoint(other);\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const { ex: X2, ey: Y2, ez: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n\n protected is0(): boolean {\n return this.equals(Point.ZERO);\n }\n\n negate(): Point {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et));\n }\n\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double(): Point {\n const { a } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other: Point) {\n isPoint(other);\n const { a, d } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;\n const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;\n // Faster algo for adding 2 Extended Points when curve's a=-1.\n // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4\n // Cost: 8M + 8add + 2*2.\n // Note: It does not check whether the `other` point is valid.\n if (a === BigInt(-1)) {\n const A = modP((Y1 - X1) * (Y2 + X2));\n const B = modP((Y1 + X1) * (Y2 - X2));\n const F = modP(B - A);\n if (F === _0n) return this.double(); // Same point. Tests say it doesn't affect timing\n const C = modP(Z1 * _2n * T2);\n const D = modP(T1 * _2n * Z2);\n const E = D + C;\n const G = B + A;\n const H = D - C;\n const X3 = modP(E * F);\n const Y3 = modP(G * H);\n const T3 = modP(E * H);\n const Z3 = modP(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n\n return new Point(X3, Y3, Z3, T3);\n }\n\n subtract(other: Point): Point {\n return this.add(other.negate());\n }\n\n private wNAF(n: bigint): { p: Point; f: Point } {\n return wnaf.wNAFCached(this, pointPrecomputes, n, Point.normalizeZ);\n }\n\n // Constant-time multiplication.\n multiply(scalar: bigint): Point {\n const { p, f } = this.wNAF(assertInRange(scalar, CURVE_ORDER));\n return Point.normalizeZ([p, f])[0];\n }\n\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n multiplyUnsafe(scalar: bigint): Point {\n let n = assertGE0(scalar); // 0 <= scalar < CURVE.n\n if (n === _0n) return I;\n if (this.equals(I) || n === _1n) return this;\n if (this.equals(G)) return this.wNAF(n).p;\n return wnaf.unsafeLadder(this, n);\n }\n\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder(): boolean {\n return this.multiplyUnsafe(cofactor).is0();\n }\n\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree(): boolean {\n return wnaf.unsafeLadder(this, CURVE_ORDER).is0();\n }\n\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(iz?: bigint): AffinePoint<bigint> {\n const { ex: x, ey: y, ez: z } = this;\n const is0 = this.is0();\n if (iz == null) iz = is0 ? _8n : (Fp.inv(z) as bigint); // 8 was chosen arbitrarily\n const ax = modP(x * iz);\n const ay = modP(y * iz);\n const zz = modP(z * iz);\n if (is0) return { x: _0n, y: _1n };\n if (zz !== _1n) throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n }\n\n clearCofactor(): Point {\n const { h: cofactor } = CURVE;\n if (cofactor === _1n) return this;\n return this.multiplyUnsafe(cofactor);\n }\n\n // Converts hash string or Uint8Array to Point.\n // Uses algo from RFC8032 5.1.3.\n static fromHex(hex: Hex, zip215 = false): Point {\n const { d, a } = CURVE;\n const len = Fp.BYTES;\n hex = ensureBytes('pointHex', hex, len); // copy hex to a new array\n const normed = hex.slice(); // copy again, we'll manipulate it\n const lastByte = hex[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = ut.bytesToNumberLE(normed);\n if (y === _0n) {\n // y=0 is allowed\n } else {\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n if (zip215) assertInRange(y, MASK); // zip215=true [1..P-1] (2^255-19-1 for ed25519)\n else assertInRange(y, Fp.ORDER); // zip215=false [1..MASK-1] (2^256-1 for ed25519)\n }\n\n // Ed25519: x\u00B2 = (y\u00B2-1)/(dy\u00B2+1) mod p. Ed448: x\u00B2 = (y\u00B2-1)/(dy\u00B2-1) mod p. Generic case:\n // ax\u00B2+y\u00B2=1+dx\u00B2y\u00B2 => y\u00B2-1=dx\u00B2y\u00B2-ax\u00B2 => y\u00B2-1=x\u00B2(dy\u00B2-a) => x\u00B2=(y\u00B2-1)/(dy\u00B2-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y\u00B2 - 1\n const v = modP(d * y2 - a); // v = d y\u00B2 + 1.\n let { isValid, value: x } = uvRatio(u, v); // \u221A(u/v)\n if (!isValid) throw new Error('Point.fromHex: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('Point.fromHex: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd) x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromPrivateKey(privKey: Hex) {\n return getExtendedPublicKey(privKey).point;\n }\n toRawBytes(): Uint8Array {\n const { x, y } = this.toAffine();\n const bytes = ut.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y)\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y\n return bytes; // and use the last byte to encode sign of x\n }\n toHex(): string {\n return ut.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string.\n }\n }\n const { BASE: G, ZERO: I } = Point;\n const wnaf = wNAF(Point, nByteLength * 8);\n\n function modN(a: bigint) {\n return mod(a, CURVE_ORDER);\n }\n // Little-endian SHA512 with modulo n\n function modN_LE(hash: Uint8Array): bigint {\n return modN(ut.bytesToNumberLE(hash));\n }\n\n /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */\n function getExtendedPublicKey(key: Hex) {\n const len = nByteLength;\n key = ensureBytes('private key', key, len);\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n const point = G.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toRawBytes(); // Uint8Array representation\n return { head, prefix, scalar, point, pointBytes };\n }\n\n // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared\n function getPublicKey(privKey: Hex): Uint8Array {\n return getExtendedPublicKey(privKey).pointBytes;\n }\n\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context: Hex = new Uint8Array(), ...msgs: Uint8Array[]) {\n const msg = ut.concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));\n }\n\n /** Signs message with privateKey. RFC8032 5.1.6 */\n function sign(msg: Hex, privKey: Hex, options: { context?: Hex } = {}): Uint8Array {\n msg = ensureBytes('message', msg);\n if (prehash) msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = G.multiply(r).toRawBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = modN(r + k * scalar); // S = (r + k * s) mod L\n assertGE0(s); // 0 <= s < l\n const res = ut.concatBytes(R, ut.numberToBytesLE(s, Fp.BYTES));\n return ensureBytes('result', res, nByteLength * 2); // 64-byte signature\n }\n\n const verifyOpts: { context?: Hex; zip215?: boolean } = VERIFY_DEFAULT;\n function verify(sig: Hex, msg: Hex, publicKey: Hex, options = verifyOpts): boolean {\n const { context, zip215 } = options;\n const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked.\n msg = ensureBytes('message', msg);\n if (prehash) msg = prehash(msg); // for ed25519ph, etc\n\n const s = ut.bytesToNumberLE(sig.slice(len, 2 * len));\n // zip215: true is good for consensus-critical apps and allows points < 2^256\n // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p\n let A, R, SB;\n try {\n A = Point.fromHex(publicKey, zip215);\n R = Point.fromHex(sig.slice(0, len), zip215);\n SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside\n } catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder()) return false;\n\n const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);\n }\n\n G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n\n const utils = {\n getExtendedPublicKey,\n // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1.\n randomPrivateKey: (): Uint8Array => randomBytes(Fp.BYTES),\n\n /**\n * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT\n * values. This slows down first getPublicKey() by milliseconds (see Speed section),\n * but allows to speed-up subsequent getPublicKey() calls up to 20x.\n * @param windowSize 2, 4, 8, 16\n */\n precompute(windowSize = 8, point = Point.BASE): typeof Point.BASE {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3));\n return point;\n },\n };\n\n return {\n CURVE,\n getPublicKey,\n sign,\n verify,\n ExtendedPoint: Point,\n utils,\n };\n}\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { mod, pow } from './modular.js';\nimport { bytesToNumberLE, ensureBytes, numberToBytesLE, validateObject } from './utils.js';\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\ntype Hex = string | Uint8Array;\n\nexport type CurveType = {\n P: bigint; // finite field prime\n nByteLength: number;\n adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array;\n domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array;\n a: bigint;\n montgomeryBits: number;\n powPminus2?: (x: bigint) => bigint;\n xyToU?: (x: bigint, y: bigint) => bigint;\n Gu: bigint;\n randomBytes?: (bytesLength?: number) => Uint8Array;\n};\nexport type CurveFn = {\n scalarMult: (scalar: Hex, u: Hex) => Uint8Array;\n scalarMultBase: (scalar: Hex) => Uint8Array;\n getSharedSecret: (privateKeyA: Hex, publicKeyB: Hex) => Uint8Array;\n getPublicKey: (privateKey: Hex) => Uint8Array;\n utils: { randomPrivateKey: () => Uint8Array };\n GuBytes: Uint8Array;\n};\n\nfunction validateOpts(curve: CurveType) {\n validateObject(\n curve,\n {\n a: 'bigint',\n },\n {\n montgomeryBits: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n adjustScalarBytes: 'function',\n domain: 'function',\n powPminus2: 'function',\n Gu: 'bigint',\n }\n );\n // Set defaults\n return Object.freeze({ ...curve } as const);\n}\n\n// NOTE: not really montgomery curve, just bunch of very specific methods for X25519/X448 (RFC 7748, https://www.rfc-editor.org/rfc/rfc7748)\n// Uses only one coordinate instead of two\nexport function montgomery(curveDef: CurveType): CurveFn {\n const CURVE = validateOpts(curveDef);\n const { P } = CURVE;\n const modP = (n: bigint) => mod(n, P);\n const montgomeryBits = CURVE.montgomeryBits;\n const montgomeryBytes = Math.ceil(montgomeryBits / 8);\n const fieldLen = CURVE.nByteLength;\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes: Uint8Array) => bytes);\n const powPminus2 = CURVE.powPminus2 || ((x: bigint) => pow(x, P - BigInt(2), P));\n\n // cswap from RFC7748. But it is not from RFC7748!\n /*\n cswap(swap, x_2, x_3):\n dummy = mask(swap) AND (x_2 XOR x_3)\n x_2 = x_2 XOR dummy\n x_3 = x_3 XOR dummy\n Return (x_2, x_3)\n Where mask(swap) is the all-1 or all-0 word of the same length as x_2\n and x_3, computed, e.g., as mask(swap) = 0 - swap.\n */\n function cswap(swap: bigint, x_2: bigint, x_3: bigint): [bigint, bigint] {\n const dummy = modP(swap * (x_2 - x_3));\n x_2 = modP(x_2 - dummy);\n x_3 = modP(x_3 + dummy);\n return [x_2, x_3];\n }\n\n // Accepts 0 as well\n function assertFieldElement(n: bigint): bigint {\n if (typeof n === 'bigint' && _0n <= n && n < P) return n;\n throw new Error('Expected valid scalar 0 < scalar < CURVE.P');\n }\n\n // x25519 from 4\n // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519\n const a24 = (CURVE.a - BigInt(2)) / BigInt(4);\n /**\n *\n * @param pointU u coordinate (x) on Montgomery Curve 25519\n * @param scalar by which the point would be multiplied\n * @returns new Point on Montgomery curve\n */\n function montgomeryLadder(pointU: bigint, scalar: bigint): bigint {\n const u = assertFieldElement(pointU);\n // Section 5: Implementations MUST accept non-canonical values and process them as\n // if they had been reduced modulo the field prime.\n const k = assertFieldElement(scalar);\n const x_1 = u;\n let x_2 = _1n;\n let z_2 = _0n;\n let x_3 = u;\n let z_3 = _1n;\n let swap = _0n;\n let sw: [bigint, bigint];\n for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {\n const k_t = (k >> t) & _1n;\n swap ^= k_t;\n sw = cswap(swap, x_2, x_3);\n x_2 = sw[0];\n x_3 = sw[1];\n sw = cswap(swap, z_2, z_3);\n z_2 = sw[0];\n z_3 = sw[1];\n swap = k_t;\n\n const A = x_2 + z_2;\n const AA = modP(A * A);\n const B = x_2 - z_2;\n const BB = modP(B * B);\n const E = AA - BB;\n const C = x_3 + z_3;\n const D = x_3 - z_3;\n const DA = modP(D * A);\n const CB = modP(C * B);\n const dacb = DA + CB;\n const da_cb = DA - CB;\n x_3 = modP(dacb * dacb);\n z_3 = modP(x_1 * modP(da_cb * da_cb));\n x_2 = modP(AA * BB);\n z_2 = modP(E * (AA + modP(a24 * E)));\n }\n // (x_2, x_3) = cswap(swap, x_2, x_3)\n sw = cswap(swap, x_2, x_3);\n x_2 = sw[0];\n x_3 = sw[1];\n // (z_2, z_3) = cswap(swap, z_2, z_3)\n sw = cswap(swap, z_2, z_3);\n z_2 = sw[0];\n z_3 = sw[1];\n // z_2^(p - 2)\n const z2 = powPminus2(z_2);\n // Return x_2 * (z_2^(p - 2))\n return modP(x_2 * z2);\n }\n\n function encodeUCoordinate(u: bigint): Uint8Array {\n return numberToBytesLE(modP(u), montgomeryBytes);\n }\n\n function decodeUCoordinate(uEnc: Hex): bigint {\n // Section 5: When receiving such an array, implementations of X25519\n // MUST mask the most significant bit in the final byte.\n const u = ensureBytes('u coordinate', uEnc, montgomeryBytes);\n if (fieldLen === 32) u[31] &= 127; // 0b0111_1111\n return bytesToNumberLE(u);\n }\n function decodeScalar(n: Hex): bigint {\n const bytes = ensureBytes('scalar', n);\n const len = bytes.length;\n if (len !== montgomeryBytes && len !== fieldLen)\n throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${len}`);\n return bytesToNumberLE(adjustScalarBytes(bytes));\n }\n function scalarMult(scalar: Hex, u: Hex): Uint8Array {\n const pointU = decodeUCoordinate(u);\n const _scalar = decodeScalar(scalar);\n const pu = montgomeryLadder(pointU, _scalar);\n // The result was not contributory\n // https://cr.yp.to/ecdh.html#validate\n if (pu === _0n) throw new Error('Invalid private or public key received');\n return encodeUCoordinate(pu);\n }\n // Computes public key from private. By doing scalar multiplication of base point.\n const GuBytes = encodeUCoordinate(CURVE.Gu);\n function scalarMultBase(scalar: Hex): Uint8Array {\n return scalarMult(scalar, GuBytes);\n }\n\n return {\n scalarMult,\n scalarMultBase,\n getSharedSecret: (privateKey: Hex, publicKey: Hex) => scalarMult(privateKey, publicKey),\n getPublicKey: (privateKey: Hex): Uint8Array => scalarMultBase(privateKey),\n utils: { randomPrivateKey: () => CURVE.randomBytes!(CURVE.nByteLength) },\n GuBytes: GuBytes,\n };\n}\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha512';\nimport { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils';\nimport { ExtPointType, twistedEdwards } from './abstract/edwards.js';\nimport { montgomery } from './abstract/montgomery.js';\nimport { Field, FpSqrtEven, isNegativeLE, mod, pow2 } from './abstract/modular.js';\nimport {\n bytesToHex,\n bytesToNumberLE,\n ensureBytes,\n equalBytes,\n Hex,\n numberToBytesLE,\n} from './abstract/utils.js';\nimport { createHasher, htfBasicOpts, expand_message_xmd } from './abstract/hash-to-curve.js';\nimport { AffinePoint, Group } from './abstract/curve.js';\n\n/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n */\n\nconst ED25519_P = BigInt(\n '57896044618658097711785492504343953926634992332820282019728792003956564819949'\n);\n// \u221A(-1) aka \u221A(a) aka 2^((p-1)/4)\nconst ED25519_SQRT_M1 = BigInt(\n '19681161376707505956807079304988542015446066515923890162744021073123829784752'\n);\n\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _5n = BigInt(5);\n// prettier-ignore\nconst _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n\nfunction ed25519_pow_2_252_3(x: bigint) {\n const P = ED25519_P;\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P; // x^3, 11\n const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111\n const b5 = (pow2(b4, _1n, P) * x) % P; // x^31\n const b10 = (pow2(b5, _5n, P) * b5) % P;\n const b20 = (pow2(b10, _10n, P) * b10) % P;\n const b40 = (pow2(b20, _20n, P) * b20) % P;\n const b80 = (pow2(b40, _40n, P) * b40) % P;\n const b160 = (pow2(b80, _80n, P) * b80) % P;\n const b240 = (pow2(b160, _80n, P) * b80) % P;\n const b250 = (pow2(b240, _10n, P) * b10) % P;\n const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;\n // ^ To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n}\n\nfunction adjustScalarBytes(bytes: Uint8Array): Uint8Array {\n // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n // set the three least significant bits of the first byte\n bytes[0] &= 248; // 0b1111_1000\n // and the most significant bit of the last to zero,\n bytes[31] &= 127; // 0b0111_1111\n // set the second most significant bit of the last byte to 1\n bytes[31] |= 64; // 0b0100_0000\n return bytes;\n}\n\n// sqrt(u/v)\nfunction uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } {\n const P = ED25519_P;\n const v3 = mod(v * v * v, P); // v\u00B3\n const v7 = mod(v3 * v3 * v, P); // v\u2077\n // (p+3)/8 and (p-5)/8\n const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n let x = mod(u * v3 * pow, P); // (uv\u00B3)(uv\u2077)^(p-5)/8\n const vx2 = mod(v * x * x, P); // vx\u00B2\n const root1 = x; // First root candidate\n const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate\n const useRoot1 = vx2 === u; // If vx\u00B2 = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u, P); // If vx\u00B2 = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx\u00B2 = -u\u221A(-1)\n if (useRoot1) x = root1;\n if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time\n if (isNegativeLE(x, P)) x = mod(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\n\n// Just in case\nexport const ED25519_TORSION_SUBGROUP = [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n];\n\nconst Fp = Field(ED25519_P, undefined, true);\n\nconst ed25519Defaults = {\n // Param: a\n a: BigInt(-1), // Fp.create(-1) is proper; our way still works and is faster\n // d is equal to -121665/121666 over finite field.\n // Negative number is P - number, and division is invert(number, P)\n d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),\n // Finite field \uD835\uDD3Dp over which we'll do calculations; 2n**255n - 19n\n Fp,\n // Subgroup order: how many points curve has\n // 2n**252n + 27742317777372353535851937790883648493n;\n n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'),\n // Cofactor\n h: BigInt(8),\n // Base point (x, y) aka generator point\n Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),\n Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),\n hash: sha512,\n randomBytes,\n adjustScalarBytes,\n // dom2\n // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.\n // Constant-time, u/\u221Av\n uvRatio,\n} as const;\n\nexport const ed25519 = /* @__PURE__ */ twistedEdwards(ed25519Defaults);\n\nfunction ed25519_domain(data: Uint8Array, ctx: Uint8Array, phflag: boolean) {\n if (ctx.length > 255) throw new Error('Context is too big');\n return concatBytes(\n utf8ToBytes('SigEd25519 no Ed25519 collisions'),\n new Uint8Array([phflag ? 1 : 0, ctx.length]),\n ctx,\n data\n );\n}\n\nexport const ed25519ctx = /* @__PURE__ */ twistedEdwards({\n ...ed25519Defaults,\n domain: ed25519_domain,\n});\nexport const ed25519ph = /* @__PURE__ */ twistedEdwards({\n ...ed25519Defaults,\n domain: ed25519_domain,\n prehash: sha512,\n});\n\nexport const x25519 = /* @__PURE__ */ (() =>\n montgomery({\n P: ED25519_P,\n a: BigInt(486662),\n montgomeryBits: 255, // n is 253 bits\n nByteLength: 32,\n Gu: BigInt(9),\n powPminus2: (x: bigint): bigint => {\n const P = ED25519_P;\n // x^(p-2) aka x^(2^255-21)\n const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n return mod(pow2(pow_p_5_8, BigInt(3), P) * b2, P);\n },\n adjustScalarBytes,\n randomBytes,\n }))();\n\n/**\n * Converts ed25519 public key to x25519 public key. Uses formula:\n * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * @example\n * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey());\n * const aPriv = x25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub))\n */\nexport function edwardsToMontgomeryPub(edwardsPub: Hex): Uint8Array {\n const { y } = ed25519.ExtendedPoint.fromHex(edwardsPub);\n const _1n = BigInt(1);\n return Fp.toBytes(Fp.create((_1n + y) * Fp.inv(_1n - y)));\n}\nexport const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated\n\n/**\n * Converts ed25519 secret key to x25519 secret key.\n * @example\n * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey());\n * const aPriv = ed25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub)\n */\nexport function edwardsToMontgomeryPriv(edwardsPriv: Uint8Array): Uint8Array {\n const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32));\n return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32);\n}\n\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since\n// SageMath returns different root first and everything falls apart\n\nconst ELL2_C1 = (Fp.ORDER + BigInt(3)) / BigInt(8); // 1. c1 = (q + 3) / 8 # Integer arithmetic\n\nconst ELL2_C2 = Fp.pow(_2n, ELL2_C1); // 2. c2 = 2^c1\nconst ELL2_C3 = Fp.sqrt(Fp.neg(Fp.ONE)); // 3. c3 = sqrt(-1)\nconst ELL2_C4 = (Fp.ORDER - BigInt(5)) / BigInt(8); // 4. c4 = (q - 5) / 8 # Integer arithmetic\nconst ELL2_J = BigInt(486662);\n\n// prettier-ignore\nfunction map_to_curve_elligator2_curve25519(u: bigint) {\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)\n let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2\n tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4\n tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3\n tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3\n tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7\n let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)\n y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3\n tv2 = Fp.sqr(y11); // 19. tv2 = y11^2\n tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd\n let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1\n let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd\n let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u\n y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2\n let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3\n let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n tv2 = Fp.sqr(y21); // 28. tv2 = y21^2\n tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2\n let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n tv2 = Fp.sqr(y1); // 32. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd\n let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2\n let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)\n return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)\n}\n\nconst ELL2_C1_EDWARDS = FpSqrtEven(Fp, Fp.neg(BigInt(486664))); // sgn0(c1) MUST equal 0\nfunction map_to_curve_elligator2_edwards25519(u: bigint) {\n const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) =\n // map_to_curve_elligator2_curve25519(u)\n let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd\n xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1\n let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM\n let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd\n let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd\n let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0\n xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)\n xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)\n yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)\n yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)\n\n const inv = Fp.invertBatch([xd, yd]); // batch division\n return { x: Fp.mul(xn, inv[0]), y: Fp.mul(yn, inv[1]) }; // 13. return (xn, xd, yn, yd)\n}\n\nconst htf = /* @__PURE__ */ (() =>\n createHasher(\n ed25519.ExtendedPoint,\n (scalars: bigint[]) => map_to_curve_elligator2_edwards25519(scalars[0]),\n {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n }\n ))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n\nfunction assertRstPoint(other: unknown) {\n if (!(other instanceof RistPoint)) throw new Error('RistrettoPoint expected');\n}\n\n// \u221A(-1) aka \u221A(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// \u221A(ad - 1)\nconst SQRT_AD_MINUS_ONE = BigInt(\n '25063068953384623474111414158702152701244531502492656460079210482610430750235'\n);\n// 1 / \u221A(a-d)\nconst INVSQRT_A_MINUS_D = BigInt(\n '54469307008909316920995813868745141605393597292927456921205312896311721017578'\n);\n// 1-d\u00B2\nconst ONE_MINUS_D_SQ = BigInt(\n '1159843021668779879193775521855586647937357759715417654439879720876111806838'\n);\n// (d-1)\u00B2\nconst D_MINUS_ONE_SQ = BigInt(\n '40440834346308536858101042469323190826248399146238708352240133220865137265952'\n);\n// Calculates 1/\u221A(number)\nconst invertSqrt = (number: bigint) => uvRatio(_1n, number);\n\nconst MAX_255B = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\nconst bytes255ToNumberLE = (bytes: Uint8Array) =>\n ed25519.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n\ntype ExtendedPoint = ExtPointType;\n\n// Computes Elligator map for Ristretto\n// https://ristretto.group/formulas/elligator.html\nfunction calcElligatorRistrettoMap(r0: bigint): ExtendedPoint {\n const { d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const r = mod(SQRT_M1 * r0 * r0); // 1\n const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = mod((c - d * r) * mod(r + d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = mod(s * r0); // 6\n if (!isNegativeLE(s_, P)) s_ = mod(-s_);\n if (!Ns_D_is_sq) s = s_; // 7\n if (!Ns_D_is_sq) c = r; // 8\n const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9\n const s2 = s * s;\n const W0 = mod((s + s) * D); // 10\n const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11\n const W2 = mod(_1n - s2); // 12\n const W3 = mod(_1n + s2); // 13\n return new ed25519.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n\n/**\n * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint,\n * but it should work in its own namespace: do not combine those two.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448\n */\nclass RistPoint implements Group<RistPoint> {\n static BASE: RistPoint;\n static ZERO: RistPoint;\n // Private property to discourage combining ExtendedPoint + RistrettoPoint\n // Always use Ristretto encoding/decoding instead.\n constructor(private readonly ep: ExtendedPoint) {}\n\n static fromAffine(ap: AffinePoint<bigint>) {\n return new RistPoint(ed25519.ExtendedPoint.fromAffine(ap));\n }\n\n /**\n * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`.\n * The hash-to-group operation applies Elligator twice and adds the results.\n * **Note:** this is one-way map, there is no conversion from point to hash.\n * https://ristretto.group/formulas/elligator.html\n * @param hex 64-byte output of a hash function\n */\n static hashToCurve(hex: Hex): RistPoint {\n hex = ensureBytes('ristrettoHash', hex, 64);\n const r1 = bytes255ToNumberLE(hex.slice(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(hex.slice(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new RistPoint(R1.add(R2));\n }\n\n /**\n * Converts ristretto-encoded string to ristretto point.\n * https://ristretto.group/formulas/decoding.html\n * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex: Hex): RistPoint {\n hex = ensureBytes('ristrettoHex', hex, 32);\n const { a, d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint';\n const s = bytes255ToNumberLE(hex);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 3. Check that s is non-negative, or else abort\n if (!equalBytes(numberToBytesLE(s, 32), hex) || isNegativeLE(s, P)) throw new Error(emsg);\n const s2 = mod(s * s);\n const u1 = mod(_1n + a * s2); // 4 (a is -1)\n const u2 = mod(_1n - a * s2); // 5\n const u1_2 = mod(u1 * u1);\n const u2_2 = mod(u2 * u2);\n const v = mod(a * d * u1_2 - u2_2); // 6\n const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7\n const Dx = mod(I * u2); // 8\n const Dy = mod(I * Dx * v); // 9\n let x = mod((s + s) * Dx); // 10\n if (isNegativeLE(x, P)) x = mod(-x); // 10\n const y = mod(u1 * Dy); // 11\n const t = mod(x * y); // 12\n if (!isValid || isNegativeLE(t, P) || y === _0n) throw new Error(emsg);\n return new RistPoint(new ed25519.ExtendedPoint(x, y, _1n, t));\n }\n\n /**\n * Encodes ristretto point to Uint8Array.\n * https://ristretto.group/formulas/encoding.html\n */\n toRawBytes(): Uint8Array {\n let { ex: x, ey: y, ez: z, et: t } = this.ep;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const u1 = mod(mod(z + y) * mod(z - y)); // 1\n const u2 = mod(x * y); // 2\n // Square root always exists\n const u2sq = mod(u2 * u2);\n const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3\n const D1 = mod(invsqrt * u1); // 4\n const D2 = mod(invsqrt * u2); // 5\n const zInv = mod(D1 * D2 * t); // 6\n let D: bigint; // 7\n if (isNegativeLE(t * zInv, P)) {\n let _x = mod(y * SQRT_M1);\n let _y = mod(x * SQRT_M1);\n x = _x;\n y = _y;\n D = mod(D1 * INVSQRT_A_MINUS_D);\n } else {\n D = D2; // 8\n }\n if (isNegativeLE(x * zInv, P)) y = mod(-y); // 9\n let s = mod((z - y) * D); // 10 (check footer's note, no sqrt(-a))\n if (isNegativeLE(s, P)) s = mod(-s);\n return numberToBytesLE(s, 32); // 11\n }\n\n toHex(): string {\n return bytesToHex(this.toRawBytes());\n }\n\n toString(): string {\n return this.toHex();\n }\n\n // Compare one point to another.\n equals(other: RistPoint): boolean {\n assertRstPoint(other);\n const { ex: X1, ey: Y1 } = this.ep;\n const { ex: X2, ey: Y2 } = other.ep;\n const mod = ed25519.CURVE.Fp.create;\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = mod(X1 * Y2) === mod(Y1 * X2);\n const two = mod(Y1 * Y2) === mod(X1 * X2);\n return one || two;\n }\n\n add(other: RistPoint): RistPoint {\n assertRstPoint(other);\n return new RistPoint(this.ep.add(other.ep));\n }\n\n subtract(other: RistPoint): RistPoint {\n assertRstPoint(other);\n return new RistPoint(this.ep.subtract(other.ep));\n }\n\n multiply(scalar: bigint): RistPoint {\n return new RistPoint(this.ep.multiply(scalar));\n }\n\n multiplyUnsafe(scalar: bigint): RistPoint {\n return new RistPoint(this.ep.multiplyUnsafe(scalar));\n }\n\n double(): RistPoint {\n return new RistPoint(this.ep.double());\n }\n\n negate(): RistPoint {\n return new RistPoint(this.ep.negate());\n }\n}\nexport const RistrettoPoint = /* @__PURE__ */ (() => {\n if (!RistPoint.BASE) RistPoint.BASE = new RistPoint(ed25519.ExtendedPoint.BASE);\n if (!RistPoint.ZERO) RistPoint.ZERO = new RistPoint(ed25519.ExtendedPoint.ZERO);\n return RistPoint;\n})();\n\n// Hashing to ristretto255. https://www.rfc-editor.org/rfc/rfc9380#appendix-B\nexport const hashToRistretto255 = (msg: Uint8Array, options: htfBasicOpts) => {\n const d = options.DST;\n const DST = typeof d === 'string' ? utf8ToBytes(d) : d;\n const uniform_bytes = expand_message_xmd(msg, DST, 64, sha512);\n const P = RistPoint.hashToCurve(uniform_bytes);\n return P;\n};\nexport const hash_to_ristretto255 = hashToRistretto255; // legacy\n", "import { Convert } from '@enbox/common';\nimport { ed25519, edwardsToMontgomeryPriv, edwardsToMontgomeryPub, x25519 } from '@noble/curves/ed25519';\n\nimport type { Jwk } from '../jose/jwk.js';\nimport type { ComputePublicKeyParams, GetPublicKeyParams, SignParams, VerifyParams } from '../types/params-direct.js';\n\nimport { computeJwkThumbprint, isOkpPrivateJwk, isOkpPublicJwk } from '../jose/jwk.js';\n\n/**\n * The `Ed25519` class provides a comprehensive suite of utilities for working with the Ed25519\n * elliptic curve, widely used in modern cryptographic applications. This class includes methods for\n * key generation, conversion, signing, verification, and public key derivation.\n *\n * The class supports conversions between raw byte formats and JSON Web Key (JWK) formats. It\n * follows the guidelines and specifications outlined in RFC8032 for EdDSA (Edwards-curve Digital\n * Signature Algorithm) operations.\n *\n * Key Features:\n * - Key Generation: Generate Ed25519 private keys in JWK format.\n * - Key Conversion: Transform keys between raw byte arrays and JWK formats.\n * - Public Key Derivation: Derive public keys from private keys.\n * - Signing and Verification: Sign data and verify signatures with Ed25519 keys.\n * - Key Validation: Validate the mathematical correctness of Ed25519 keys.\n *\n * The methods in this class are asynchronous, returning Promises to accommodate various\n * JavaScript environments, and use `Uint8Array` for binary data handling.\n *\n * @example\n * ```ts\n * // Key Generation\n * const privateKey = await Ed25519.generateKey();\n *\n * // Public Key Derivation\n * const publicKey = await Ed25519.computePublicKey({ key: privateKey });\n * console.log(publicKey === await Ed25519.getPublicKey({ key: privateKey })); // Output: true\n *\n * // EdDSA Signing\n * const signature = await Ed25519.sign({\n * key: privateKey,\n * data: new TextEncoder().encode('Message')\n * });\n *\n * // EdDSA Signature Verification\n * const isValid = await Ed25519.verify({\n * key: publicKey,\n * signature: signature,\n * data: new TextEncoder().encode('Message')\n * });\n *\n * // Key Conversion\n * const privateKeyBytes = await Ed25519.privateKeyToBytes({ privateKey });\n * const publicKeyBytes = await Ed25519.publicKeyToBytes({ publicKey });\n *\n * // Key Validation\n * const isPublicKeyValid = await Ed25519.validatePublicKey({ publicKeyBytes });\n * ```\n */\nexport class Ed25519 {\n /**\n * Converts a raw private key in bytes to its corresponding JSON Web Key (JWK) format.\n *\n * @remarks\n * This method accepts a private key as a byte array (Uint8Array) for the Curve25519 curve in\n * Twisted Edwards form and transforms it into a JWK object. The process involves first deriving\n * the public key from the private key, then encoding both the private and public keys into\n * base64url format.\n *\n * The resulting JWK object includes the following properties:\n * - `kty`: Key Type, set to 'OKP' for Octet Key Pair.\n * - `crv`: Curve Name, set to 'Ed25519'.\n * - `d`: The private key component, base64url-encoded.\n * - `x`: The computed public key, base64url-encoded.\n *\n * @example\n * ```ts\n * const privateKeyBytes = new Uint8Array([...]); // Replace with actual private key bytes\n * const privateKey = await Ed25519.bytesToPrivateKey({ privateKeyBytes });\n * ```\n *\n * @param params - The parameters for the private key conversion.\n * @param params.privateKeyBytes - The raw private key as a Uint8Array.\n *\n * @returns A Promise that resolves to the private key in JWK format.\n */\n public static async bytesToPrivateKey({ privateKeyBytes }: {\n privateKeyBytes: Uint8Array;\n }): Promise<Jwk> {\n // Derive the public key from the private key.\n const publicKeyBytes = ed25519.getPublicKey(privateKeyBytes);\n\n // Construct the private key in JWK format.\n const privateKey: Jwk = {\n crv : 'Ed25519',\n d : Convert.uint8Array(privateKeyBytes).toBase64Url(),\n kty : 'OKP',\n x : Convert.uint8Array(publicKeyBytes).toBase64Url(),\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n return privateKey;\n }\n\n /**\n * Converts a raw private key in bytes to its corresponding JSON Web Key (JWK) format.\n *\n * @remarks\n * This method accepts a public key as a byte array (Uint8Array) for the Curve25519 curve in\n * Twisted Edwards form and transforms it into a JWK object. The process involves encoding the\n * public key bytes into base64url format.\n *\n * The resulting JWK object includes the following properties:\n * - `kty`: Key Type, set to 'OKP' for Octet Key Pair.\n * - `crv`: Curve Name, set to 'X25519'.\n * - `x`: The public key, base64url-encoded.\n *\n * @example\n * ```ts\n * const publicKeyBytes = new Uint8Array([...]); // Replace with actual public key bytes\n * const publicKey = await X25519.bytesToPublicKey({ publicKeyBytes });\n * ```\n *\n * @param params - The parameters for the public key conversion.\n * @param params.publicKeyBytes - The raw public key as a `Uint8Array`.\n *\n * @returns A Promise that resolves to the public key in JWK format.\n */\n public static async bytesToPublicKey({ publicKeyBytes }: {\n publicKeyBytes: Uint8Array;\n }): Promise<Jwk> {\n // Construct the public key in JWK format.\n const publicKey: Jwk = {\n kty : 'OKP',\n crv : 'Ed25519',\n x : Convert.uint8Array(publicKeyBytes).toBase64Url(),\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n publicKey.kid = await computeJwkThumbprint({ jwk: publicKey });\n\n return publicKey;\n }\n\n /**\n * Derives the public key in JWK format from a given Ed25519 private key.\n *\n * @remarks\n * This method takes a private key in JWK format and derives its corresponding public key,\n * also in JWK format. The derivation process involves converting the private key to a\n * raw byte array and then computing the corresponding public key on the Curve25519 curve in\n * Twisted Edwards form. The public key is then encoded into base64url format to construct\n * a JWK representation.\n *\n * @example\n * ```ts\n * const privateKey = { ... }; // A Jwk object representing an Ed25519 private key\n * const publicKey = await Ed25519.computePublicKey({ key: privateKey });\n * ```\n *\n * @param params - The parameters for the public key derivation.\n * @param params.key - The private key in JWK format from which to derive the public key.\n *\n * @returns A Promise that resolves to the computed public key in JWK format.\n */\n public static async computePublicKey({ key }:\n ComputePublicKeyParams\n ): Promise<Jwk> {\n // Convert the provided private key to a byte array.\n const privateKeyBytes = await Ed25519.privateKeyToBytes({ privateKey: key });\n\n // Derive the public key from the private key.\n const publicKeyBytes = ed25519.getPublicKey(privateKeyBytes);\n\n // Construct the public key in JWK format.\n const publicKey: Jwk = {\n kty : 'OKP',\n crv : 'Ed25519',\n x : Convert.uint8Array(publicKeyBytes).toBase64Url()\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n publicKey.kid = await computeJwkThumbprint({ jwk: publicKey });\n\n return publicKey;\n }\n\n /**\n * Converts an Ed25519 private key to its X25519 counterpart.\n *\n * @remarks\n * This method enables the use of the same key pair for both digital signature (Ed25519)\n * and key exchange (X25519) operations. It takes an Ed25519 private key and converts it\n * to the corresponding X25519 format, facilitating interoperability between signing\n * and encryption protocols.\n *\n * @example\n * ```ts\n * const ed25519PrivateKey = { ... }; // An Ed25519 private key in JWK format\n * const x25519PrivateKey = await Ed25519.convertPrivateKeyToX25519({\n * privateKey: ed25519PrivateKey\n * });\n * ```\n *\n * @param params - The parameters for the private key conversion.\n * @param params.privateKey - The Ed25519 private key to convert, in JWK format.\n *\n * @returns A Promise that resolves to the X25519 private key in JWK format.\n */\n public static async convertPrivateKeyToX25519({ privateKey }: {\n privateKey: Jwk;\n }): Promise<Jwk> {\n // Convert the provided Ed25519 private key to bytes.\n const ed25519PrivateKeyBytes = await Ed25519.privateKeyToBytes({ privateKey });\n\n // Convert the Ed25519 private key to an X25519 private key.\n const x25519PrivateKeyBytes = edwardsToMontgomeryPriv(ed25519PrivateKeyBytes);\n\n // Derive the X25519 public key from the X25519 private key.\n const x25519PublicKeyBytes = x25519.getPublicKey(x25519PrivateKeyBytes);\n\n // Construct the X25519 private key in JWK format.\n const x25519PrivateKey: Jwk = {\n kty : 'OKP',\n crv : 'X25519',\n d : Convert.uint8Array(x25519PrivateKeyBytes).toBase64Url(),\n x : Convert.uint8Array(x25519PublicKeyBytes).toBase64Url(),\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n x25519PrivateKey.kid = await computeJwkThumbprint({ jwk: x25519PrivateKey });\n\n return x25519PrivateKey;\n }\n\n /**\n * Converts an Ed25519 public key to its X25519 counterpart.\n *\n * @remarks\n * This method enables the use of the same key pair for both digital signature (Ed25519)\n * and key exchange (X25519) operations. It takes an Ed25519 public key and converts it\n * to the corresponding X25519 format, facilitating interoperability between signing\n * and encryption protocols.\n *\n * @example\n * ```ts\n * const ed25519PublicKey = { ... }; // An Ed25519 public key in JWK format\n * const x25519PublicKey = await Ed25519.convertPublicKeyToX25519({\n * publicKey: ed25519PublicKey\n * });\n * ```\n *\n * @param params - The parameters for the public key conversion.\n * @param params.publicKey - The Ed25519 public key to convert, in JWK format.\n *\n * @returns A Promise that resolves to the X25519 public key in JWK format.\n */\n public static async convertPublicKeyToX25519({ publicKey }: {\n publicKey: Jwk;\n }): Promise<Jwk> {\n // Convert the provided private key to a byte array.\n const ed25519PublicKeyBytes = await Ed25519.publicKeyToBytes({ publicKey });\n\n // Verify Edwards public key is valid.\n const isValid = await Ed25519.validatePublicKey({ publicKeyBytes: ed25519PublicKeyBytes });\n if (!isValid) {\n throw new Error('Ed25519: Invalid public key.');\n }\n\n // Convert the Ed25519 public key to an X25519 private key.\n const x25519PublicKeyBytes = edwardsToMontgomeryPub(ed25519PublicKeyBytes);\n\n // Construct the X25519 private key in JWK format.\n const x25519PublicKey: Jwk = {\n kty : 'OKP',\n crv : 'X25519',\n x : Convert.uint8Array(x25519PublicKeyBytes).toBase64Url(),\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n x25519PublicKey.kid = await computeJwkThumbprint({ jwk: x25519PublicKey });\n\n return x25519PublicKey;\n }\n\n /**\n * Generates an Ed25519 private key in JSON Web Key (JWK) format.\n *\n * @remarks\n * This method creates a new private key suitable for use with the Curve25519 elliptic curve in\n * Twisted Edwards form. The key generation process involves using cryptographically secure\n * random number generation to ensure the uniqueness and security of the key. The resulting\n * private key adheres to the JWK format making it compatible with common cryptographic\n * standards and easy to use in various cryptographic processes.\n *\n * The generated private key in JWK format includes the following components:\n * - `kty`: Key Type, set to 'OKP' for Octet Key Pair.\n * - `crv`: Curve Name, set to 'Ed25519'.\n * - `d`: The private key component, base64url-encoded.\n * - `x`: The derived public key, base64url-encoded.\n *\n * @example\n * ```ts\n * const privateKey = await Ed25519.generateKey();\n * ```\n *\n * @returns A Promise that resolves to the generated private key in JWK format.\n */\n public static async generateKey(): Promise<Jwk> {\n // Generate a random private key.\n const privateKeyBytes = ed25519.utils.randomPrivateKey();\n\n // Convert private key from bytes to JWK format.\n const privateKey = await Ed25519.bytesToPrivateKey({ privateKeyBytes });\n\n // Compute the JWK thumbprint and set as the key ID.\n privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n return privateKey;\n }\n\n /**\n * Retrieves the public key properties from a given private key in JWK format.\n *\n * @remarks\n * This method extracts the public key portion from an Ed25519 private key in JWK format. It does\n * so by removing the private key property 'd' and making a shallow copy, effectively yielding the\n * public key. The method sets the 'kid' (key ID) property using the JWK thumbprint if it is not\n * already defined. This approach is used under the assumption that a private key in JWK format\n * always contains the corresponding public key properties.\n *\n * Note: This method offers a significant performance advantage, being about 100 times faster\n * than `computePublicKey()`. However, it does not mathematically validate the private key, nor\n * does it derive the public key from the private key. It simply extracts existing public key\n * properties from the private key object. This makes it suitable for scenarios where speed is\n * critical and the private key's integrity is already assured.\n *\n * @example\n * ```ts\n * const privateKey = { ... }; // A Jwk object representing an Ed25519 private key\n * const publicKey = await Ed25519.getPublicKey({ key: privateKey });\n * ```\n *\n * @param params - The parameters for retrieving the public key properties.\n * @param params.key - The private key in JWK format.\n *\n * @returns A Promise that resolves to the public key in JWK format.\n */\n public static async getPublicKey({ key }:\n GetPublicKeyParams\n ): Promise<Jwk> {\n // Verify the provided JWK represents an octet key pair (OKP) Ed25519 private key.\n if (!(isOkpPrivateJwk(key) && key.crv === 'Ed25519')) {\n throw new Error(`Ed25519: The provided key is not an Ed25519 private JWK.`);\n }\n\n // Remove the private key property ('d') and make a shallow copy of the provided key.\n const { d, ...publicKey } = key;\n\n // If the key ID is undefined, set it to the JWK thumbprint.\n publicKey.kid ??= await computeJwkThumbprint({ jwk: publicKey });\n\n return publicKey;\n }\n\n /**\n * Converts a private key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n *\n * @remarks\n * This method accepts a private key in JWK format and extracts its raw byte representation.\n *\n * This method accepts a public key in JWK format and converts it into its raw binary\n * form. The conversion process involves decoding the 'd' parameter of the JWK\n * from base64url format into a byte array.\n *\n * @example\n * ```ts\n * const privateKey = { ... }; // An Ed25519 private key in JWK format\n * const privateKeyBytes = await Ed25519.privateKeyToBytes({ privateKey });\n * ```\n *\n * @param params - The parameters for the private key conversion.\n * @param params.privateKey - The private key in JWK format.\n *\n * @returns A Promise that resolves to the private key as a Uint8Array.\n */\n public static async privateKeyToBytes({ privateKey }: {\n privateKey: Jwk;\n }): Promise<Uint8Array> {\n // Verify the provided JWK represents a valid OKP private key.\n if (!isOkpPrivateJwk(privateKey)) {\n throw new Error(`Ed25519: The provided key is not a valid OKP private key.`);\n }\n\n // Decode the provided private key to bytes.\n const privateKeyBytes = Convert.base64Url(privateKey.d).toUint8Array();\n\n return privateKeyBytes;\n }\n\n /**\n * Converts a public key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n *\n * @remarks\n * This method accepts a public key in JWK format and converts it into its raw binary form.\n * The conversion process involves decoding the 'x' parameter of the JWK (which represent the\n * x coordinate of the elliptic curve point) from base64url format into a byte array.\n *\n * @example\n * ```ts\n * const publicKey = { ... }; // An Ed25519 public key in JWK format\n * const publicKeyBytes = await Ed25519.publicKeyToBytes({ publicKey });\n * ```\n *\n * @param params - The parameters for the public key conversion.\n * @param params.publicKey - The public key in JWK format.\n *\n * @returns A Promise that resolves to the public key as a Uint8Array.\n */\n public static async publicKeyToBytes({ publicKey }: {\n publicKey: Jwk;\n }): Promise<Uint8Array> {\n // Verify the provided JWK represents a valid OKP public key.\n if (!isOkpPublicJwk(publicKey)) {\n throw new Error(`Ed25519: The provided key is not a valid OKP public key.`);\n }\n\n // Decode the provided public key to bytes.\n const publicKeyBytes = Convert.base64Url(publicKey.x).toUint8Array();\n\n return publicKeyBytes;\n }\n\n /**\n * Generates an RFC8032-compliant EdDSA signature of given data using an Ed25519 private key.\n *\n * @remarks\n * This method signs the provided data with a specified private key using the EdDSA\n * (Edwards-curve Digital Signature Algorithm) as defined in RFC8032. It\n * involves converting the private key from JWK format to a byte array and then employing\n * the Ed25519 algorithm to sign the data. The output is a digital signature in the form\n * of a Uint8Array, uniquely corresponding to both the data and the private key used for\n * signing.\n *\n * @example\n * ```ts\n * const data = new TextEncoder().encode('Messsage'); // Data to be signed\n * const privateKey = { ... }; // A Jwk object representing an Ed25519 private key\n * const signature = await Ed25519.sign({ key: privateKey, data });\n * ```\n *\n * @param params - The parameters for the signing operation.\n * @param params.key - The private key to use for signing, represented in JWK format.\n * @param params.data - The data to sign, represented as a Uint8Array.\n *\n * @returns A Promise that resolves to the signature as a Uint8Array.\n */\n public static async sign({ key, data }:\n SignParams\n ): Promise<Uint8Array> {\n // Convert the private key from JWK format to bytes.\n const privateKeyBytes = await Ed25519.privateKeyToBytes({ privateKey: key });\n\n // Sign the provided data using the EdDSA algorithm.\n const signature = ed25519.sign(data, privateKeyBytes);\n\n return signature;\n }\n\n /**\n * Validates a given public key to confirm its mathematical correctness on the Edwards curve.\n *\n * @remarks\n * This method decodes the Edwards points from the key bytes and asserts their validity on the\n * Curve25519 curve in Twisted Edwards form. If the points are not valid, the method returns\n * false. If the points are valid, the method returns true.\n *\n * Note that this validation strictly pertains to the key's format and numerical validity; it does\n * not assess whether the key corresponds to a known entity or its security status (e.g., whether\n * it has been compromised).\n *\n * @example\n * ```ts\n * const publicKeyBytes = new Uint8Array([...]); // A public key in byte format\n * const isValid = await Ed25519.validatePublicKey({ publicKeyBytes });\n * console.log(isValid); // true if the key is valid on the Edwards curve, false otherwise\n * ```\n *\n * @param params - The parameters for the public key validation.\n * @param params.publicKeyBytes - The public key to validate, represented as a Uint8Array.\n *\n * @returns A Promise that resolves to a boolean indicating whether the key\n * corresponds to a valid point on the Edwards curve.\n */\n public static async validatePublicKey({ publicKeyBytes }: {\n publicKeyBytes: Uint8Array;\n }): Promise<boolean> {\n try {\n // Decode Edwards points from key bytes.\n const point = ed25519.ExtendedPoint.fromHex(publicKeyBytes);\n\n // Check if points are on the Twisted Edwards curve.\n point.assertValidity();\n\n } catch {\n return false;\n }\n\n return true;\n }\n\n /**\n * Verifies an RFC8032-compliant EdDSA signature against given data using an Ed25519 public key.\n *\n * @remarks\n * This method validates a digital signature to ensure its authenticity and integrity.\n * It uses the EdDSA (Edwards-curve Digital Signature Algorithm) as specified in RFC8032.\n * The verification process involves converting the public key from JWK format to a raw\n * byte array and using the Ed25519 algorithm to validate the signature against the provided data.\n *\n * @example\n * ```ts\n * const data = new TextEncoder().encode('Messsage'); // Data that was signed\n * const publicKey = { ... }; // A Jwk object representing an Ed25519 public key\n * const signature = new Uint8Array([...]); // Signature to verify\n * const isValid = await Ed25519.verify({ key: publicKey, signature, data });\n * console.log(isValid); // true if the signature is valid, false otherwise\n * ```\n *\n * @param params - The parameters for the signature verification.\n * @param params.key - The public key in JWK format used for verification.\n * @param params.signature - The signature to verify, represented as a Uint8Array.\n * @param params.data - The data that was signed, represented as a Uint8Array.\n *\n * @returns A Promise that resolves to a boolean indicating whether the signature is valid.\n */\n public static async verify({ key, signature, data }:\n VerifyParams\n ): Promise<boolean> {\n // Convert the public key from JWK format to bytes.\n const publicKeyBytes = await Ed25519.publicKeyToBytes({ publicKey: key });\n\n // Perform the verification of the signature.\n const isValid = ed25519.verify(signature, data, publicKeyBytes);\n\n return isValid;\n }\n}", "import type { AsymmetricKeyGenerator } from '../types/key-generator.js';\nimport type { Jwk } from '../jose/jwk.js';\nimport type { Signer } from '../types/signer.js';\nimport type {\n ComputePublicKeyParams,\n GenerateKeyParams,\n GetPublicKeyParams,\n SignParams,\n VerifyParams,\n} from '../types/params-direct.js';\n\nimport { CryptoAlgorithm } from './crypto-algorithm.js';\nimport { Ed25519 } from '../primitives/ed25519.js';\nimport { isOkpPrivateJwk, isOkpPublicJwk } from '../jose/jwk.js';\n\n/**\n * The `EdDsaGenerateKeyParams` interface defines the algorithm-specific parameters that should be\n * passed into the `generateKey()` method when using the EdDSA algorithm.\n */\nexport interface EdDsaGenerateKeyParams extends GenerateKeyParams {\n /**\n * A string defining the type of key to generate. The value must be one of the following:\n * - `\"Ed25519\"`: EdDSA using the Ed25519 curve.\n */\n algorithm: 'Ed25519';\n}\n\n/**\n * The `EdDsaAlgorithm` class provides a concrete implementation for cryptographic operations using\n * the Edwards-curve Digital Signature Algorithm (EdDSA). This class implements both\n * {@link Signer | `Signer`} and { @link AsymmetricKeyGenerator | `AsymmetricKeyGenerator`}\n * interfaces, providing private key generation, public key derivation, and creation/verification\n * of signatures.\n *\n * This class is typically accessed through implementations that extend the\n * {@link CryptoApi | `CryptoApi`} interface.\n */\nexport class EdDsaAlgorithm extends CryptoAlgorithm\n implements AsymmetricKeyGenerator<EdDsaGenerateKeyParams, Jwk, GetPublicKeyParams>,\n Signer<SignParams, VerifyParams> {\n\n /**\n * Derives the public key in JWK format from a given private key.\n *\n * @remarks\n * This method takes a private key in JWK format and derives its corresponding public key,\n * also in JWK format. The process ensures that the derived public key correctly corresponds to\n * the given private key.\n *\n * @example\n * ```ts\n * const eddsa = new EdDsaAlgorithm();\n * const privateKey = { ... }; // A Jwk object representing a private key\n * const publicKey = await eddsa.computePublicKey({ key: privateKey });\n * ```\n *\n * @param params - The parameters for the public key derivation.\n * @param params.key - The private key in JWK format from which to derive the public key.\n *\n * @returns A Promise that resolves to the derived public key in JWK format.\n */\n public async computePublicKey({ key }:\n ComputePublicKeyParams\n ): Promise<Jwk> {\n if (!isOkpPrivateJwk(key)) {throw new TypeError('Invalid key provided. Must be an octet key pair (OKP) private key.');}\n\n switch (key.crv) {\n\n case 'Ed25519': {\n const publicKey = await Ed25519.computePublicKey({ key });\n publicKey.alg = 'EdDSA';\n return publicKey;\n }\n\n default: {\n throw new Error(`Unsupported curve: ${key.crv}`);\n }\n }\n }\n\n /**\n * Generates a new private key with the specified algorithm in JSON Web Key (JWK) format.\n *\n * @example\n * ```ts\n * const eddsa = new EdDsaAlgorithm();\n * const privateKey = await eddsa.generateKey({ algorithm: 'Ed25519' });\n * ```\n *\n * @param params - The parameters for key generation.\n * @param params.algorithm - The algorithm to use for key generation.\n *\n * @returns A Promise that resolves to the generated private key in JWK format.\n */\n async generateKey({ algorithm }:\n EdDsaGenerateKeyParams\n ): Promise<Jwk> {\n switch (algorithm) {\n\n case 'Ed25519': {\n const privateKey = await Ed25519.generateKey();\n privateKey.alg = 'EdDSA';\n return privateKey;\n }\n }\n }\n\n /**\n * Retrieves the public key properties from a given private key in JWK format.\n *\n * @remarks\n * This method extracts the public key portion from an EdDSA private key in JWK format. It does\n * so by removing the private key property 'd' and making a shallow copy, effectively yielding the\n * public key.\n *\n * Note: This method offers a significant performance advantage, being about 100 times faster\n * than `computePublicKey()`. However, it does not mathematically validate the private key, nor\n * does it derive the public key from the private key. It simply extracts existing public key\n * properties from the private key object. This makes it suitable for scenarios where speed is\n * critical and the private key's integrity is already assured.\n *\n * @example\n * ```ts\n * const eddsa = new EdDsaAlgorithm();\n * const privateKey = { ... }; // A Jwk object representing a private key\n * const publicKey = await eddsa.getPublicKey({ key: privateKey });\n * ```\n *\n * @param params - The parameters for retrieving the public key properties.\n * @param params.key - The private key in JWK format.\n *\n * @returns A Promise that resolves to the public key in JWK format.\n */\n public async getPublicKey({ key }:\n GetPublicKeyParams\n ): Promise<Jwk> {\n if (!isOkpPrivateJwk(key)) {throw new TypeError('Invalid key provided. Must be an octet key pair (OKP) private key.');}\n\n switch (key.crv) {\n\n case 'Ed25519': {\n const publicKey = await Ed25519.getPublicKey({ key });\n publicKey.alg = 'EdDSA';\n return publicKey;\n }\n\n default: {\n throw new Error(`Unsupported curve: ${key.crv}`);\n }\n }\n }\n\n /**\n * Generates an EdDSA signature of given data using a private key.\n *\n * @remarks\n * This method uses the signature algorithm determined by the given `algorithm` to sign the\n * provided data.\n *\n * The signature can later be verified by parties with access to the corresponding\n * public key, ensuring that the data has not been tampered with and was indeed signed by the\n * holder of the private key.\n *\n * @example\n * ```ts\n * const eddsa = new EdDsaAlgorithm();\n * const data = new TextEncoder().encode('Message');\n * const privateKey = { ... }; // A Jwk object representing a private key\n * const signature = await eddsa.sign({\n * key: privateKey,\n * data\n * });\n * ```\n *\n * @param params - The parameters for the signing operation.\n * @param params.key - The private key to use for signing, represented in JWK format.\n * @param params.data - The data to sign.\n *\n * @returns A Promise resolving to the digital signature as a `Uint8Array`.\n */\n public async sign({ key, data }:\n SignParams\n ): Promise<Uint8Array> {\n if (!isOkpPrivateJwk(key)) {throw new TypeError('Invalid key provided. Must be an octet key pair (OKP) private key.');}\n\n switch (key.crv) {\n\n case 'Ed25519': {\n return await Ed25519.sign({ key, data });\n }\n\n default: {\n throw new Error(`Unsupported curve: ${key.crv}`);\n }\n }\n }\n\n /**\n * Verifies an EdDSA signature associated with the provided data using the provided key.\n *\n * @remarks\n * This method uses the signature algorithm determined by the `crv` property of the provided key\n * to check the validity of a digital signature against the original data. It confirms whether the\n * signature was created by the holder of the corresponding private key and that the data has not\n * been tampered with.\n *s\n * @example\n * ```ts\n * const eddsa = new EdDsaAlgorithm();\n * const publicKey = { ... }; // Public key in JWK format corresponding to the private key that signed the data\n * const signature = new Uint8Array([...]); // Signature to verify\n * const data = new TextEncoder().encode('Message');\n * const isValid = await eddsa.verify({\n * key: publicKey,\n * signature,\n * data\n * });\n * ```\n *\n * @param params - The parameters for the verification operation.\n * @param params.key - The key to use for verification.\n * @param params.signature - The signature to verify.\n * @param params.data - The data to verify.\n *\n * @returns A Promise resolving to a boolean indicating whether the signature is valid.\n */\n public async verify({ key, signature, data }:\n VerifyParams\n ): Promise<boolean> {\n if (!isOkpPublicJwk(key)) {throw new TypeError('Invalid key provided. Must be an octet key pair (OKP) public key.');}\n\n switch (key.crv) {\n\n case 'Ed25519': {\n return await Ed25519.verify({ key, signature, data });\n }\n\n default: {\n throw new Error(`Unsupported curve: ${key.crv}`);\n }\n }\n }\n}", "import type { DigestParams } from '../types/params-direct.js';\nimport type { Hasher } from '../types/hasher.js';\n\nimport { CryptoAlgorithm } from './crypto-algorithm.js';\nimport { Sha256 } from '../primitives/sha256.js';\n\n/**\n * The `Sha2DigestParams` interface defines the algorithm-specific parameters that should be\n * passed into the `digest()` method when using the SHA-2 algorithm.\n */\nexport interface Sha2DigestParams extends DigestParams {\n /**\n * A string defining the name of hash function to use. The value must be one of the following:\n * - `\"SHA-256\"`: Generates a 256-bit digest.\n */\n algorithm: 'SHA-256';\n}\n\n/**\n * The `Sha2Algorithm` class is an implementation of the {@link Hasher | `Hasher`} interface for the\n * SHA-2 family of cryptographic hash functions. The `digest` method takes the algorithm identifier\n * of the hash function and arbitrary data as input and returns the hash digest of the data.\n *\n * This class is typically accessed through implementations that extend the\n * {@link CryptoApi | `CryptoApi`} interface.\n */\nexport class Sha2Algorithm extends CryptoAlgorithm\n implements Hasher<Sha2DigestParams> {\n\n /**\n * Generates a hash digest of the provided data.\n *\n * @remarks\n * A digest is the output of the hash function. It's a fixed-size string of bytes\n * that uniquely represents the data input into the hash function. The digest is often used for\n * data integrity checks, as any alteration in the input data results in a significantly\n * different digest.\n *\n * It takes the algorithm identifier of the hash function and data to digest as input and returns\n * the digest of the data.\n *\n * @example\n * ```ts\n * const sha2 = new Sha2Algorithm();\n * const data = new TextEncoder().encode('Messsage');\n * const digest = await sha2.digest({ data });\n * ```\n *\n * @param params - The parameters for the digest operation.\n * @param params.algorithm - The name of hash function to use.\n * @param params.data - The data to digest.\n *\n * @returns A Promise which will be fulfilled with the hash digest.\n */\n public async digest({ algorithm, data }: Sha2DigestParams): Promise<Uint8Array> {\n switch (algorithm) {\n\n case 'SHA-256': {\n const hash = await Sha256.digest({ data });\n return hash;\n }\n }\n\n }\n}", "import type { KeyValueStore } from '@enbox/common';\nimport { MemoryStore } from '@enbox/common';\n\nimport type { CryptoAlgorithm } from './algorithms/crypto-algorithm.js';\nimport type { CryptoApi } from './types/crypto-api.js';\nimport type { Hasher } from './types/hasher.js';\nimport type { Jwk } from './jose/jwk.js';\nimport type { KeyIdentifier } from './types/identifier.js';\nimport type { KeyImporterExporter } from './types/key-io.js';\nimport type { Signer } from './types/signer.js';\nimport type { AsymmetricKeyGenerator, KeyGenerator } from './types/key-generator.js';\nimport type { GetPublicKeyParams, SignParams, VerifyParams } from './types/params-direct.js';\nimport type {\n KmsDigestParams,\n KmsExportKeyParams,\n KmsGenerateKeyParams,\n KmsGetKeyUriParams,\n KmsGetPublicKeyParams,\n KmsImportKeyParams,\n KmsSignParams,\n KmsVerifyParams,\n} from './types/params-kms.js';\n\nimport { EcdsaAlgorithm } from './algorithms/ecdsa.js';\nimport { EdDsaAlgorithm } from './algorithms/eddsa.js';\nimport { Sha2Algorithm } from './algorithms/sha-2.js';\nimport { computeJwkThumbprint, isPrivateJwk, KEY_URI_PREFIX_JWK } from './jose/jwk.js';\n\n/**\n * `supportedAlgorithms` is an object mapping algorithm names to their respective implementations\n * Each entry in this map specifies the algorithm name and its associated properties, including the\n * implementation class and any relevant names or identifiers for the algorithm. This structure\n * allows for easy retrieval and instantiation of algorithm implementations based on the algorithm\n * name or key specification. It facilitates the support of multiple algorithms within the\n * `LocalKeyManager` class.\n */\nconst supportedAlgorithms = {\n 'Ed25519': {\n implementation : EdDsaAlgorithm,\n names : ['Ed25519'],\n },\n 'secp256k1': {\n implementation : EcdsaAlgorithm,\n names : ['ES256K', 'secp256k1'],\n },\n 'secp256r1': {\n implementation : EcdsaAlgorithm,\n names : ['ES256', 'secp256r1'],\n },\n 'SHA-256': {\n implementation : Sha2Algorithm,\n names : ['SHA-256']\n }\n} satisfies {\n [key: string]: {\n implementation : typeof CryptoAlgorithm;\n names : string[];\n }\n};\n\n/* Helper type for `supportedAlgorithms`. */\ntype SupportedAlgorithm = keyof typeof supportedAlgorithms;\n\n/* Helper type for `supportedAlgorithms` implementations. */\ntype AlgorithmConstructor = typeof supportedAlgorithms[SupportedAlgorithm]['implementation'];\n\n/**\n * The `LocalKeyManagerParams` interface specifies the parameters for initializing an instance of\n * `LocalKeyManager`. It allows the optional inclusion of a `KeyValueStore` instance for key\n * management. If not provided, a default `MemoryStore` instance will be used for storing keys in\n * memory. Note that the `MemoryStore` is not persistent and will be cleared when the application\n * exits.\n */\nexport type LocalKeyManagerParams = {\n /**\n * An optional property to specify a custom `KeyValueStore` instance for key management. If not\n * provided, {@link LocalKeyManager | `LocalKeyManager`} uses a default `MemoryStore` instance.\n * This store is responsible for managing cryptographic keys, allowing them to be retrieved,\n * stored, and managed during cryptographic operations.\n */\n keyStore?: KeyValueStore<KeyIdentifier, Jwk>;\n};\n\n/**\n * The `LocalKeyManagerDigestParams` interface defines the algorithm-specific parameters that should\n * be passed into the {@link LocalKeyManager.digest | `LocalKeyManager.digest()`} method.\n */\nexport interface LocalKeyManagerDigestParams extends KmsDigestParams {\n /**\n * A string defining the name of hash function to use. The value must be one of the following:\n * - `\"SHA-256\"`: Generates a 256-bit digest.\n */\n algorithm: 'SHA-256';\n}\n\n/**\n * The `LocalKeyManagerGenerateKeyParams` interface defines the algorithm-specific parameters that\n * should be passed into the {@link LocalKeyManager.generateKey | `LocalKeyManager.generateKey()`}\n * method when generating a key in the local KMS.\n */\nexport interface LocalKeyManagerGenerateKeyParams extends KmsGenerateKeyParams {\n /**\n * A string defining the type of key to generate. The value must be one of the following:\n * - `\"Ed25519\"`\n * - `\"secp256k1\"`\n */\n algorithm: 'Ed25519' | 'secp256k1' | 'secp256r1';\n}\n\nexport class LocalKeyManager implements\n CryptoApi,\n KeyImporterExporter<KmsImportKeyParams, KeyIdentifier, KmsExportKeyParams> {\n\n /**\n * A private map that stores instances of cryptographic algorithm implementations. Each key in\n * this map is an `AlgorithmConstructor`, and its corresponding value is an instance of a class\n * that implements a specific cryptographic algorithm. This map is used to cache and reuse\n * instances for performance optimization, ensuring that each algorithm is instantiated only once.\n */\n private _algorithmInstances: Map<AlgorithmConstructor, InstanceType<typeof CryptoAlgorithm>> = new Map();\n\n /**\n * The `_keyStore` private variable in `LocalKeyManager` is a `KeyValueStore` instance used for\n * storing and managing cryptographic keys. It allows the `LocalKeyManager` class to save,\n * retrieve, and handle keys efficiently within the local Key Management System (KMS) context.\n * This variable can be configured to use different storage backends, like in-memory storage or\n * persistent storage, providing flexibility in key management according to the application's\n * requirements.\n */\n private _keyStore: KeyValueStore<KeyIdentifier, Jwk>;\n\n constructor(params?: LocalKeyManagerParams) {\n this._keyStore = params?.keyStore ?? new MemoryStore<KeyIdentifier, Jwk>();\n }\n\n /**\n * Generates a hash digest of the provided data.\n *\n * @remarks\n * A digest is the output of the hash function. It's a fixed-size string of bytes\n * that uniquely represents the data input into the hash function. The digest is often used for\n * data integrity checks, as any alteration in the input data results in a significantly\n * different digest.\n *\n * It takes the algorithm identifier of the hash function and data to digest as input and returns\n * the digest of the data.\n *\n * @example\n * ```ts\n * const keyManager = new LocalKeyManager();\n * const data = new Uint8Array([...]);\n * const digest = await keyManager.digest({ algorithm: 'SHA-256', data });\n * ```\n *\n * @param params - The parameters for the digest operation.\n * @param params.algorithm - The name of hash function to use.\n * @param params.data - The data to digest.\n *\n * @returns A Promise which will be fulfilled with the hash digest.\n */\n public async digest({ algorithm, data }:\n LocalKeyManagerDigestParams\n ): Promise<Uint8Array> {\n // Get the hash function implementation based on the specified `algorithm` parameter.\n const hasher = this.getAlgorithm({ algorithm }) as Hasher<KmsDigestParams>;\n\n // Compute the hash.\n const hash = await hasher.digest({ algorithm, data });\n\n return hash;\n }\n\n /**\n * Exports a private key identified by the provided key URI from the local KMS.\n *\n * @remarks\n * This method retrieves the key from the key store and returns it. It is primarily used\n * for extracting keys for backup or transfer purposes.\n *\n * @example\n * ```ts\n * const keyManager = new LocalKeyManager();\n * const keyUri = await keyManager.generateKey({ algorithm: 'Ed25519' });\n * const privateKey = await keyManager.exportKey({ keyUri });\n * ```\n *\n * @param params - Parameters for exporting the key.\n * @param params.keyUri - The key URI identifying the key to export.\n *\n * @returns A Promise resolving to the JWK representation of the exported key.\n */\n public async exportKey({ keyUri }:\n KmsExportKeyParams\n ): Promise<Jwk> {\n // Get the private key from the key store.\n const privateKey = await this.getPrivateKey({ keyUri });\n\n return privateKey;\n }\n\n /**\n * Generates a new cryptographic key in the local KMS with the specified algorithm and returns a\n * unique key URI which can be used to reference the key in subsequent operations.\n *\n * @example\n * ```ts\n * const keyManager = new LocalKeyManager();\n * const keyUri = await keyManager.generateKey({ algorithm: 'Ed25519' });\n * console.log(keyUri); // Outputs the key URI\n * ```\n *\n * @param params - The parameters for key generation.\n * @param params.algorithm - The algorithm to use for key generation, defined in `SupportedAlgorithm`.\n *\n * @returns A Promise that resolves to the key URI, a unique identifier for the generated key.\n */\n public async generateKey({ algorithm }:\n LocalKeyManagerGenerateKeyParams\n ): Promise<KeyIdentifier> {\n // Get the key generator implementation based on the specified `algorithm` parameter.\n const keyGenerator = this.getAlgorithm({ algorithm }) as KeyGenerator<LocalKeyManagerGenerateKeyParams, Jwk>;\n\n // Generate the key.\n const key = await keyGenerator.generateKey({ algorithm });\n\n if (key?.kid === undefined) {\n throw new Error('Generated key is missing a required property: kid');\n }\n\n // Construct the key URI.\n const keyUri = `${KEY_URI_PREFIX_JWK}${key.kid}`;\n\n // Store the key in the key store.\n await this._keyStore.set(keyUri, key);\n\n return keyUri;\n }\n\n /**\n * Computes the Key URI for a given public JWK (JSON Web Key).\n *\n * @remarks\n * This method generates a {@link https://datatracker.ietf.org/doc/html/rfc3986 | URI}\n * (Uniform Resource Identifier) for the given JWK, which uniquely identifies the key across all\n * `CryptoApi` implementations. The key URI is constructed by appending the\n * {@link https://datatracker.ietf.org/doc/html/rfc7638 | JWK thumbprint} to the prefix\n * `urn:jwk:`. The JWK thumbprint is deterministically computed from the JWK and is consistent\n * regardless of property order or optional property inclusion in the JWK. This ensures that the\n * same key material represented as a JWK will always yield the same thumbprint, and therefore,\n * the same key URI.\n *\n * @example\n * ```ts\n * const keyManager = new LocalKeyManager();\n * const keyUri = await keyManager.generateKey({ algorithm: 'Ed25519' });\n * const publicKey = await keyManager.getPublicKey({ keyUri });\n * const keyUriFromPublicKey = await keyManager.getKeyUri({ key: publicKey });\n * console.log(keyUri === keyUriFromPublicKey); // Outputs `true`\n * ```\n *\n * @param params - The parameters for getting the key URI.\n * @param params.key - The JWK for which to compute the key URI.\n *\n * @returns A Promise that resolves to the key URI as a string.\n */\n public async getKeyUri({ key }:\n KmsGetKeyUriParams\n ): Promise<KeyIdentifier> {\n // Compute the JWK thumbprint.\n const jwkThumbprint = await computeJwkThumbprint({ jwk: key });\n\n // Construct the key URI by appending the JWK thumbprint to the key URI prefix.\n const keyUri = `${KEY_URI_PREFIX_JWK}${jwkThumbprint}`;\n\n return keyUri;\n }\n\n /**\n * Retrieves the public key associated with a previously generated private key, identified by\n * the provided key URI.\n *\n * @example\n * ```ts\n * const keyManager = new LocalKeyManager();\n * const keyUri = await keyManager.generateKey({ algorithm: 'Ed25519' });\n * const publicKey = await keyManager.getPublicKey({ keyUri });\n * ```\n *\n * @param params - The parameters for retrieving the public key.\n * @param params.keyUri - The key URI of the private key to retrieve the public key for.\n *\n * @returns A Promise that resolves to the public key in JWK format.\n */\n public async getPublicKey({ keyUri }:\n KmsGetPublicKeyParams\n ): Promise<Jwk> {\n // Get the private key from the key store.\n const privateKey = await this.getPrivateKey({ keyUri });\n\n // Determine the algorithm name based on the JWK's `alg` and `crv` properties.\n const algorithm = this.getAlgorithmName({ key: privateKey });\n\n // Get the key generator based on the algorithm name.\n const keyGenerator = this.getAlgorithm({ algorithm }) as AsymmetricKeyGenerator<LocalKeyManagerGenerateKeyParams, Jwk, GetPublicKeyParams>;\n\n // Get the public key properties from the private JWK.\n const publicKey = await keyGenerator.getPublicKey({ key: privateKey });\n\n return publicKey;\n }\n\n /**\n * Imports a private key into the local KMS.\n *\n * @remarks\n * This method stores the provided JWK in the key store, making it available for subsequent\n * cryptographic operations. It is particularly useful for initializing the KMS with pre-existing\n * keys or for restoring keys from backups.\n *\n * Note that, if defined, the `kid` (key ID) property of the JWK is used as the key URI for the\n * imported key. If the `kid` property is not provided, the key URI is computed from the JWK\n * thumbprint of the key.\n *\n * @example\n * ```ts\n * const keyManager = new LocalKeyManager();\n * const privateKey = { ... } // A private key in JWK format\n * const keyUri = await keyManager.importKey({ key: privateKey });\n * ```\n *\n * @param params - Parameters for importing the key.\n * @param params.key - The private key to import to in JWK format.\n *\n * @returns A Promise resolving to the key URI, uniquely identifying the imported key.\n */\n public async importKey({ key }:\n KmsImportKeyParams\n ): Promise<KeyIdentifier> {\n if (!isPrivateJwk(key)) {throw new TypeError('Invalid key provided. Must be a private key in JWK format.');}\n\n // Make a deep copy of the key to avoid mutating the original.\n const privateKey = structuredClone(key);\n\n // If the key ID is undefined, set it to the JWK thumbprint.\n privateKey.kid ??= await computeJwkThumbprint({ jwk: privateKey });\n\n // Compute the key URI for the key.\n const keyUri = await this.getKeyUri({ key: privateKey });\n\n // Store the key in the key store.\n await this._keyStore.set(keyUri, privateKey);\n\n return keyUri;\n }\n\n /**\n * Signs the provided data using the private key identified by the provided key URI.\n *\n * @remarks\n * This method uses the signature algorithm determined by the `alg` and/or `crv` properties of the\n * private key identified by the provided key URI to sign the provided data. The signature can\n * later be verified by parties with access to the corresponding public key, ensuring that the\n * data has not been tampered with and was indeed signed by the holder of the private key.\n *\n * @example\n * ```ts\n * const keyManager = new LocalKeyManager();\n * const keyUri = await keyManager.generateKey({ algorithm: 'Ed25519' });\n * const data = new TextEncoder().encode('Message to sign');\n * const signature = await keyManager.sign({ keyUri, data });\n * ```\n *\n * @param params - The parameters for the signing operation.\n * @param params.keyUri - The key URI of the private key to use for signing.\n * @param params.data - The data to sign.\n *\n * @returns A Promise resolving to the digital signature as a `Uint8Array`.\n */\n public async sign({ keyUri, data }:\n KmsSignParams\n ): Promise<Uint8Array> {\n // Get the private key from the key store.\n const privateKey = await this.getPrivateKey({ keyUri });\n\n // Determine the algorithm name based on the JWK's `alg` and `crv` properties.\n const algorithm = this.getAlgorithmName({ key: privateKey });\n\n // Get the signature algorithm based on the algorithm name.\n const signer = this.getAlgorithm({ algorithm }) as Signer<SignParams, VerifyParams>;\n\n // Sign the data.\n const signature = signer.sign({ data, key: privateKey });\n\n return signature;\n }\n\n /**\n * Verifies a digital signature associated the provided data using the provided key.\n *\n * @remarks\n * This method uses the signature algorithm determined by the `alg` and/or `crv` properties of the\n * provided key to check the validity of a digital signature against the original data. It\n * confirms whether the signature was created by the holder of the corresponding private key and\n * that the data has not been tampered with.\n *\n * @example\n * ```ts\n * const keyManager = new LocalKeyManager();\n * const keyUri = await keyManager.generateKey({ algorithm: 'Ed25519' });\n * const data = new TextEncoder().encode('Message to sign');\n * const signature = await keyManager.sign({ keyUri, data });\n * const isSignatureValid = await keyManager.verify({ keyUri, data, signature });\n * ```\n *\n * @param params - The parameters for the verification operation.\n * @param params.key - The key to use for verification.\n * @param params.signature - The signature to verify.\n * @param params.data - The data to verify.\n *\n * @returns A Promise resolving to a boolean indicating whether the signature is valid.\n */\n public async verify({ key, signature, data }:\n KmsVerifyParams\n ): Promise<boolean> {\n // Determine the algorithm name based on the JWK's `alg` and `crv` properties.\n const algorithm = this.getAlgorithmName({ key });\n\n // Get the signature algorithm based on the algorithm name.\n const signer = this.getAlgorithm({ algorithm }) as Signer<SignParams, VerifyParams>;\n\n // Verify the signature.\n const isSignatureValid = signer.verify({ key, signature, data });\n\n return isSignatureValid;\n }\n\n /**\n * Retrieves an algorithm implementation instance based on the provided algorithm name.\n *\n * @remarks\n * This method checks if the requested algorithm is supported and returns a cached instance\n * if available. If an instance does not exist, it creates and caches a new one. This approach\n * optimizes performance by reusing algorithm instances across cryptographic operations.\n *\n * @example\n * ```ts\n * const signer = this.getAlgorithm({ algorithm: 'Ed25519' });\n * ```\n *\n * @param params - The parameters for retrieving the algorithm implementation.\n * @param params.algorithm - The name of the algorithm to retrieve.\n *\n * @returns An instance of the requested algorithm implementation.\n *\n * @throws Error if the requested algorithm is not supported.\n */\n private getAlgorithm({ algorithm }: {\n algorithm: SupportedAlgorithm;\n }): InstanceType<typeof CryptoAlgorithm> {\n // Check if algorithm is supported.\n const AlgorithmImplementation = supportedAlgorithms[algorithm]?.['implementation'];\n if (!AlgorithmImplementation) {\n throw new Error(`Algorithm not supported: ${algorithm}`);\n }\n\n // Check if instance already exists for the `AlgorithmImplementation`.\n if (!this._algorithmInstances.has(AlgorithmImplementation)) {\n // If not, create a new instance and store it in the cache\n this._algorithmInstances.set(AlgorithmImplementation, new AlgorithmImplementation());\n }\n\n // Return the cached instance\n return this._algorithmInstances.get(AlgorithmImplementation)!;\n }\n\n /**\n * Determines the name of the algorithm based on the key's properties.\n *\n * @remarks\n * This method facilitates the identification of the correct algorithm for cryptographic\n * operations based on the `alg` or `crv` properties of a {@link Jwk | JWK}.\n *\n * @example\n * ```ts\n * const publicKey = { ... }; // Public key in JWK format\n * const algorithm = this.getAlgorithmName({ key: publicKey });\n * ```\n *\n * @param params - The parameters for determining the algorithm name.\n * @param params.key - A JWK containing the `alg` or `crv` properties.\n *\n * @returns The name of the algorithm associated with the key.\n *\n * @throws Error if the algorithm cannot be determined from the provided input.\n */\n private getAlgorithmName({ key }: {\n key: { alg?: string, crv?: string };\n }): SupportedAlgorithm {\n const algProperty = key.alg;\n const crvProperty = key.crv;\n\n for (const algName in supportedAlgorithms) {\n const algorithmInfo = supportedAlgorithms[algName as SupportedAlgorithm];\n if (algProperty && algorithmInfo.names.includes(algProperty)) {\n return algName as SupportedAlgorithm;\n } else if (crvProperty && algorithmInfo.names.includes(crvProperty)) {\n return algName as SupportedAlgorithm;\n }\n }\n\n throw new Error(`Unable to determine algorithm based on provided input: alg=${algProperty}, crv=${crvProperty}`);\n }\n\n /**\n * Retrieves a private key from the key store based on the provided key URI.\n *\n * @example\n * ```ts\n * const privateKey = this.getPrivateKey({ keyUri: 'urn:jwk:...' });\n * ```\n *\n * @param params - Parameters for retrieving the private key.\n * @param params.keyUri - The key URI identifying the private key to retrieve.\n *\n * @returns A Promise resolving to the JWK representation of the private key.\n *\n * @throws Error if the key is not found in the key store.\n */\n private async getPrivateKey({ keyUri }: {\n keyUri: KeyIdentifier;\n }): Promise<Jwk> {\n // Get the private key from the key store.\n const privateKey = await this._keyStore.get(keyUri);\n\n if (!privateKey) {\n throw new Error(`Key not found: ${keyUri}`);\n }\n\n return privateKey;\n }\n}", "import type { Jwk } from './jose/jwk.js';\n\nimport { crypto } from '@noble/hashes/crypto';\nimport { randomBytes as nobleRandomBytes } from '@noble/hashes/utils';\n\n/**\n * A collection of cryptographic utility methods.\n */\nexport class CryptoUtils {\n\n /**\n * Determines the JOSE algorithm identifier of the digital signature algorithm based on the `alg` or\n * `crv` property of a {@link Jwk | JWK}.\n *\n * If the `alg` property is present, its value takes precedence and is returned. Otherwise, the\n * `crv` property is used to determine the algorithm.\n *\n * @memberof CryptoUtils\n * @see {@link https://www.iana.org/assignments/jose/jose.xhtml#web-signature-encryption-algorithms | JOSE Algorithms}\n * @see {@link https://datatracker.ietf.org/doc/draft-ietf-jose-fully-specified-algorithms/ | Fully-Specified Algorithms for JOSE and COSE}\n *\n * @example\n * ```ts\n * const publicKey: Jwk = {\n * \"kty\": \"OKP\",\n * \"crv\": \"Ed25519\",\n * \"x\": \"FEJG7OakZi500EydXxuE8uMc8uaAzEJkmQeG8khXANw\"\n * }\n * const algorithm = getJoseSignatureAlgorithmFromPublicKey(publicKey);\n * console.log(algorithm); // Output: \"EdDSA\"\n * ```\n * @param publicKey - A JWK containing the `alg` and/or `crv` properties.\n * @returns The name of the algorithm associated with the key.\n * @throws Error if the algorithm cannot be determined from the provided input.\n */\n static getJoseSignatureAlgorithmFromPublicKey(publicKey: Jwk): string {\n const curveToJoseAlgorithm: Record<string, string> = {\n 'Ed25519' : 'EdDSA',\n 'P-256' : 'ES256',\n 'P-384' : 'ES384',\n 'P-521' : 'ES512',\n 'secp256k1' : 'ES256K',\n };\n\n // If the key contains an `alg` property that matches a JOSE registered algorithm identifier,\n // return its value.\n if (publicKey.alg && Object.values(curveToJoseAlgorithm).includes(publicKey.alg)) {\n return publicKey.alg;\n }\n\n // If the key contains a `crv` property, return the corresponding algorithm.\n if (publicKey.crv && Object.keys(curveToJoseAlgorithm).includes(publicKey.crv)) {\n return curveToJoseAlgorithm[publicKey.crv];\n }\n\n throw new Error(\n `Unable to determine algorithm based on provided input: alg=${publicKey.alg}, crv=${publicKey.crv}. ` +\n `Supported 'alg' values: ${Object.values(curveToJoseAlgorithm).join(', ')}. ` +\n `Supported 'crv' values: ${Object.keys(curveToJoseAlgorithm).join(', ')}.`\n );\n }\n\n /**\n * Generates secure pseudorandom values of the specified length using\n * `crypto.getRandomValues`, which defers to the operating system.\n *\n * @memberof CryptoUtils\n * @remarks\n * This function is a wrapper around `randomBytes` from the '@noble/hashes'\n * package. It's designed to be cryptographically strong, suitable for\n * generating initialization vectors, nonces, and other random values.\n *\n * @see {@link https://www.npmjs.com/package/@noble/hashes | @noble/hashes on NPM} for more\n * information about the underlying implementation.\n *\n * @example\n * ```ts\n * const bytes = randomBytes(32); // Generates 32 random bytes\n * ```\n *\n * @param bytesLength - The number of bytes to generate.\n * @returns A Uint8Array containing the generated random bytes.\n */\n static randomBytes(bytesLength: number): Uint8Array {\n return nobleRandomBytes(bytesLength);\n }\n\n /**\n * Generates a UUID (Universally Unique Identifier) using a\n * cryptographically strong random number generator following\n * the version 4 format, as specified in RFC 4122.\n *\n * A version 4 UUID is a randomly generated UUID. The 13th character\n * is set to '4' to denote version 4, and the 17th character is one\n * of '8', '9', 'A', or 'B' to comply with the variant 1 format of\n * UUIDs (the high bits are set to '10').\n *\n * The UUID is a 36 character string, including hyphens, and looks like this:\n * xxxxxxxx-xxxx-4xxx-axxx-xxxxxxxxxxxx\n *\n * Note that while UUIDs are not guaranteed to be unique, they are\n * practically unique\" given the large number of possible UUIDs and\n * the randomness of generation.\n * @memberof CryptoUtils\n * @example\n * ```ts\n * const uuid = randomUuid();\n * console.log(uuid); // Outputs a version 4 UUID, e.g., '123e4567-e89b-12d3-a456-426655440000'\n * ```\n *\n * @returns A string containing a randomly generated, 36 character long v4 UUID.\n */\n static randomUuid(): string {\n const uuid = crypto.randomUUID();\n\n return uuid;\n }\n\n\n /**\n * Generates a secure random PIN (Personal Identification Number) of a\n * specified length.\n *\n * This function ensures that the generated PIN is cryptographically secure and\n * uniformly distributed by using rejection sampling. It repeatedly generates\n * random numbers until it gets one in the desired range [0, max]. This avoids\n * bias introduced by simply taking the modulus or truncating the number.\n *\n * Note: The function can generate PINs of 3 to 10 digits in length.\n * Any request for a PIN outside this range will result in an error.\n *\n * Example usage:\n *\n * ```ts\n * const pin = randomPin({ length: 4 });\n * console.log(pin); // Outputs a 4-digit PIN, e.g., \"0231\"\n * ```\n * @memberof CryptoUtils\n * @param options - The options object containing the desired length of the generated PIN.\n * @param options.length - The desired length of the generated PIN. The value should be\n * an integer between 3 and 8 inclusive.\n *\n * @returns A string representing the generated PIN. The PIN will be zero-padded\n * to match the specified length, if necessary.\n *\n * @throws Will throw an error if the requested PIN length is less than 3 or greater than 8.\n */\n static randomPin({ length }: { length: number }): string {\n if (3 > length || length > 10) {\n throw new Error('randomPin() can securely generate a PIN between 3 to 10 digits.');\n }\n\n const max = Math.pow(10, length) - 1;\n\n let pin;\n\n if (length <= 6) {\n const rejectionRange = Math.pow(10, length);\n do {\n // Adjust the byte generation based on length.\n const randomBuffer = CryptoUtils.randomBytes(Math.ceil(length / 2) ); // 2 digits per byte.\n const view = new DataView(randomBuffer.buffer);\n // Convert the buffer to integer and take modulus based on length.\n pin = view.getUint16(0, false) % rejectionRange;\n } while (pin > max);\n } else {\n const rejectionRange = Math.pow(10, 10); // For max 10 digit number.\n do {\n // Generates 4 random bytes.\n const randomBuffer = CryptoUtils.randomBytes(4);\n // Create a DataView to read from the randomBuffer.\n const view = new DataView(randomBuffer.buffer);\n // Transform bytes to number (big endian).\n pin = view.getUint32(0, false) % rejectionRange;\n } while (pin > max); // Reject if the number is outside the desired range.\n }\n\n // Pad the PIN with leading zeros to the desired length.\n return pin.toString().padStart(length, '0');\n }\n}\n", "// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// See utils.ts for details.\ndeclare const globalThis: Record<string, any> | undefined;\nconst cr = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (cr && typeof cr.getRandomValues === 'function')\n return cr.getRandomValues(new Uint8Array(bytesLength));\n throw new Error('crypto.getRandomValues must be defined');\n}\n\nexport function getWebcryptoSubtle() {\n if (cr && typeof cr.subtle === 'object' && cr.subtle != null) return cr.subtle;\n throw new Error('crypto.subtle must be defined');\n}\n", "import { Convert } from '@enbox/common';\nimport { getWebcryptoSubtle } from '@noble/ciphers/crypto';\n\nimport type { Jwk } from '../jose/jwk.js';\n\nimport { computeJwkThumbprint, isOctPrivateJwk } from '../jose/jwk.js';\n\n/**\n * Constant defining the AES block size in bits.\n *\n * @remarks\n * In AES Counter (CTR) mode, the counter length must match the block size of the AES algorithm,\n * which is 128 bits. NIST publication 800-38A, which provides guidelines for block cipher modes of\n * operation, specifies this requirement. Maintaining a counter length of 128 bits is essential for\n * the correct operation and security of AES-CTR.\n *\n * This implementation does not support counter lengths that are different from the value defined by\n * this constant.\n *\n * @see {@link https://doi.org/10.6028/NIST.SP.800-38A | NIST SP 800-38A}\n */\nconst AES_BLOCK_SIZE = 128;\n\n/**\n * Constant defining the AES key length values in bits.\n *\n * @remarks\n * NIST publication FIPS 197 states:\n * > The AES algorithm is capable of using cryptographic keys of 128, 192, and 256 bits to encrypt\n * > and decrypt data in blocks of 128 bits.\n *\n * This implementation does not support key lengths that are different from the three values\n * defined by this constant.\n *\n * @see {@link https://doi.org/10.6028/NIST.FIPS.197-upd1 | NIST FIPS 197}\n */\nconst AES_KEY_LENGTHS = [128, 192, 256] as const;\n\n/**\n * Constant defining the maximum length of the counter in bits.\n *\n * @remarks\n * The rightmost bits of the counter block are used as the actual counter value, while the leftmost\n * bits are used as the nonce. The maximum length of the counter is 128 bits, which is the same as\n * the AES block size.\n */\nconst COUNTER_MAX_LENGTH = AES_BLOCK_SIZE;\n\n/**\n * The `AesCtr` class provides a comprehensive set of utilities for cryptographic operations\n * using the Advanced Encryption Standard (AES) in Counter (CTR) mode. This class includes\n * methods for key generation, encryption, decryption, and conversions between raw byte arrays\n * and JSON Web Key (JWK) formats. It is designed to support AES-CTR, a symmetric key algorithm\n * that is widely used in various cryptographic applications for its efficiency and security.\n *\n * AES-CTR mode operates as a stream cipher using a block cipher (AES) and is well-suited for\n * scenarios where parallel processing is beneficial or where the same key is required to\n * encrypt multiple data blocks. The class adheres to standard cryptographic practices, ensuring\n * compatibility and security in its implementations.\n *\n * Key Features:\n * - Key Generation: Generate AES symmetric keys in JWK format.\n * - Key Conversion: Transform keys between raw byte arrays and JWK formats.\n * - Encryption: Encrypt data using AES-CTR with the provided symmetric key.\n * - Decryption: Decrypt data encrypted with AES-CTR using the corresponding symmetric key.\n *\n * The methods in this class are asynchronous, returning Promises to accommodate various\n * JavaScript environments.\n *\n * @example\n * ```ts\n * // Key Generation\n * const length = 256; // Length of the key in bits (e.g., 128, 192, 256)\n * const privateKey = await AesCtr.generateKey({ length });\n *\n * // Encryption\n * const data = new TextEncoder().encode('Messsage');\n * const counter = new Uint8Array(16); // 16-byte (128-bit) counter block\n * const encryptedData = await AesCtr.encrypt({\n * data,\n * counter,\n * key: privateKey,\n * length: 64 // Length of the counter in bits\n * });\n *\n * // Decryption\n * const decryptedData = await AesCtr.decrypt({\n * data: encryptedData,\n * counter,\n * key: privateKey,\n * length: 64 // Length of the counter in bits\n * });\n *\n * // Key Conversion\n * const privateKeyBytes = await AesCtr.privateKeyToBytes({ privateKey });\n * ```\n */\nexport class AesCtr {\n /**\n * Converts a raw private key in bytes to its corresponding JSON Web Key (JWK) format.\n *\n * @remarks\n * This method takes a symmetric key represented as a byte array (Uint8Array) and\n * converts it into a JWK object for use with AES (Advanced Encryption Standard)\n * in Counter (CTR) mode. The conversion process involves encoding the key into\n * base64url format and setting the appropriate JWK parameters.\n *\n * The resulting JWK object includes the following properties:\n * - `kty`: Key Type, set to 'oct' for Octet Sequence (representing a symmetric key).\n * - `k`: The symmetric key, base64url-encoded.\n * - `kid`: Key ID, generated based on the JWK thumbprint.\n *\n * @example\n * ```ts\n * const privateKeyBytes = new Uint8Array([...]); // Replace with actual symmetric key bytes\n * const privateKey = await AesCtr.bytesToPrivateKey({ privateKeyBytes });\n * ```\n *\n * @param params - The parameters for the symmetric key conversion.\n * @param params.privateKeyBytes - The raw symmetric key as a Uint8Array.\n *\n * @returns A Promise that resolves to the symmetric key in JWK format.\n */\n public static async bytesToPrivateKey({ privateKeyBytes }: {\n privateKeyBytes: Uint8Array;\n }): Promise<Jwk> {\n // Construct the private key in JWK format.\n const privateKey: Jwk = {\n k : Convert.uint8Array(privateKeyBytes).toBase64Url(),\n kty : 'oct'\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n return privateKey;\n }\n\n /**\n * Decrypts the provided data using AES in Counter (CTR) mode.\n *\n * @remarks\n * This method performs AES-CTR decryption on the given encrypted data using the specified key.\n * Similar to the encryption process, it requires an initial counter block and the length\n * of the counter block, along with the encrypted data and the decryption key. The method\n * returns the decrypted data as a Uint8Array.\n *\n * @example\n * ```ts\n * const encryptedData = new Uint8Array([...]); // Encrypted data\n * const counter = new Uint8Array(16); // 16-byte (128-bit) counter block used during encryption\n * const key = { ... }; // A Jwk object representing the same AES key used for encryption\n * const decryptedData = await AesCtr.decrypt({\n * data: encryptedData,\n * counter,\n * key,\n * length: 64 // Length of the counter in bits\n * });\n * ```\n *\n * @param params - The parameters for the decryption operation.\n * @param params.key - The key to use for decryption, represented in JWK format.\n * @param params.data - The encrypted data to decrypt, as a Uint8Array.\n * @param params.counter - The initial value of the counter block.\n * @param params.length - The number of bits in the counter block that are used for the actual counter.\n *\n * @returns A Promise that resolves to the decrypted data as a Uint8Array.\n */\n public static async decrypt({ key, data, counter, length }: {\n key: Jwk;\n data: Uint8Array;\n counter: Uint8Array;\n length: number;\n }): Promise<Uint8Array> {\n // Validate the initial counter block length matches the AES block size.\n if (counter.byteLength !== AES_BLOCK_SIZE / 8) {\n throw new TypeError(`The counter must be ${AES_BLOCK_SIZE} bits in length`);\n }\n\n // Validate the length of the counter.\n if (length === 0 || length > COUNTER_MAX_LENGTH) {\n throw new TypeError(`The 'length' property must be in the range 1 to ${COUNTER_MAX_LENGTH}`);\n }\n\n // Get the Web Crypto API interface.\n const webCrypto = getWebcryptoSubtle();\n\n // Import the JWK into the Web Crypto API to use for the decrypt operation.\n const webCryptoKey = await webCrypto.importKey('jwk', key, { name: 'AES-CTR' }, true, ['decrypt']);\n\n // Decrypt the data.\n const plaintextBuffer = await webCrypto.decrypt(\n { name: 'AES-CTR', counter, length },\n webCryptoKey,\n data\n );\n\n // Convert from ArrayBuffer to Uint8Array.\n const plaintext = new Uint8Array(plaintextBuffer);\n\n return plaintext;\n }\n\n /**\n * Encrypts the provided data using AES in Counter (CTR) mode.\n *\n * @remarks\n * This method performs AES-CTR encryption on the given data using the specified key.\n * It requires the initial counter block and the length of the counter block, alongside\n * the data and key. The method is designed to work asynchronously and returns the\n * encrypted data as a Uint8Array.\n *\n * @example\n * ```ts\n * const data = new TextEncoder().encode('Messsage');\n * const counter = new Uint8Array(16); // 16-byte (128-bit) counter block\n * const key = { ... }; // A Jwk object representing an AES key\n * const encryptedData = await AesCtr.encrypt({\n * data,\n * counter,\n * key,\n * length: 64 // Length of the counter in bits\n * });\n * ```\n *\n * @param params - The parameters for the encryption operation.\n * @param params.key - The key to use for encryption, represented in JWK format.\n * @param params.data - The data to encrypt, represented as a Uint8Array.\n * @param params.counter - The initial value of the counter block.\n * @param params.length - The number of bits in the counter block that are used for the actual counter.\n *\n * @returns A Promise that resolves to the encrypted data as a Uint8Array.\n */\n public static async encrypt({ key, data, counter, length }: {\n key: Jwk;\n data: Uint8Array;\n counter: Uint8Array;\n length: number;\n }): Promise<Uint8Array> {\n // Validate the initial counter block value length.\n if (counter.byteLength !== AES_BLOCK_SIZE / 8) {\n throw new TypeError(`The counter must be ${AES_BLOCK_SIZE} bits in length`);\n }\n\n // Validate the length of the counter.\n if (length === 0 || length > COUNTER_MAX_LENGTH) {\n throw new TypeError(`The 'length' property must be in the range 1 to ${COUNTER_MAX_LENGTH}`);\n }\n\n // Get the Web Crypto API interface.\n const webCrypto = getWebcryptoSubtle();\n\n // Import the JWK into the Web Crypto API to use for the encrypt operation.\n const webCryptoKey = await webCrypto.importKey('jwk', key, { name: 'AES-CTR' }, true, ['encrypt', 'decrypt']);\n\n // Encrypt the data.\n const ciphertextBuffer = await webCrypto.encrypt(\n { name: 'AES-CTR', counter, length },\n webCryptoKey,\n data\n );\n\n // Convert from ArrayBuffer to Uint8Array.\n const ciphertext = new Uint8Array(ciphertextBuffer);\n\n return ciphertext;\n }\n\n /**\n * Generates a symmetric key for AES in Counter (CTR) mode in JSON Web Key (JWK) format.\n *\n * @remarks\n * This method creates a new symmetric key of a specified length suitable for use with\n * AES-CTR encryption. It uses cryptographically secure random number generation to\n * ensure the uniqueness and security of the key. The generated key adheres to the JWK\n * format, making it compatible with common cryptographic standards and easy to use in\n * various cryptographic processes.\n *\n * The generated key includes the following components:\n * - `kty`: Key Type, set to 'oct' for Octet Sequence.\n * - `k`: The symmetric key component, base64url-encoded.\n * - `kid`: Key ID, generated based on the JWK thumbprint.\n *\n * @example\n * ```ts\n * const length = 256; // Length of the key in bits (e.g., 128, 192, 256)\n * const privateKey = await AesCtr.generateKey({ length });\n * ```\n *\n * @param params - The parameters for the key generation.\n * @param params.length - The length of the key in bits. Common lengths are 128, 192, and 256 bits.\n *\n * @returns A Promise that resolves to the generated symmetric key in JWK format.\n */\n public static async generateKey({ length }: {\n length: typeof AES_KEY_LENGTHS[number];\n }): Promise<Jwk> {\n // Validate the key length.\n if (!(AES_KEY_LENGTHS as readonly number[]).includes(length)) {\n throw new RangeError(`The key length is invalid: Must be ${AES_KEY_LENGTHS.join(', ')} bits`);\n }\n\n // Get the Web Crypto API interface.\n const webCrypto = getWebcryptoSubtle();\n\n // Generate a random private key.\n // See https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#usage_notes for\n // an explanation for why Web Crypto generateKey() is used instead of getRandomValues().\n const webCryptoKey = await webCrypto.generateKey( { name: 'AES-CTR', length }, true, ['encrypt']);\n\n // Export the private key in JWK format.\n const { ext, key_ops, ...privateKey } = await webCrypto.exportKey('jwk', webCryptoKey);\n\n // Compute the JWK thumbprint and set as the key ID.\n privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n return privateKey;\n }\n\n /**\n * Converts a private key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n *\n * @remarks\n * This method takes a symmetric key in JWK format and extracts its raw byte representation.\n * It decodes the 'k' parameter of the JWK value, which represents the symmetric key in base64url\n * encoding, into a byte array.\n *\n * @example\n * ```ts\n * const privateKey = { ... }; // A symmetric key in JWK format\n * const privateKeyBytes = await AesCtr.privateKeyToBytes({ privateKey });\n * ```\n *\n * @param params - The parameters for the symmetric key conversion.\n * @param params.privateKey - The symmetric key in JWK format.\n *\n * @returns A Promise that resolves to the symmetric key as a Uint8Array.\n */\n public static async privateKeyToBytes({ privateKey }: {\n privateKey: Jwk;\n }): Promise<Uint8Array> {\n // Verify the provided JWK represents a valid oct private key.\n if (!isOctPrivateJwk(privateKey)) {\n throw new Error(`AesCtr: The provided key is not a valid oct private key.`);\n }\n\n // Decode the provided private key to bytes.\n const privateKeyBytes = Convert.base64Url(privateKey.k).toUint8Array();\n\n return privateKeyBytes;\n }\n}", "import type { Cipher } from '../types/cipher.js';\nimport type { Jwk } from '../jose/jwk.js';\nimport type { KeyGenerator } from '../types/key-generator.js';\nimport type { DecryptParams, EncryptParams, GenerateKeyParams } from '../types/params-direct.js';\n\nimport { AesCtr } from '../primitives/aes-ctr.js';\nimport { CryptoAlgorithm } from './crypto-algorithm.js';\n\n/**\n * The `AesCtrGenerateKeyParams` interface defines the algorithm-specific parameters that should be\n * passed into the `generateKey()` method when using the AES-CTR algorithm.\n */\nexport interface AesCtrGenerateKeyParams extends GenerateKeyParams {\n /** Specifies the algorithm variant for key generation in AES-CTR mode.\n * The value determines the length of the key to be generated and must be one of the following:\n * - `\"A128CTR\"`: Generates a 128-bit key.\n * - `\"A192CTR\"`: Generates a 192-bit key.\n * - `\"A256CTR\"`: Generates a 256-bit key.\n */\n algorithm: 'A128CTR' | 'A192CTR' | 'A256CTR';\n}\n\n/**\n * The `AesCtrParams` interface defines the algorithm-specific parameters that should be passed\n * into the `encrypt()` and `decrypt()` methods when using the AES-CTR algorithm.\n */\nexport interface AesCtrParams {\n /** The initial value of the counter block. */\n counter: Uint8Array;\n\n /** The number of bits in the counter block that are used for the actual counter. */\n length: number;\n}\n\n/**\n * The `AesCtrAlgorithm` class provides a concrete implementation for cryptographic operations using\n * the AES algorithm in Counter (CTR) mode. This class implements both {@link Cipher | `Cipher`} and\n * { @link KeyGenerator | `KeyGenerator`} interfaces, providing key generation, encryption, and\n * decryption features.\n *\n * This class is typically accessed through implementations that extend the\n * {@link CryptoApi | `CryptoApi`} interface.\n */\nexport class AesCtrAlgorithm extends CryptoAlgorithm\n implements Cipher<EncryptParams & AesCtrParams, DecryptParams & AesCtrParams>,\n KeyGenerator<AesCtrGenerateKeyParams, Jwk> {\n\n /**\n * Decrypts the provided data using AES-CTR.\n *\n * @remarks\n * This method performs AES-CTR decryption on the given encrypted data using the specified key.\n * Similar to the encryption process, it requires an initial counter block and the length\n * of the counter block, along with the encrypted data and the decryption key. The method\n * returns the decrypted data as a Uint8Array.\n *\n * @example\n * ```ts\n * const aesCtr = new AesCtrAlgorithm();\n * const encryptedData = new Uint8Array([...]); // Encrypted data\n * const counter = new Uint8Array(16); // 16-byte (128-bit) counter block used during encryption\n * const key = { ... }; // A Jwk object representing the same AES key used for encryption\n * const decryptedData = await aesCtr.decrypt({\n * data: encryptedData,\n * counter,\n * key,\n * length: 128 // Length of the counter in bits\n * });\n * ```\n *\n * @param params - The parameters for the decryption operation.\n *\n * @returns A Promise that resolves to the decrypted data as a Uint8Array.\n */\n public async decrypt(params:\n DecryptParams & AesCtrParams\n ): Promise<Uint8Array> {\n const plaintext = AesCtr.decrypt(params);\n\n return plaintext;\n }\n\n /**\n * Encrypts the provided data using AES-CTR.\n *\n * @remarks\n * This method performs AES-CTR encryption on the given data using the specified key.\n * It requires the initial counter block and the length of the counter block, alongside\n * the data and key. The method is designed to work asynchronously and returns the\n * encrypted data as a Uint8Array.\n *\n * @example\n * ```ts\n * const aesCtr = new AesCtrAlgorithm();\n * const data = new TextEncoder().encode('Messsage');\n * const counter = new Uint8Array(16); // 16-byte (128-bit) counter block\n * const key = { ... }; // A Jwk object representing an AES key\n * const encryptedData = await aesCtr.encrypt({\n * data,\n * counter,\n * key,\n * length: 128 // Length of the counter in bits\n * });\n * ```\n *\n * @param params - The parameters for the encryption operation.\n *\n * @returns A Promise that resolves to the encrypted data as a Uint8Array.\n */\n public async encrypt(params:\n EncryptParams & AesCtrParams\n ): Promise<Uint8Array> {\n const ciphertext = AesCtr.encrypt(params);\n\n return ciphertext;\n }\n\n /**\n * Generates a symmetric key for AES in Counter (CTR) mode in JSON Web Key (JWK) format.\n *\n * @remarks\n * This method generates a symmetric AES key for use in CTR mode, based on the specified\n * `algorithm` parameter which determines the key length. It uses cryptographically secure random\n * number generation to ensure the uniqueness and security of the key. The key is returned in JWK\n * format.\n *\n * The generated key includes the following components:\n * - `kty`: Key Type, set to 'oct' for Octet Sequence.\n * - `k`: The symmetric key component, base64url-encoded.\n * - `kid`: Key ID, generated based on the JWK thumbprint.\n *\n * @example\n * ```ts\n * const aesCtr = new AesCtrAlgorithm();\n * const privateKey = await aesCtr.generateKey({ algorithm: 'A256CTR' });\n * ```\n *\n * @param params - The parameters for the key generation.\n *\n * @returns A Promise that resolves to the generated symmetric key in JWK format.\n */\n public async generateKey({ algorithm }:\n AesCtrGenerateKeyParams\n ): Promise<Jwk> {\n // Map algorithm name to key length.\n const length = { A128CTR: 128, A192CTR: 192, A256CTR: 256 }[algorithm] as 128 | 192 | 256;\n\n // Generate a random private key.\n const privateKey = await AesCtr.generateKey({ length });\n\n // Set the `alg` property based on the specified algorithm.\n privateKey.alg = algorithm;\n\n return privateKey;\n }\n}", "function number(n: number) {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error(`positive integer expected, not ${n}`);\n}\n\nfunction bool(b: boolean) {\n if (typeof b !== 'boolean') throw new Error(`boolean expected, not ${b}`);\n}\n\nexport function isBytes(a: unknown): a is Uint8Array {\n return (\n a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')\n );\n}\n\nfunction bytes(b: Uint8Array | undefined, ...lengths: number[]) {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);\n}\n\nexport type Hash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\nfunction hash(hash: Hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('hash must be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\n\nfunction exists(instance: any, checkFinished = true) {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\nfunction output(out: any, instance: any) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\n\nexport { number, bool, bytes, hash, exists, output };\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n", "/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */\nimport { bytes as abytes, isBytes } from './_assert.js';\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n// Cast array to different type\nexport const u8 = (arr: TypedArray) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u16 = (arr: TypedArray) =>\n new Uint16Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 2));\nexport const u32 = (arr: TypedArray) =>\n new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n\n// Cast array to view\nexport const createView = (arr: TypedArray) =>\n new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n\n// big-endian hardware is rare. Just in case someone still decides to run ciphers:\n// early-throw an error because we don't support BE yet.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE) throw new Error('Non little-endian hardware is not supported');\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 } as const;\nfunction asciiToBase16(char: number): number | undefined {\n if (char >= asciis._0 && char <= asciis._9) return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F) return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f) return char - (asciis._a - 10);\n return;\n}\n\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex(bytes));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\n\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => {};\n\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters: number, tick: number, cb: (i: number) => void) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error(`string expected, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/**\n * @example bytesToUtf8(new Uint8Array([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\nexport type Input = Uint8Array | string;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n else if (isBytes(data)) data = data.slice();\n else throw new Error(`Uint8Array expected, got ${typeof data}`);\n return data;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts: T2\n): T1 & T2 {\n if (opts == null || typeof opts !== 'object') throw new Error('options must be defined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a: Uint8Array, b: Uint8Array) {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n// For runtime check if class implements interface\nexport abstract class Hash<T extends Hash<T>> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n}\n\n// This will allow to re-use with composable things like packed & base encoders\n// Also, we probably can make tags composable\nexport type Cipher = {\n encrypt(plaintext: Uint8Array): Uint8Array;\n decrypt(ciphertext: Uint8Array): Uint8Array;\n};\n\nexport type AsyncCipher = {\n encrypt(plaintext: Uint8Array): Promise<Uint8Array>;\n decrypt(ciphertext: Uint8Array): Promise<Uint8Array>;\n};\n\nexport type CipherWithOutput = Cipher & {\n encrypt(plaintext: Uint8Array, output?: Uint8Array): Uint8Array;\n decrypt(ciphertext: Uint8Array, output?: Uint8Array): Uint8Array;\n};\n\n// Params is outside return type, so it is accessible before calling constructor\n// If function support multiple nonceLength's, we return best one\nexport type CipherParams = { blockSize: number; nonceLength?: number; tagLength?: number };\nexport type CipherCons<T extends any[]> = (key: Uint8Array, ...args: T) => Cipher;\n/**\n * @__NO_SIDE_EFFECTS__\n */\nexport const wrapCipher = <C extends CipherCons<any>, P extends CipherParams>(\n params: P,\n c: C\n): C & P => {\n Object.assign(c, params);\n return c as C & P;\n};\n\nexport type XorStream = (\n key: Uint8Array,\n nonce: Uint8Array,\n data: Uint8Array,\n output?: Uint8Array,\n counter?: number\n) => Uint8Array;\n\n// Polyfill for Safari 14\nexport function setBigUint64(\n view: DataView,\n byteOffset: number,\n value: bigint,\n isLE: boolean\n): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\nexport function u64Lengths(ciphertext: Uint8Array, AAD?: Uint8Array) {\n const num = new Uint8Array(16);\n const view = createView(num);\n setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true);\n setBigUint64(view, 8, BigInt(ciphertext.length), true);\n return num;\n}\n", "// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.js on#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated, we can just drop the import.\n//\n// Use full path so that Node.js can rewrite it to `cryptoNode.js`.\nimport { randomBytes, getWebcryptoSubtle } from '@noble/ciphers/crypto';\nimport { AsyncCipher, Cipher, concatBytes } from './utils.js';\nimport { number, bytes as abytes } from './_assert.js';\n\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport { randomBytes, getWebcryptoSubtle };\n\ntype RemoveNonceInner<T extends any[], Ret> = ((...args: T) => Ret) extends (\n arg0: any,\n arg1: any,\n ...rest: infer R\n) => any\n ? (key: Uint8Array, ...args: R) => Ret\n : never;\n\ntype RemoveNonce<T extends (...args: any) => any> = RemoveNonceInner<Parameters<T>, ReturnType<T>>;\ntype CipherWithNonce = ((key: Uint8Array, nonce: Uint8Array, ...args: any[]) => Cipher) & {\n nonceLength: number;\n};\n\n// Uses CSPRG for nonce, nonce injected in ciphertext\nexport function managedNonce<T extends CipherWithNonce>(fn: T): RemoveNonce<T> {\n number(fn.nonceLength);\n return ((key: Uint8Array, ...args: any[]): any => ({\n encrypt: (plaintext: Uint8Array, ...argsEnc: any[]) => {\n const { nonceLength } = fn;\n const nonce = randomBytes(nonceLength);\n const ciphertext = (fn(key, nonce, ...args).encrypt as any)(plaintext, ...argsEnc);\n const out = concatBytes(nonce, ciphertext);\n ciphertext.fill(0);\n return out;\n },\n decrypt: (ciphertext: Uint8Array, ...argsDec: any[]) => {\n const { nonceLength } = fn;\n const nonce = ciphertext.subarray(0, nonceLength);\n const data = ciphertext.subarray(nonceLength);\n return (fn(key, nonce, ...args).decrypt as any)(data, ...argsDec);\n },\n })) as RemoveNonce<T>;\n}\n\n// Overridable\nexport const utils = {\n async encrypt(key: Uint8Array, keyParams: any, cryptParams: any, plaintext: Uint8Array) {\n const cr = getWebcryptoSubtle();\n const iKey = await cr.importKey('raw', key, keyParams, true, ['encrypt']);\n const ciphertext = await cr.encrypt(cryptParams, iKey, plaintext);\n return new Uint8Array(ciphertext);\n },\n async decrypt(key: Uint8Array, keyParams: any, cryptParams: any, ciphertext: Uint8Array) {\n const cr = getWebcryptoSubtle();\n const iKey = await cr.importKey('raw', key, keyParams, true, ['decrypt']);\n const plaintext = await cr.decrypt(cryptParams, iKey, ciphertext);\n return new Uint8Array(plaintext);\n },\n};\n\nconst mode = {\n CBC: 'AES-CBC',\n CTR: 'AES-CTR',\n GCM: 'AES-GCM',\n} as const;\ntype BlockMode = (typeof mode)[keyof typeof mode];\n\nfunction getCryptParams(algo: BlockMode, nonce: Uint8Array, AAD?: Uint8Array) {\n if (algo === mode.CBC) return { name: mode.CBC, iv: nonce };\n if (algo === mode.CTR) return { name: mode.CTR, counter: nonce, length: 64 };\n if (algo === mode.GCM) {\n if (AAD) return { name: mode.GCM, iv: nonce, additionalData: AAD };\n else return { name: mode.GCM, iv: nonce };\n }\n\n throw new Error('unknown aes block mode');\n}\n\nfunction generate(algo: BlockMode) {\n return (key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array): AsyncCipher => {\n abytes(key);\n abytes(nonce);\n const keyParams = { name: algo, length: key.length * 8 };\n const cryptParams = getCryptParams(algo, nonce, AAD);\n return {\n // keyLength,\n encrypt(plaintext: Uint8Array) {\n abytes(plaintext);\n return utils.encrypt(key, keyParams, cryptParams, plaintext);\n },\n decrypt(ciphertext: Uint8Array) {\n abytes(ciphertext);\n return utils.decrypt(key, keyParams, cryptParams, ciphertext);\n },\n };\n };\n}\n\nexport const cbc = generate(mode.CBC);\nexport const ctr = generate(mode.CTR);\nexport const gcm = generate(mode.GCM);\n\n// // Type tests\n// import { siv, gcm, ctr, ecb, cbc } from '../aes.js';\n// import { xsalsa20poly1305 } from '../salsa.js';\n// import { chacha20poly1305, xchacha20poly1305 } from '../chacha.js';\n\n// const wsiv = managedNonce(siv);\n// const wgcm = managedNonce(gcm);\n// const wctr = managedNonce(ctr);\n// const wcbc = managedNonce(cbc);\n// const wsalsapoly = managedNonce(xsalsa20poly1305);\n// const wchacha = managedNonce(chacha20poly1305);\n// const wxchacha = managedNonce(xchacha20poly1305);\n\n// // should fail\n// const wcbc2 = managedNonce(managedNonce(cbc));\n// const wecb = managedNonce(ecb);\n", "import { Convert } from '@enbox/common';\nimport { getWebcryptoSubtle } from '@noble/ciphers/webcrypto';\n\nimport type { Jwk } from '../jose/jwk.js';\n\nimport { computeJwkThumbprint, isOctPrivateJwk } from '../jose/jwk.js';\n\n/**\n * Const defining the AES-GCM initialization vector (IV) length in bits.\n *\n * @remarks\n * NIST Special Publication 800-38D, Section 5.2.1.1 states that the IV length:\n * > For IVs, it is recommended that implementations restrict support to the length of 96 bits, to\n * > promote interoperability, efficiency, and simplicity of design.\n *\n * This implementation does not support IV lengths that are different from the value defined by\n * this constant.\n *\n * @see {@link https://doi.org/10.6028/NIST.SP.800-38D | NIST SP 800-38D}\n */\nconst AES_GCM_IV_LENGTH = 96;\n\n/**\n * Constant defining the AES key length values in bits.\n *\n * @remarks\n * NIST publication FIPS 197 states:\n * > The AES algorithm is capable of using cryptographic keys of 128, 192, and 256 bits to encrypt\n * > and decrypt data in blocks of 128 bits.\n *\n * This implementation does not support key lengths that are different from the three values\n * defined by this constant.\n *\n * @see {@link https://doi.org/10.6028/NIST.FIPS.197-upd1 | NIST FIPS 197}\n */\nconst AES_KEY_LENGTHS = [128, 192, 256] as const;\n\n/**\n * Constant defining the AES-GCM tag length values in bits.\n *\n * @remarks\n * NIST Special Publication 800-38D, Section 5.2.1.2 states that the tag length:\n * > may be any one of the following five values: 128, 120, 112, 104, or 96\n *\n * Although the NIST specification allows for tag lengths of 32 or 64 bits in certain applications,\n * the use of shorter tag lengths can be problematic for GCM due to targeted forgery attacks. As a\n * precaution, this implementation does not support tag lengths that are different from the five\n * values defined by this constant. See Appendix C of the NIST SP 800-38D specification for\n * additional guidance and details.\n *\n * @see {@link https://doi.org/10.6028/NIST.SP.800-38D | NIST SP 800-38D}\n */\nexport const AES_GCM_TAG_LENGTHS = [96, 104, 112, 120, 128] as const;\n\n/**\n * The `AesGcm` class provides a comprehensive set of utilities for cryptographic operations\n * using the Advanced Encryption Standard (AES) in Galois/Counter Mode (GCM). This class includes\n * methods for key generation, encryption, decryption, and conversions between raw byte arrays\n * and JSON Web Key (JWK) formats. It is designed to support AES-GCM, a symmetric key algorithm\n * that is widely used for its efficiency, security, and provision of authenticated encryption.\n *\n * AES-GCM is particularly favored for scenarios that require both confidentiality and integrity\n * of data. It integrates the counter mode of encryption with the Galois mode of authentication,\n * offering high performance and parallel processing capabilities.\n *\n * Key Features:\n * - Key Generation: Generate AES symmetric keys in JWK format.\n * - Key Conversion: Transform keys between raw byte arrays and JWK formats.\n * - Encryption: Encrypt data using AES-GCM with the provided symmetric key.\n * - Decryption: Decrypt data encrypted with AES-GCM using the corresponding symmetric key.\n *\n * The methods in this class are asynchronous, returning Promises to accommodate various\n * JavaScript environments.\n *\n * @example\n * ```ts\n * // Key Generation\n * const length = 256; // Length of the key in bits (e.g., 128, 192, 256)\n * const privateKey = await AesGcm.generateKey({ length });\n *\n * // Encryption\n * const data = new TextEncoder().encode('Messsage');\n * const iv = new Uint8Array(12); // 12-byte initialization vector\n * const encryptedData = await AesGcm.encrypt({\n * data,\n * iv,\n * key: privateKey\n * });\n *\n * // Decryption\n * const decryptedData = await AesGcm.decrypt({\n * data: encryptedData,\n * iv,\n * key: privateKey\n * });\n *\n * // Key Conversion\n * const privateKeyBytes = await AesGcm.privateKeyToBytes({ privateKey });\n * ```\n */\nexport class AesGcm {\n /**\n * Converts a raw private key in bytes to its corresponding JSON Web Key (JWK) format.\n *\n * @remarks\n * This method accepts a symmetric key represented as a byte array (Uint8Array) and\n * converts it into a JWK object for use with AES-GCM (Advanced Encryption Standard -\n * Galois/Counter Mode). The conversion process involves encoding the key into\n * base64url format and setting the appropriate JWK parameters.\n *\n * The resulting JWK object includes the following properties:\n * - `kty`: Key Type, set to 'oct' for Octet Sequence (representing a symmetric key).\n * - `k`: The symmetric key, base64url-encoded.\n * - `kid`: Key ID, generated based on the JWK thumbprint.\n *\n * @example\n * ```ts\n * const privateKeyBytes = new Uint8Array([...]); // Replace with actual symmetric key bytes\n * const privateKey = await AesGcm.bytesToPrivateKey({ privateKeyBytes });\n * ```\n *\n * @param params - The parameters for the symmetric key conversion.\n * @param params.privateKeyBytes - The raw symmetric key as a Uint8Array.\n *\n * @returns A Promise that resolves to the symmetric key in JWK format.\n */\n public static async bytesToPrivateKey({ privateKeyBytes }: {\n privateKeyBytes: Uint8Array;\n }): Promise<Jwk> {\n // Construct the private key in JWK format.\n const privateKey: Jwk = {\n k : Convert.uint8Array(privateKeyBytes).toBase64Url(),\n kty : 'oct'\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n return privateKey;\n }\n\n /**\n * Decrypts the provided data using AES-GCM.\n *\n * @remarks\n * This method performs AES-GCM decryption on the given encrypted data using the specified key.\n * It requires an initialization vector (IV), the encrypted data along with the decryption key,\n * and optionally, additional authenticated data (AAD). The method returns the decrypted data as a\n * Uint8Array. The optional `tagLength` parameter specifies the size in bits of the authentication\n * tag used when encrypting the data. If not specified, the default tag length of 128 bits is\n * used.\n *\n * @example\n * ```ts\n * const encryptedData = new Uint8Array([...]); // Encrypted data\n * const iv = new Uint8Array([...]); // Initialization vector used during encryption\n * const additionalData = new Uint8Array([...]); // Optional additional authenticated data\n * const key = { ... }; // A Jwk object representing the AES key\n * const decryptedData = await AesGcm.decrypt({\n * data: encryptedData,\n * iv,\n * additionalData,\n * key,\n * tagLength: 128 // Optional tag length in bits\n * });\n * ```\n *\n * @param params - The parameters for the decryption operation.\n * @param params.key - The key to use for decryption, represented in JWK format.\n * @param params.data - The encrypted data to decrypt, represented as a Uint8Array.\n * @param params.iv - The initialization vector, represented as a Uint8Array.\n * @param params.additionalData - Optional additional authenticated data. Optional.\n * @param params.tagLength - The length of the authentication tag in bits. Optional.\n *\n * @returns A Promise that resolves to the decrypted data as a Uint8Array.\n */\n public static async decrypt({ key, data, iv, additionalData, tagLength }: {\n key: Jwk;\n data: Uint8Array;\n iv: Uint8Array;\n additionalData?: Uint8Array;\n tagLength?: typeof AES_GCM_TAG_LENGTHS[number];\n }): Promise<Uint8Array> {\n // Validate the initialization vector length.\n if (iv.byteLength !== AES_GCM_IV_LENGTH / 8) {\n throw new TypeError(`The initialization vector must be ${AES_GCM_IV_LENGTH} bits in length`);\n }\n\n // Validate the tag length.\n if (tagLength && !(AES_GCM_TAG_LENGTHS as readonly number[]).includes(tagLength)) {\n throw new RangeError(`The tag length is invalid: Must be ${AES_GCM_TAG_LENGTHS.join(', ')} bits`);\n }\n\n // Get the Web Crypto API interface.\n const webCrypto = getWebcryptoSubtle();\n\n // Import the JWK into the Web Crypto API to use for the decrypt operation.\n const webCryptoKey = await webCrypto.importKey('jwk', key, { name: 'AES-GCM' }, true, ['decrypt']);\n\n // Note: Some browser implementations of the Web Crypto API throw an error if additionalData or\n // tagLength are undefined, so only include them in the algorithm object if they are defined.\n const algorithm = {\n name: 'AES-GCM',\n iv,\n ...(tagLength && { tagLength }),\n ...(additionalData && { additionalData })\n };\n\n // Decrypt the data.\n const plaintextBuffer = await webCrypto.decrypt(algorithm, webCryptoKey, data);\n\n // Convert from ArrayBuffer to Uint8Array.\n const plaintext = new Uint8Array(plaintextBuffer);\n\n return plaintext;\n }\n\n /**\n * Encrypts the provided data using AES-GCM.\n *\n * @remarks\n * This method performs AES-GCM encryption on the given data using the specified key.\n * It requires an initialization vector (IV), the encrypted data along with the decryption key,\n * and optionally, additional authenticated data (AAD). The method returns the encrypted data as a\n * Uint8Array. The optional `tagLength` parameter specifies the size in bits of the authentication\n * tag generated in the encryption operation and used for authentication in the corresponding\n * decryption. If not specified, the default tag length of 128 bits is used.\n *\n * @example\n * ```ts\n * const data = new TextEncoder().encode('Messsage');\n * const iv = new Uint8Array([...]); // Initialization vector\n * const additionalData = new Uint8Array([...]); // Optional additional authenticated data\n * const key = { ... }; // A Jwk object representing an AES key\n * const encryptedData = await AesGcm.encrypt({\n * data,\n * iv,\n * additionalData,\n * key,\n * tagLength: 128 // Optional tag length in bits\n * });\n * ```\n *\n * @param params - The parameters for the encryption operation.\n * @param params.key - The key to use for encryption, represented in JWK format.\n * @param params.data - The data to encrypt, represented as a Uint8Array.\n * @param params.iv - The initialization vector, represented as a Uint8Array.\n * @param params.additionalData - Optional additional authenticated data. Optional.\n * @param params.tagLength - The length of the authentication tag in bits. Optional.\n *\n * @returns A Promise that resolves to the encrypted data as a Uint8Array.\n */\n public static async encrypt({ data, iv, key, additionalData, tagLength }: {\n key: Jwk;\n data: Uint8Array;\n iv: Uint8Array;\n additionalData?: Uint8Array;\n tagLength?: typeof AES_GCM_TAG_LENGTHS[number];\n }): Promise<Uint8Array> {\n // Validate the initialization vector length.\n if (iv.byteLength !== AES_GCM_IV_LENGTH / 8) {\n throw new TypeError(`The initialization vector must be ${AES_GCM_IV_LENGTH} bits in length`);\n }\n\n // Validate the tag length.\n if (tagLength && !(AES_GCM_TAG_LENGTHS as readonly number[]).includes(tagLength)) {\n throw new RangeError(`The tag length is invalid: Must be ${AES_GCM_TAG_LENGTHS.join(', ')} bits`);\n }\n\n // Get the Web Crypto API interface.\n const webCrypto = getWebcryptoSubtle();\n\n // Import the JWK into the Web Crypto API to use for the encrypt operation.\n const webCryptoKey = await webCrypto.importKey('jwk', key, { name: 'AES-GCM' }, true, ['encrypt']);\n\n // Note: Some browser implementations of the Web Crypto API throw an error if additionalData or\n // tagLength are undefined, so only include them in the algorithm object if they are defined.\n const algorithm = {\n name: 'AES-GCM',\n iv,\n ...(tagLength && { tagLength }),\n ...(additionalData && { additionalData })\n };\n\n // Encrypt the data.\n const ciphertextBuffer = await webCrypto.encrypt(algorithm, webCryptoKey, data);\n\n // Convert from ArrayBuffer to Uint8Array.\n const ciphertext = new Uint8Array(ciphertextBuffer);\n\n return ciphertext;\n }\n\n /**\n * Generates a symmetric key for AES in Galois/Counter Mode (GCM) in JSON Web Key (JWK) format.\n *\n * @remarks\n * This method creates a new symmetric key of a specified length suitable for use with\n * AES-GCM encryption. It leverages cryptographically secure random number generation\n * to ensure the uniqueness and security of the key. The generated key adheres to the JWK\n * format, facilitating compatibility with common cryptographic standards and ease of use\n * in various cryptographic applications.\n *\n * The generated key includes these components:\n * - `kty`: Key Type, set to 'oct' for Octet Sequence, indicating a symmetric key.\n * - `k`: The symmetric key component, base64url-encoded.\n * - `kid`: Key ID, generated based on the JWK thumbprint, providing a unique identifier.\n *\n * @example\n * ```ts\n * const length = 256; // Length of the key in bits (e.g., 128, 192, 256)\n * const privateKey = await AesGcm.generateKey({ length });\n * ```\n *\n * @param params - The parameters for the key generation.\n * @param params.length - The length of the key in bits. Common lengths are 128, 192, and 256 bits.\n *\n * @returns A Promise that resolves to the generated symmetric key in JWK format.\n */\n public static async generateKey({ length }: {\n length: typeof AES_KEY_LENGTHS[number];\n }): Promise<Jwk> {\n // Validate the key length.\n if (!(AES_KEY_LENGTHS as readonly number[]).includes(length)) {\n throw new RangeError(`The key length is invalid: Must be ${AES_KEY_LENGTHS.join(', ')} bits`);\n }\n\n // Get the Web Crypto API interface.\n const webCrypto = getWebcryptoSubtle();\n\n // Generate a random private key.\n // See https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#usage_notes for\n // an explanation for why Web Crypto generateKey() is used instead of getRandomValues().\n const webCryptoKey = await webCrypto.generateKey( { name: 'AES-GCM', length }, true, ['encrypt']);\n\n // Export the private key in JWK format.\n const { ext, key_ops, ...privateKey } = await webCrypto.exportKey('jwk', webCryptoKey);\n\n // Compute the JWK thumbprint and set as the key ID.\n privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n return privateKey;\n }\n\n /**\n * Converts a private key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n *\n * @remarks\n * This method takes a symmetric key in JWK format and extracts its raw byte representation.\n * It focuses on the 'k' parameter of the JWK, which represents the symmetric key component\n * in base64url encoding. The method decodes this value into a byte array, providing\n * the symmetric key in its raw binary form.\n *\n * @example\n * ```ts\n * const privateKey = { ... }; // A symmetric key in JWK format\n * const privateKeyBytes = await AesGcm.privateKeyToBytes({ privateKey });\n * ```\n *\n * @param params - The parameters for the symmetric key conversion.\n * @param params.privateKey - The symmetric key in JWK format.\n *\n * @returns A Promise that resolves to the symmetric key as a Uint8Array.\n */\n public static async privateKeyToBytes({ privateKey }: {\n privateKey: Jwk;\n }): Promise<Uint8Array> {\n // Verify the provided JWK represents a valid oct private key.\n if (!isOctPrivateJwk(privateKey)) {\n throw new Error(`AesGcm: The provided key is not a valid oct private key.`);\n }\n\n // Decode the provided private key to bytes.\n const privateKeyBytes = Convert.base64Url(privateKey.k).toUint8Array();\n\n return privateKeyBytes;\n }\n}", "import type { AES_GCM_TAG_LENGTHS } from '../primitives/aes-gcm.js';\nimport type { Cipher } from '../types/cipher.js';\nimport type { Jwk } from '../jose/jwk.js';\nimport type { KeyGenerator } from '../types/key-generator.js';\nimport type { DecryptParams, EncryptParams, GenerateKeyParams } from '../types/params-direct.js';\n\nimport { AesGcm } from '../primitives/aes-gcm.js';\nimport { CryptoAlgorithm } from './crypto-algorithm.js';\n\n/**\n * The `AesGcmGenerateKeyParams` interface defines the algorithm-specific parameters that should be\n * passed into the `generateKey()` method when using the AES-GCM algorithm.\n */\nexport interface AesGcmGenerateKeyParams extends GenerateKeyParams {\n /** Specifies the algorithm variant for key generation in AES-GCM mode.\n * The value determines the length of the key to be generated and must be one of the following:\n * - `\"A128GCM\"`: Generates a 128-bit key.\n * - `\"A192GCM\"`: Generates a 192-bit key.\n * - `\"A256GCM\"`: Generates a 256-bit key.\n */\n algorithm: 'A128GCM' | 'A192GCM' | 'A256GCM';\n}\n\n/**\n * The `AesGcmParams` interface defines the algorithm-specific parameters that should be passed\n * into the `encrypt()` and `decrypt()` methods when using the AES-GCM algorithm.\n */\nexport interface AesGcmParams {\n /**\n * The `additionalData` property is used for authentication alongside encrypted data but isn't\n * encrypted itself. It must match in both encryption and decryption; a mismatch will cause\n * decryption to fail. This feature allows for the authentication of data without encrypting it.\n *\n * The `additionalData` property is optional and omitting it does not compromise encryption\n * security.\n */\n additionalData?: Uint8Array;\n\n /**\n * The initialization vector (IV) must be unique for every encryption operation carried out with a\n * given key. The IV need not be secret, but it must be unpredictable: that is, the IV must not be\n * reused with the same key. The IV must be 12 bytes (96 bits) in length in accordance with the\n * AES-GCM specification recommendedation to promote interoperability and efficiency.\n *\n * Note: It is OK to transmit the IV in the clear with the encrypted message.\n */\n iv: Uint8Array;\n\n /**\n * This property determines the size in bits of the authentication tag generated in the encryption\n * operation and used for authentication in the corresponding decryption. In accordance with the\n * AES-GCM specification, the tag length must be 96, 104, 112, 120 or 128.\n *\n * The `tagLength` property is optional and defaults to 128 bits if omitted.\n */\n tagLength?: typeof AES_GCM_TAG_LENGTHS[number];\n}\n\n/**\n * The `AesGcmAlgorithm` class provides a concrete implementation for cryptographic operations using\n * the AES algorithm in Galois/Counter Mode (GCM). This class implements both\n * {@link Cipher | `Cipher`} and { @link KeyGenerator | `KeyGenerator`} interfaces, providing\n * key generation, encryption, and decryption features.\n *\n * This class is typically accessed through implementations that extend the\n * {@link CryptoApi | `CryptoApi`} interface.\n */\nexport class AesGcmAlgorithm extends CryptoAlgorithm\n implements Cipher<AesGcmParams, AesGcmParams>,\n KeyGenerator<AesGcmGenerateKeyParams, Jwk> {\n\n /**\n * Decrypts the provided data using AES-GCM.\n *\n * @remarks\n * This method performs AES-GCM decryption on the given encrypted data using the specified key.\n * It requires an initialization vector (IV), the encrypted data along with the decryption key,\n * and optionally, additional authenticated data (AAD). The method returns the decrypted data as a\n * Uint8Array. The optional `tagLength` parameter specifies the size in bits of the authentication\n * tag used when encrypting the data. If not specified, the default tag length of 128 bits is\n * used.\n *\n * @example\n * ```ts\n * const aesGcm = new AesGcmAlgorithm();\n * const encryptedData = new Uint8Array([...]); // Encrypted data\n * const iv = new Uint8Array([...]); // Initialization vector used during encryption\n * const additionalData = new Uint8Array([...]); // Optional additional authenticated data\n * const key = { ... }; // A Jwk object representing the AES key\n * const decryptedData = await aesGcm.decrypt({\n * data: encryptedData,\n * iv,\n * additionalData,\n * key,\n * tagLength: 128 // Optional tag length in bits\n * });\n * ```\n *\n * @param params - The parameters for the decryption operation.\n *\n * @returns A Promise that resolves to the decrypted data as a Uint8Array.\n */\n public async decrypt(params:\n DecryptParams & AesGcmParams\n ): Promise<Uint8Array> {\n const plaintext = AesGcm.decrypt(params);\n\n return plaintext;\n }\n\n /**\n * Encrypts the provided data using AES-GCM.\n *\n * @remarks\n * This method performs AES-GCM encryption on the given data using the specified key.\n * It requires an initialization vector (IV), the encrypted data along with the decryption key,\n * and optionally, additional authenticated data (AAD). The method returns the encrypted data as a\n * Uint8Array. The optional `tagLength` parameter specifies the size in bits of the authentication\n * tag generated in the encryption operation and used for authentication in the corresponding\n * decryption. If not specified, the default tag length of 128 bits is used.\n *\n * @example\n * ```ts\n * const aesGcm = new AesGcmAlgorithm();\n * const data = new TextEncoder().encode('Messsage');\n * const iv = new Uint8Array([...]); // Initialization vector\n * const additionalData = new Uint8Array([...]); // Optional additional authenticated data\n * const key = { ... }; // A Jwk object representing an AES key\n * const encryptedData = await aesGcm.encrypt({\n * data,\n * iv,\n * additionalData,\n * key,\n * tagLength: 128 // Optional tag length in bits\n * });\n * ```\n *\n * @param params - The parameters for the encryption operation.\n *\n * @returns A Promise that resolves to the encrypted data as a Uint8Array.\n */\n public async encrypt(params:\n EncryptParams & AesGcmParams\n ): Promise<Uint8Array> {\n const ciphertext = AesGcm.encrypt(params);\n\n return ciphertext;\n }\n\n /**\n * Generates a symmetric key for AES in Galois/Counter Mode (GCM) in JSON Web Key (JWK) format.\n *\n * @remarks\n * This method generates a symmetric AES key for use in GCM mode, based on the specified\n * `algorithm` parameter which determines the key length. It uses cryptographically secure random\n * number generation to ensure the uniqueness and security of the key. The key is returned in JWK\n * format.\n *\n * The generated key includes the following components:\n * - `kty`: Key Type, set to 'oct' for Octet Sequence.\n * - `k`: The symmetric key component, base64url-encoded.\n * - `kid`: Key ID, generated based on the JWK thumbprint.\n *\n * @example\n * ```ts\n * const aesGcm = new AesGcmAlgorithm();\n * const privateKey = await aesGcm.generateKey({ algorithm: 'A256GCM' });\n * ```\n *\n * @param params - The parameters for the key generation.\n *\n * @returns A Promise that resolves to the generated symmetric key in JWK format.\n */\n public async generateKey({ algorithm }:\n AesGcmGenerateKeyParams\n ): Promise<Jwk> {\n // Map algorithm name to key length.\n const length = { A128GCM: 128, A192GCM: 192, A256GCM: 256 }[algorithm] as 128 | 192 | 256;\n\n // Generate a random private key.\n const privateKey = await AesGcm.generateKey({ length });\n\n // Set the `alg` property based on the specified algorithm.\n privateKey.alg = algorithm;\n\n return privateKey;\n }\n}", "import type { Jwk } from '../jose/jwk.js';\nimport type { UnwrapKeyParams, WrapKeyParams } from '../types/params-direct.js';\n\nimport { getWebcryptoSubtle } from '@noble/ciphers/webcrypto';\n\nimport { Convert } from '@enbox/common';\nimport { computeJwkThumbprint, isOctPrivateJwk } from '../jose/jwk.js';\nimport { CryptoError, CryptoErrorCode } from '../crypto-error.js';\n\n/**\n * Constant defining the AES key length values in bits.\n *\n * @remarks\n * NIST publication FIPS 197 states:\n * > The AES algorithm is capable of using cryptographic keys of 128, 192, and 256 bits to encrypt\n * > and decrypt data in blocks of 128 bits.\n *\n * This implementation does not support key lengths that are different from the three values\n * defined by this constant.\n *\n * @see {@link https://doi.org/10.6028/NIST.FIPS.197-upd1 | NIST FIPS 197}\n */\nconst AES_KEY_LENGTHS = [128, 192, 256] as const;\n\nexport class AesKw {\n /**\n * Converts a raw private key in bytes to its corresponding JSON Web Key (JWK) format.\n *\n * @remarks\n * This method takes a symmetric key represented as a byte array (Uint8Array) and\n * converts it into a JWK object for use with AES (Advanced Encryption Standard)\n * for key wrapping. The conversion process involves encoding the key into\n * base64url format and setting the appropriate JWK parameters.\n *\n * The resulting JWK object includes the following properties:\n * - `kty`: Key Type, set to 'oct' for Octet Sequence (representing a symmetric key).\n * - `k`: The symmetric key, base64url-encoded.\n * - `kid`: Key ID, generated based on the JWK thumbprint.\n *\n * @example\n * ```ts\n * const privateKeyBytes = new Uint8Array([...]); // Replace with actual symmetric key bytes\n * const privateKey = await AesKw.bytesToPrivateKey({ privateKeyBytes });\n * ```\n *\n * @param params - The parameters for the symmetric key conversion.\n * @param params.privateKeyBytes - The raw symmetric key as a Uint8Array.\n *\n * @returns A Promise that resolves to the symmetric key in JWK format.\n */\n public static async bytesToPrivateKey({ privateKeyBytes }: {\n privateKeyBytes: Uint8Array;\n }): Promise<Jwk> {\n // Construct the private key in JWK format.\n const privateKey: Jwk = {\n k : Convert.uint8Array(privateKeyBytes).toBase64Url(),\n kty : 'oct'\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n // Add algorithm identifier based on key length.\n const lengthInBits = privateKeyBytes.length * 8;\n privateKey.alg = { 128: 'A128KW', 192: 'A192KW', 256: 'A256KW' }[lengthInBits];\n\n return privateKey;\n }\n\n /**\n * Generates a symmetric key for AES for key wrapping in JSON Web Key (JWK) format.\n *\n * @remarks\n * This method creates a new symmetric key of a specified length suitable for use with\n * AES key wrapping. It uses cryptographically secure random number generation to\n * ensure the uniqueness and security of the key. The generated key adheres to the JWK\n * format, making it compatible with common cryptographic standards and easy to use in\n * various cryptographic processes.\n *\n * The generated key includes the following components:\n * - `kty`: Key Type, set to 'oct' for Octet Sequence.\n * - `k`: The symmetric key component, base64url-encoded.\n * - `kid`: Key ID, generated based on the JWK thumbprint.\n * - `alg`: Algorithm, set to 'A128KW', 'A192KW', or 'A256KW' for AES Key Wrap with the\n * specified key length.\n *\n * @example\n * ```ts\n * const length = 256; // Length of the key in bits (e.g., 128, 192, 256)\n * const privateKey = await AesKw.generateKey({ length });\n * ```\n *\n * @param params - The parameters for the key generation.\n * @param params.length - The length of the key in bits. Common lengths are 128, 192, and 256 bits.\n *\n * @returns A Promise that resolves to the generated symmetric key in JWK format.\n */\n public static async generateKey({ length }: {\n length: typeof AES_KEY_LENGTHS[number];\n }): Promise<Jwk> {\n // Validate the key length.\n if (!(AES_KEY_LENGTHS as readonly number[]).includes(length)) {\n throw new RangeError(`The key length is invalid: Must be ${AES_KEY_LENGTHS.join(', ')} bits`);\n }\n\n // Get the Web Crypto API interface.\n const webCrypto = getWebcryptoSubtle() as SubtleCrypto;\n\n // Generate a random private key.\n // See https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#usage_notes for\n // an explanation for why Web Crypto generateKey() is used instead of getRandomValues().\n const webCryptoKey = await webCrypto.generateKey( { name: 'AES-KW', length }, true, ['wrapKey', 'unwrapKey']);\n\n // Export the private key in JWK format.\n const { ext, key_ops, ...privateKey } = await webCrypto.exportKey('jwk', webCryptoKey) as Jwk;\n\n // Compute the JWK thumbprint and set as the key ID.\n privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n return privateKey;\n }\n\n /**\n * Converts a private key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n *\n * @remarks\n * This method takes a symmetric key in JWK format and extracts its raw byte representation.\n * It decodes the 'k' parameter of the JWK value, which represents the symmetric key in base64url\n * encoding, into a byte array.\n *\n * @example\n * ```ts\n * const privateKey = { ... }; // A symmetric key in JWK format\n * const privateKeyBytes = await AesKw.privateKeyToBytes({ privateKey });\n * ```\n *\n * @param params - The parameters for the symmetric key conversion.\n * @param params.privateKey - The symmetric key in JWK format.\n *\n * @returns A Promise that resolves to the symmetric key as a Uint8Array.\n */\n public static async privateKeyToBytes({ privateKey }: {\n privateKey: Jwk;\n }): Promise<Uint8Array> {\n // Verify the provided JWK represents a valid oct private key.\n if (!isOctPrivateJwk(privateKey)) {\n throw new Error(`AesKw: The provided key is not a valid oct private key.`);\n }\n\n // Decode the provided private key to bytes.\n const privateKeyBytes = Convert.base64Url(privateKey.k).toUint8Array();\n\n return privateKeyBytes;\n }\n\n public static async unwrapKey({ wrappedKeyBytes, wrappedKeyAlgorithm, decryptionKey }:\n UnwrapKeyParams\n ): Promise<Jwk> {\n if (!('alg' in decryptionKey && decryptionKey.alg)) {\n throw new CryptoError(CryptoErrorCode.InvalidJwk, `The decryption key is missing the 'alg' property.`);\n }\n\n if (!['A128KW', 'A192KW', 'A256KW'].includes(decryptionKey.alg)) {\n throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `The 'decryptionKey' algorithm is not supported: ${decryptionKey.alg}`);\n }\n\n // Get the Web Crypto API interface.\n const webCrypto = getWebcryptoSubtle() as SubtleCrypto;\n\n // Import the decryption key for use with the Web Crypto API.\n const decryptionCryptoKey = await webCrypto.importKey(\n 'jwk', // key format\n decryptionKey as JsonWebKey, // key data\n { name: 'AES-KW' }, // algorithm identifier\n true, // key is extractable\n ['unwrapKey'] // key usages\n );\n\n // Map the private key's JOSE algorithm name to the Web Crypto API algorithm identifier.\n const webCryptoAlgorithm = {\n A128KW : 'AES-KW', A192KW : 'AES-KW', A256KW : 'AES-KW',\n A128GCM : 'AES-GCM', A192GCM : 'AES-GCM', A256GCM : 'AES-GCM',\n }[wrappedKeyAlgorithm];\n\n if (!webCryptoAlgorithm) {\n throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `The 'wrappedKeyAlgorithm' is not supported: ${wrappedKeyAlgorithm}`);\n }\n\n // Unwrap the key using the Web Crypto API.\n const unwrappedCryptoKey = await webCrypto.unwrapKey(\n 'raw', // output format\n wrappedKeyBytes.buffer, // key to unwrap\n decryptionCryptoKey, // unwrapping key\n 'AES-KW', // algorithm identifier\n { name: webCryptoAlgorithm }, // unwrapped key algorithm identifier\n true, // key is extractable\n ['unwrapKey'] // key usages\n );\n\n // Export the unwrapped key in JWK format.\n const { ext, key_ops, ...unwrappedJsonWebKey } = await webCrypto.exportKey('jwk', unwrappedCryptoKey);\n const unwrappedKey = unwrappedJsonWebKey as Jwk;\n\n // Compute the JWK thumbprint and set as the key ID.\n unwrappedKey.kid = await computeJwkThumbprint({ jwk: unwrappedKey });\n\n return unwrappedKey;\n }\n\n public static async wrapKey({ unwrappedKey, encryptionKey }:\n WrapKeyParams\n ): Promise<Uint8Array> {\n if (!('alg' in encryptionKey && encryptionKey.alg)) {\n throw new CryptoError(CryptoErrorCode.InvalidJwk, `The encryption key is missing the 'alg' property.`);\n }\n\n if (!['A128KW', 'A192KW', 'A256KW'].includes(encryptionKey.alg)) {\n throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `The 'encryptionKey' algorithm is not supported: ${encryptionKey.alg}`);\n }\n\n if (!('alg' in unwrappedKey && unwrappedKey.alg)) {\n throw new CryptoError(CryptoErrorCode.InvalidJwk, `The private key to wrap is missing the 'alg' property.`);\n }\n\n // Get the Web Crypto API interface.\n const webCrypto = getWebcryptoSubtle() as SubtleCrypto;\n\n // Import the encryption key for use with the Web Crypto API.\n const encryptionCryptoKey = await webCrypto.importKey(\n 'jwk', // key format\n encryptionKey as JsonWebKey, // key data\n { name: 'AES-KW' }, // algorithm identifier\n true, // key is extractable\n ['wrapKey'] // key usages\n );\n\n // Map the private key's JOSE algorithm name to the Web Crypto API algorithm identifier.\n const webCryptoAlgorithm = {\n A128KW : 'AES-KW', A192KW : 'AES-KW', A256KW : 'AES-KW',\n A128GCM : 'AES-GCM', A192GCM : 'AES-GCM', A256GCM : 'AES-GCM',\n }[unwrappedKey.alg];\n\n if (!webCryptoAlgorithm) {\n throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `The 'unwrappedKey' algorithm is not supported: ${unwrappedKey.alg}`);\n }\n\n // Import the private key to wrap for use with the Web Crypto API.\n const unwrappedCryptoKey = await webCrypto.importKey(\n 'jwk', // key format\n unwrappedKey as JsonWebKey, // key data\n { name: webCryptoAlgorithm }, // algorithm identifier\n true, // key is extractable\n ['unwrapKey'] // key usages\n );\n\n // Wrap the key using the Web Crypto API.\n const wrappedKeyBuffer = await webCrypto.wrapKey(\n 'raw', // output format\n unwrappedCryptoKey, // key to wrap\n encryptionCryptoKey, // wrapping key\n 'AES-KW' // algorithm identifier\n );\n\n // Convert from ArrayBuffer to Uint8Array.\n const wrappedKeyBytes = new Uint8Array(wrappedKeyBuffer);\n\n return wrappedKeyBytes;\n }\n}\n", "import type { TypedArray } from '@noble/hashes/utils';\n\nimport { concatBytes } from '@noble/hashes/utils';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { Convert, universalTypeOf } from '@enbox/common';\n\n/**\n * ConcatKDF FixedInfo Parameters.\n *\n * This implementation follows the recommended format for `FixedInfo` specified in section 5.8.2\n * of the NIST.800-56A publication.\n *\n * @see {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Ar3.pdf | NIST.800-56A}\n * @see {@link https://datatracker.ietf.org/doc/html/rfc7518#section-4.6.2 | RFC 7518, Section 4.6.2}\n */\nexport type ConcatKdfFixedInfo = {\n /**\n * The algorithm the derived secret keying material will be used with.\n */\n algorithmId: string;\n\n /**\n * Information related to party U (initiator) involved in the key agreement\n * transaction. It could be a public key, identifier, or any other data.\n */\n partyUInfo: string | TypedArray;\n\n /**\n * Information related to party V (receiver) involved in the key\n * agreement transaction. Similar to partyUInfo, it could be a\n * public key, identifier, etc.\n */\n partyVInfo: string | TypedArray;\n\n /**\n * Optional field. It is usually used to ensure the uniqueness of the\n * derived keying material when the input keying material is used in\n * multiple key-derivation key-agreement transactions. It is usually\n * a public value such as the keyDataLen.\n */\n suppPubInfo?: number;\n\n /**\n * Optional field. It is used when it is desired to secretively\n * bind additional information into the derived keying material.\n * It is a secret value agreed upon by the entities who are party\n * to the key agreement.\n */\n suppPrivInfo?: string | TypedArray;\n};\n\n/**\n * An implementation of the Concatenation Key Derivation Function (ConcatKDF)\n * as specified in NIST.800-56A, a single-step key-derivation function (SSKDF).\n * ConcatKDF produces a derived key from a secret key (like a shared secret\n * from ECDH), and other optional public information. This implementation\n * specifically uses SHA-256 as the pseudorandom function (PRF).\n *\n * Note: This implementation allows for only a single round / repetition using the function\n * `K(1) = H(counter || Z || FixedInfo)`, where:\n * - `K(1)` is the derived key material after one round\n * - `H` is the SHA-256 hashing function\n * - `counter` is a 32-bit, big-endian bit string counter set to 0x00000001\n * - `Z` is the shared secret value obtained from a key agreement protocol\n * - `FixedInfo` is a bit string used to ensure that the derived keying material is adequately\n * \"bound\" to the key-agreement transaction.\n *\n * @example\n * ```ts\n * // Key Derivation\n * const derivedKeyingMaterial = await ConcatKdf.deriveKey({\n * sharedSecret: utils.randomBytes(32),\n * keyDataLen: 128,\n * fixedInfo: {\n * algorithmId: \"A128GCM\",\n * partyUInfo: \"Alice\",\n * partyVInfo: \"Bob\",\n * suppPubInfo: 128,\n * },\n * });\n * ```\n *\n * Additional Information:\n *\n * `Z`, or \"shared secret\":\n * The shared secret value obtained from a key agreement protocol, such as\n * Diffie-Hellman, ECDH (Elliptic Curve Diffie-Hellman). Importantly, this\n * shared secret is not directly used as the encryption or authentication\n * key, but as an input to a key derivation function (KDF), such as Concat\n * KDF, to generate the actual key. This adds an extra layer of security, as\n * even if the shared secret gets compromised, the actual encryption or\n * authentication key stays safe. This shared secret `Z` value is kept\n * confidential between the two parties in the key agreement protocol.\n *\n * @see {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Ar3.pdf | NIST.800-56A}\n * @see {@link https://datatracker.ietf.org/doc/html/rfc7518#section-4.6.2 | RFC 7518, Section 4.6.2}\n */\nexport class ConcatKdf {\n /**\n * Derives a key of a specified length from the input parameters.\n *\n * @example\n * ```ts\n * // Key Derivation\n * const derivedKeyingMaterial = await ConcatKdf.deriveKey({\n * sharedSecret: utils.randomBytes(32),\n * keyDataLen: 128,\n * fixedInfo: {\n * algorithmId: \"A128GCM\",\n * partyUInfo: \"Alice\",\n * partyVInfo: \"Bob\",\n * suppPubInfo: 128,\n * },\n * });\n * ```\n *\n * @param params - Input parameters for key derivation.\n * @param params.keyDataLen - The desired length of the derived key in bits.\n * @param params.sharedSecret - The shared secret key to derive from.\n * @param params.fixedInfo - Additional public information to use in key derivation.\n * @returns The derived key as a Uint8Array.\n *\n * @throws {Error} If the `keyDataLen` would require multiple rounds.\n */\n public static async deriveKey({ keyDataLen, fixedInfo, sharedSecret }: {\n keyDataLen: number;\n fixedInfo: ConcatKdfFixedInfo;\n sharedSecret: Uint8Array;\n }): Promise<Uint8Array> {\n // RFC 7518 Section 4.6.2 specifies using SHA-256 for ECDH key agreement:\n // \"Key derivation is performed using the Concat KDF, as defined in\n // Section 5.8.1 of [NIST.800-56A], where the Digest Method is SHA-256.\"\n // Reference: https://tools.ietf.org/html/rfc7518#section-4.6.2\n const hashLen = 256;\n\n // This implementation only supports single round Concat KDF.\n const roundCount = Math.ceil(keyDataLen / hashLen);\n if (roundCount !== 1) {\n throw new Error(`Concat KDF with ${roundCount} rounds not supported.`);\n }\n\n // Initialize a 32-bit, big-endian bit string counter as 0x00000001.\n const counter = new Uint8Array(4);\n new DataView(counter.buffer).setUint32(0, roundCount);\n\n // Compute the FixedInfo bit-string.\n const fixedInfoBytes = ConcatKdf.computeFixedInfo(fixedInfo);\n\n // Compute K(i) = H(counter || Z || FixedInfo)\n // return concatBytes(counter, sharedSecretZ, fixedInfo);\n const derivedKeyingMaterial = sha256(concatBytes(counter, sharedSecret, fixedInfoBytes));\n\n // Return the bit string of derived keying material of length keyDataLen bits.\n return derivedKeyingMaterial.slice(0, keyDataLen / 8);\n }\n\n /**\n * Computes the `FixedInfo` parameter for Concat KDF, which binds the derived key material to the\n * context of the key agreement transaction.\n *\n * @remarks\n * This implementation follows the recommended format for `FixedInfo` specified in section\n * 5.8.1.2.1 of the NIST.800-56A publication.\n *\n * `FixedInfo` is a bit string equal to the following concatenation:\n * `AlgorithmID || PartyUInfo || PartyVInfo {|| SuppPubInfo }{|| SuppPrivInfo }`.\n *\n * `SuppPubInfo` is the key length in bits, big endian encoded as a 32-bit number. For example,\n * 128 would be [0, 0, 0, 128] and 256 would be [0, 0, 1, 0].\n *\n * @param params - Input data to construct FixedInfo.\n * @returns FixedInfo as a Uint8Array.\n */\n private static computeFixedInfo(params:\n ConcatKdfFixedInfo\n ): Uint8Array {\n // Required sub-fields.\n const algorithmId = ConcatKdf.toDataLenData({ data: params.algorithmId });\n const partyUInfo = ConcatKdf.toDataLenData({ data: params.partyUInfo });\n const partyVInfo = ConcatKdf.toDataLenData({ data: params.partyVInfo });\n // Optional sub-fields.\n const suppPubInfo = ConcatKdf.toDataLenData({ data: params.suppPubInfo, variableLength: false });\n const suppPrivInfo = ConcatKdf.toDataLenData({ data: params.suppPrivInfo });\n\n // Concatenate AlgorithmID || PartyUInfo || PartyVInfo || SuppPubInfo || SuppPrivInfo.\n const fixedInfo = concatBytes(algorithmId, partyUInfo, partyVInfo, suppPubInfo, suppPrivInfo);\n\n return fixedInfo;\n }\n\n /**\n * Encodes input data as a length-prefixed byte string, or\n * as a fixed-length bit string if specified.\n *\n * If variableLength = true, return the data in the form Datalen || Data,\n * where Data is a variable-length string of zero or more (eight-bit)\n * bytes, and Datalen is a fixed-length, big-endian counter that\n * indicates the length (in bytes) of Data.\n *\n * If variableLength = false, return the data formatted as a\n * fixed-length bit string.\n *\n * @param params - Input data and options for the conversion.\n * @param params.data - The input data to encode. Must be a type convertible to Uint8Array by the Convert class.\n * @param params.variableLength - Whether to output the data as variable length. Default is true.\n *\n * @returns The input data encoded as a Uint8Array.\n *\n * @throws {TypeError} If fixed-length data is not a number.\n */\n private static toDataLenData({ data, variableLength = true }: {\n data: unknown;\n variableLength?: boolean;\n }): Uint8Array {\n let encodedData: Uint8Array;\n const dataType = universalTypeOf(data);\n\n // Return an emtpy octet sequence if data is not specified.\n if (dataType === 'Undefined') {\n return new Uint8Array(0);\n }\n\n if (variableLength) {\n const dataU8A = (dataType === 'Uint8Array')\n ? data as Uint8Array\n : new Convert(data, dataType).toUint8Array();\n const bufferLength = dataU8A.length;\n encodedData = new Uint8Array(4 + bufferLength);\n new DataView(encodedData.buffer).setUint32(0, bufferLength);\n encodedData.set(dataU8A, 4);\n\n } else {\n if (typeof data !== 'number') {\n throw TypeError('Fixed length input must be a number.');\n }\n encodedData = new Uint8Array(4);\n new DataView(encodedData.buffer).setUint32(0, data);\n }\n\n return encodedData;\n }\n}", "import type { DeriveKeyBytesParams } from '../types/params-direct.js';\n\nimport { getWebcryptoSubtle } from '@noble/ciphers/webcrypto';\n\nimport { Convert } from '@enbox/common';\n\n/**\n * The object that should be passed into `Hkdf.deriveKeyBytes()`, when using the HKDF algorithm.\n */\nexport type HkdfParams = {\n /**\n * A string representing the digest algorithm to use. This may be one of:\n * - 'SHA-256'\n * - 'SHA-384'\n * - 'SHA-512'\n */\n hash: 'SHA-256' | 'SHA-384' | 'SHA-512';\n\n /**\n * The salt value to use in the derivation process.\n *\n * Ideally, the salt is a random or pseudo-random value with the same length as the output of the\n * digest function. Unlike the input key material passed into deriveKey(), salt does not need to\n * be kept secret.\n *\n * Note: The {@link https://datatracker.ietf.org/doc/html/rfc5869 | HKDF specification} states\n * that adding salt \"adds significantly to the strength of HKDF\".\n */\n salt: string | Uint8Array;\n\n /**\n * Optional application-specific information to use in the HKDF.\n *\n * If given, this value is used to bind the derived key to application-specific contextual\n * information. This makes it possible to derive different keys for different contexts while using\n * the same input key material.\n *\n * If not provided, the `info` value is set to an empty array.\n *\n * Note: It is important that the `info` value be independent and unrelated to the input key\n * material.\n */\n info?: string | Uint8Array,\n};\n\n/**\n * The `Hkdf` class provides an interface for HMAC-based Extract-and-Expand Key Derivation Function (HKDF)\n * as defined in RFC 5869.\n *\n * Note: The `baseKeyBytes` that will be the input key material for HKDF should be a high-entropy secret\n * value, such as a cryptographic key. It should be kept confidential and not be derived from a\n * low-entropy value, such as a password.\n *\n * @example\n * ```ts\n * const info = new Uint8Array([...]);\n * const derivedKeyBytes = await Hkdf.deriveKeyBytes({\n * baseKeyBytes: new Uint8Array([...]), // Input keying material\n * hash: 'SHA-256', // The hash function to use ('SHA-256', 'SHA-384', 'SHA-512')\n * salt: new Uint8Array([...]), // The salt value\n * info: new Uint8Array([...]), // Optional application-specific information\n * length: 256 // The length of the derived key in bits\n * });\n * ```\n */\nexport class Hkdf {\n /**\n * Derives a key using the HMAC-based Extract-and-Expand Key Derivation Function (HKDF).\n *\n * This method generates a derived key using a hash function from input keying material given as\n * `baseKeyBytes`. The length of the derived key can be specified. Optionally, it can also use a salt\n * and info for the derivation process.\n *\n * HKDF is useful in various cryptographic applications and protocols, especially when\n * there's a need to derive multiple keys from a single source of key material.\n *\n * Note: The `baseKeyBytes` that will be the input key material for HKDF should be a high-entropy\n * secret value, such as a cryptographic key. It should be kept confidential and not be derived\n * from a low-entropy value, such as a password.\n *\n * @example\n * ```ts\n * const info = new Uint8Array([...]);\n * const derivedKeyBytes = await Hkdf.deriveKeyBytes({\n * baseKeyBytes: new Uint8Array([...]), // Input keying material\n * hash: 'SHA-256', // The hash function to use ('SHA-256', 'SHA-384', 'SHA-512')\n * salt: new Uint8Array([...]), // The salt value\n * info: new Uint8Array([...]), // Optional application-specific information\n * length: 256 // The length of the derived key in bits\n * });\n * ```\n *\n * @param params - The parameters for key derivation.\n * @returns A Promise that resolves to the derived key as a byte array.\n */\n public static async deriveKeyBytes({ baseKeyBytes, length, hash, salt, info = new Uint8Array() }:\n DeriveKeyBytesParams & HkdfParams\n ): Promise<Uint8Array> {\n // Get the Web Crypto API interface.\n const webCrypto = getWebcryptoSubtle() as SubtleCrypto;\n\n // Import the baseKeyBytes into the Web Crypto API to use for the key derivation operation.\n const webCryptoKey = await webCrypto.importKey('raw', baseKeyBytes, { name: 'HKDF' }, false, ['deriveBits']);\n\n // Convert the salt and info to Uint8Array if they are provided as strings.\n const saltBytes = typeof salt === 'string' ? Convert.string(salt).toUint8Array() : salt;\n const infoBytes = typeof info === 'string' ? Convert.string(info).toUint8Array() : info;\n\n // Derive the bytes using the Web Crypto API.\n const derivedKeyBuffer = await webCrypto.deriveBits(\n { name: 'HKDF', hash, salt: saltBytes, info: infoBytes },\n webCryptoKey,\n length\n );\n\n // Convert from ArrayBuffer to Uint8Array.\n const derivedKeyBytes = new Uint8Array(derivedKeyBuffer);\n\n return derivedKeyBytes;\n }\n}\n", "import type { DeriveKeyBytesParams } from '../types/params-direct.js';\n\nimport { getWebcryptoSubtle } from '@noble/ciphers/webcrypto';\n\nimport { crypto } from '@noble/hashes/crypto';\n\n/**\n * The object that should be passed into `Pbkdf2.deriveKeyBytes()`, when using the PBKDF2 algorithm.\n */\nexport interface Pbkdf2Params {\n /**\n * A string representing the digest algorithm to use. This may be one of:\n * - 'SHA-256'\n * - 'SHA-384'\n * - 'SHA-512'\n */\n hash: 'SHA-256' | 'SHA-384' | 'SHA-512';\n\n /**\n * The salt value to use in the derivation process, as a Uint8Array. This should be a random or\n * pseudo-random value of at least 16 bytes. Unlike the `password`, `salt` does not need to be\n * kept secret.\n */\n salt: Uint8Array;\n\n /**\n * A `Number` representing the number of iterations the hash function will be executed in\n * `deriveKey()`. This impacts the computational cost of the `deriveKey()` operation, making it\n * more resistant to dictionary attacks. The higher the number, the more secure, but also slower,\n * the operation. Choose a value that balances security needs and performance for your\n * application.\n */\n iterations: number;\n}\n\n/**\n * The object that should be passed into `Pbkdf2.deriveKey()`, when using the PBKDF2 algorithm.\n */\nexport type Pbkdf2DeriveKeyParams = {\n /**\n * A string representing the digest algorithm to use. This may be one of:\n * - 'SHA-256'\n * - 'SHA-384'\n * - 'SHA-512'\n */\n hash: 'SHA-256' | 'SHA-384' | 'SHA-512';\n\n /**\n * The password from which to derive the key, represented as a Uint8Array.\n */\n password: Uint8Array;\n\n /**\n * The salt value to use in the derivation process, as a Uint8Array. This should be a random or\n * pseudo-random value of at least 16 bytes. Unlike the `password`, `salt` does not need to be\n * kept secret.\n */\n salt: Uint8Array;\n\n /**\n * A `Number` representing the number of iterations the hash function will be executed in\n * `deriveKey()`. This impacts the computational cost of the `deriveKey()` operation, making it\n * more resistant to dictionary attacks. The higher the number, the more secure, but also slower,\n * the operation. Choose a value that balances security needs and performance for your\n * application.\n */\n iterations: number;\n\n /**\n * The desired length of the derived key in bits. To be compatible with all browsers, the number\n * should be a multiple of 8.\n */\n length: number;\n};\n\n/**\n * The `Pbkdf2` class provides a secure way to derive cryptographic keys from a password\n * using the PBKDF2 (Password-Based Key Derivation Function 2) algorithm.\n *\n * The PBKDF2 algorithm is widely used for generating keys from passwords, as it applies\n * a pseudorandom function to the input password along with a salt value and iterates the\n * process multiple times to increase the key's resistance to brute-force attacks.\n *\n * This class offers a single static method `deriveKey` to perform key derivation.\n *\n * @example\n * ```ts\n * // Key Derivation\n * const derivedKey = await Pbkdf2.deriveKey({\n * hash: 'SHA-256', // The hash function to use ('SHA-256', 'SHA-384', 'SHA-512')\n * password: new TextEncoder().encode('password'), // The password as a Uint8Array\n * salt: new Uint8Array([...]), // The salt value\n * iterations: 1000, // The number of iterations\n * length: 256 // The length of the derived key in bits\n * });\n * ```\n *\n * @remarks\n * This class relies on the availability of the Web Crypto API.\n */\nexport class Pbkdf2 {\n /**\n * Derives a cryptographic key from a password using the PBKDF2 algorithm.\n *\n * @remarks\n * This method applies the PBKDF2 algorithm to the provided password along with\n * a salt value and iterates the process a specified number of times. It uses\n * a cryptographic hash function to enhance security and produce a key of the\n * desired length. The method is capable of utilizing either the Web Crypto API\n * or the Node.js Crypto module, depending on the environment's support.\n *\n * @example\n * ```ts\n * const derivedKey = await Pbkdf2.deriveKey({\n * hash: 'SHA-256',\n * password: new TextEncoder().encode('password'),\n * salt: new Uint8Array([...]),\n * iterations: 1000,\n * length: 256\n * });\n * ```\n *\n * @param params - The parameters for key derivation.\n * @param params.hash - The hash function to use, such as 'SHA-256', 'SHA-384', or 'SHA-512'.\n * @param params.password - The password from which to derive the key, represented as a Uint8Array.\n * @param params.salt - The salt value to use in the derivation process, as a Uint8Array.\n * @param params.iterations - The number of iterations to apply in the PBKDF2 algorithm.\n * @param params.length - The desired length of the derived key in bits.\n *\n * @returns A Promise that resolves to the derived key as a Uint8Array.\n */\n public static async deriveKey({ hash, password, salt, iterations, length }:\n Pbkdf2DeriveKeyParams\n ): Promise<Uint8Array> {\n // Import the password as a raw key for use with the Web Crypto API.\n const webCryptoKey = await crypto.subtle.importKey(\n 'raw',\n password,\n { name: 'PBKDF2' },\n false,\n ['deriveBits']\n );\n\n const derivedKeyBuffer = await crypto.subtle.deriveBits(\n { name: 'PBKDF2', hash, salt, iterations },\n webCryptoKey,\n length\n );\n\n // Convert from ArrayBuffer to Uint8Array.\n const derivedKey = new Uint8Array(derivedKeyBuffer);\n\n return derivedKey;\n }\n\n /**\n * Derives cryptographic key bytes from base key material using the PBKDF2 algorithm.\n *\n * @remarks\n * This method is similar to {@link Pbkdf2.deriveKey | `deriveKey()`} but accepts\n * raw key bytes (`baseKeyBytes`) instead of a password. It is intended for use cases\n * where the input key material is already available as a byte array.\n *\n * Notes:\n * - The `baseKeyBytes` that will be the input key material for PBKDF2 is expected to be a\n * low-entropy value, such as a password or passphrase. It should be kept confidential.\n * - In 2023,\n * {@link https://web.archive.org/web/20230123232056/https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#pbkdf2\n * | OWASP recommended}\n * a minimum of 600,000 iterations for PBKDF2-HMAC-SHA256 and 210,000 for PBKDF2-HMAC-SHA512.\n *\n * @example\n * ```ts\n * const derivedKeyBytes = await Pbkdf2.deriveKeyBytes({\n * baseKeyBytes: new TextEncoder().encode('password'),\n * hash: 'SHA-256',\n * salt: new Uint8Array([...]),\n * iterations: 600_000,\n * length: 256\n * });\n * ```\n *\n * @param params - The parameters for key derivation.\n * @returns A Promise that resolves to the derived key as a byte array.\n */\n public static async deriveKeyBytes({ baseKeyBytes, hash, salt, iterations, length }:\n DeriveKeyBytesParams & Pbkdf2Params\n ): Promise<Uint8Array> {\n // Get the Web Crypto API interface.\n const webCrypto = getWebcryptoSubtle() as SubtleCrypto;\n\n // Import the password as a raw key for use with the Web Crypto API.\n const webCryptoKey = await webCrypto.importKey(\n 'raw', // key format is raw bytes\n baseKeyBytes, // key data to import\n { name: 'PBKDF2' }, // algorithm identifier\n false, // key is not extractable\n ['deriveBits'] // key usages\n );\n\n // Derive the bytes using the Web Crypto API.\n const derivedKeyBuffer = await webCrypto.deriveBits(\n { name: 'PBKDF2', hash, salt, iterations },\n webCryptoKey,\n length\n );\n\n // Convert from ArrayBuffer to Uint8Array.\n const derivedKeyBytes = new Uint8Array(derivedKeyBuffer);\n\n return derivedKeyBytes;\n }\n}", "import { Convert } from '@enbox/common';\nimport { x25519 } from '@noble/curves/ed25519';\n\nimport type { Jwk } from '../jose/jwk.js';\nimport type { ComputePublicKeyParams, GetPublicKeyParams } from '../types/params-direct.js';\n\nimport { computeJwkThumbprint, isOkpPrivateJwk, isOkpPublicJwk } from '../jose/jwk.js';\n\n/**\n * The `X25519` class provides a comprehensive suite of utilities for working with the X25519\n * elliptic curve, widely used for key agreement protocols and cryptographic applications. It\n * provides methods for key generation, conversion, and Elliptic Curve Diffie-Hellman (ECDH)\n * key agreement, all aligned with standard cryptographic practices.\n *\n * The class supports conversions between raw byte formats and JSON Web Key (JWK) formats,\n * making it versatile for various cryptographic tasks. It adheres to RFC6090 for ECDH, ensuring\n * secure and effective handling of keys and cryptographic operations.\n *\n * Key Features:\n * - Key Generation: Generate X25519 private keys in JWK format.\n * - Key Conversion: Transform keys between raw byte arrays and JWK formats.\n * - Public Key Derivation: Derive public keys from private keys.\n * - ECDH Shared Secret Computation: Securely derive shared secrets using private and public keys.\n *\n * The methods in this class are asynchronous, returning Promises to accommodate various\n * JavaScript environments.\n *\n * @example\n * ```ts\n * // Key Generation\n * const privateKey = await X25519.generateKey();\n *\n * // Public Key Derivation\n * const publicKey = await X25519.computePublicKey({ key: privateKey });\n * console.log(publicKey === await X25519.getPublicKey({ key: privateKey })); // Output: true\n *\n * // ECDH Shared Secret Computation\n * const sharedSecret = await X25519.sharedSecret({\n * privateKeyA: privateKey,\n * publicKeyB: anotherPublicKey\n * });\n *\n * // Key Conversion\n * const publicKeyBytes = await X25519.publicKeyToBytes({ publicKey });\n * const privateKeyBytes = await X25519.privateKeyToBytes({ privateKey });\n * ```\n */\nexport class X25519 {\n /**\n * Converts a raw private key in bytes to its corresponding JSON Web Key (JWK) format.\n *\n * @remarks\n * This method accepts a private key as a byte array (Uint8Array) for the X25519 elliptic curve\n * and transforms it into a JWK object. The process involves first deriving the public key from\n * the private key, then encoding both the private and public keys into base64url format.\n *\n * The resulting JWK object includes the following properties:\n * - `kty`: Key Type, set to 'OKP' for Octet Key Pair.\n * - `crv`: Curve Name, set to 'X25519'.\n * - `d`: The private key component, base64url-encoded.\n * - `x`: The derived public key, base64url-encoded.\n *\n * This method is useful for converting raw public keys into a standardized\n * JSON format, facilitating their use in cryptographic operations and making\n * them easy to share and store.\n *\n * @example\n * ```ts\n * const privateKeyBytes = new Uint8Array([...]); // Replace with actual private key bytes\n * const privateKey = await X25519.bytesToPrivateKey({ privateKeyBytes });\n * ```\n *\n * @param params - The parameters for the private key conversion.\n * @param params.privateKeyBytes - The raw private key as a Uint8Array.\n *\n * @returns A Promise that resolves to the private key in JWK format.\n */\n public static async bytesToPrivateKey({ privateKeyBytes }: {\n privateKeyBytes: Uint8Array;\n }): Promise<Jwk> {\n // Derive the public key from the private key.\n const publicKeyBytes = x25519.getPublicKey(privateKeyBytes);\n\n // Construct the private key in JWK format.\n const privateKey: Jwk = {\n kty : 'OKP',\n crv : 'X25519',\n d : Convert.uint8Array(privateKeyBytes).toBase64Url(),\n x : Convert.uint8Array(publicKeyBytes).toBase64Url(),\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n return privateKey;\n }\n\n /**\n * Converts a raw public key in bytes to its corresponding JSON Web Key (JWK) format.\n *\n * @remarks\n * This method accepts a public key as a byte array (Uint8Array) for the X25519 elliptic curve\n * and transforms it into a JWK object. The conversion process involves encoding the public\n * key bytes into base64url format.\n *\n * The resulting JWK object includes the following properties:\n * - `kty`: Key Type, set to 'OKP' for Octet Key Pair.\n * - `crv`: Curve Name, set to 'X25519'.\n * - `x`: The public key, base64url-encoded.\n *\n * This method is useful for converting raw public keys into a standardized\n * JSON format, facilitating their use in cryptographic operations and making\n * them easy to share and store.\n *\n * @example\n * ```ts\n * const publicKeyBytes = new Uint8Array([...]); // Replace with actual public key bytes\n * const publicKey = await X25519.bytesToPublicKey({ publicKeyBytes });\n * ```\n *\n * @param params - The parameters for the public key conversion.\n * @param params.publicKeyBytes - The raw public key as a Uint8Array.\n *\n * @returns A Promise that resolves to the public key in JWK format.\n */\n public static async bytesToPublicKey({ publicKeyBytes }: {\n publicKeyBytes: Uint8Array;\n }): Promise<Jwk> {\n // Construct the public key in JWK format.\n const publicKey: Jwk = {\n kty : 'OKP',\n crv : 'X25519',\n x : Convert.uint8Array(publicKeyBytes).toBase64Url(),\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n publicKey.kid = await computeJwkThumbprint({ jwk: publicKey });\n\n return publicKey;\n }\n\n /**\n * Derives the public key in JWK format from a given X25519 private key.\n *\n * @remarks\n * This method takes a private key in JWK format and derives its corresponding public key,\n * also in JWK format. The derivation process involves converting the private key to a\n * raw byte array and then computing the corresponding public key on the Curve25519 curve.\n * The public key is then encoded into base64url format to construct a JWK representation.\n *\n * The process ensures that the derived public key correctly corresponds to the given private key,\n * adhering to the Curve25519 elliptic curve in Twisted Edwards form standards. This method is\n * useful in cryptographic operations where a public key is needed for operations like signature\n * verification, but only the private key is available.\n *\n * @example\n * ```ts\n * const privateKey = { ... }; // A Jwk object representing an X25519 private key\n * const publicKey = await X25519.computePublicKey({ key: privateKey });\n * ```\n *\n * @param params - The parameters for the public key derivation.\n * @param params.key - The private key in JWK format from which to derive the public key.\n *\n * @returns A Promise that resolves to the derived public key in JWK format.\n */\n public static async computePublicKey({ key }:\n ComputePublicKeyParams\n ): Promise<Jwk> {\n // Convert the provided private key to a byte array.\n const privateKeyBytes = await X25519.privateKeyToBytes({ privateKey: key });\n\n // Derive the public key from the private key.\n const publicKeyBytes = x25519.getPublicKey(privateKeyBytes);\n\n // Construct the public key in JWK format.\n const publicKey: Jwk = {\n kty : 'OKP',\n crv : 'X25519',\n x : Convert.uint8Array(publicKeyBytes).toBase64Url()\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n publicKey.kid = await computeJwkThumbprint({ jwk: publicKey });\n\n return publicKey;\n }\n\n /**\n * Generates an X25519 private key in JSON Web Key (JWK) format.\n *\n * @remarks\n * This method creates a new private key suitable for use with the X25519 elliptic curve.\n * The key generation process involves using cryptographically secure random number generation\n * to ensure the uniqueness and security of the key. The resulting private key adheres to the\n * JWK format making it compatible with common cryptographic standards and easy to use in various\n * cryptographic processes.\n *\n * The generated private key in JWK format includes the following components:\n * - `kty`: Key Type, set to 'OKP' for Octet Key Pair.\n * - `crv`: Curve Name, set to 'X25519'.\n * - `d`: The private key component, base64url-encoded.\n * - `x`: The derived public key, base64url-encoded.\n *\n * The key is returned in a format suitable for direct use in key agreement operations.\n *\n * @example\n * ```ts\n * const privateKey = await X25519.generateKey();\n * ```\n *\n * @returns A Promise that resolves to the generated private key in JWK format.\n */\n public static async generateKey(): Promise<Jwk> {\n // Generate a random private key.\n const privateKeyBytes = x25519.utils.randomPrivateKey();\n\n // Convert private key from bytes to JWK format.\n const privateKey = await X25519.bytesToPrivateKey({ privateKeyBytes });\n\n // Compute the JWK thumbprint and set as the key ID.\n privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n return privateKey;\n }\n\n /**\n * Retrieves the public key properties from a given private key in JWK format.\n *\n * @remarks\n * This method extracts the public key portion from an X25519 private key in JWK format. It does\n * so by removing the private key property 'd' and making a shallow copy, effectively yielding the\n * public key. The method sets the 'kid' (key ID) property using the JWK thumbprint if it is not\n * already defined. This approach is used under the assumption that a private key in JWK format\n * always contains the corresponding public key properties.\n *\n * Note: This method offers a significant performance advantage, being about 500 times faster\n * than `computePublicKey()`. However, it does not mathematically validate the private key, nor\n * does it derive the public key from the private key. It simply extracts existing public key\n * properties from the private key object. This makes it suitable for scenarios where speed is\n * critical and the private key's integrity is already assured.\n *\n * @example\n * ```ts\n * const privateKey = { ... }; // A Jwk object representing an X25519 private key\n * const publicKey = await X25519.getPublicKey({ key: privateKey });\n * ```\n *\n * @param params - The parameters for retrieving the public key properties.\n * @param params.key - The private key in JWK format.\n *\n * @returns A Promise that resolves to the public key in JWK format.\n */\n public static async getPublicKey({ key }:\n GetPublicKeyParams\n ): Promise<Jwk> {\n // Verify the provided JWK represents an octet key pair (OKP) X25519 private key.\n if (!(isOkpPrivateJwk(key) && key.crv === 'X25519')) {\n throw new Error(`X25519: The provided key is not an X25519 private JWK.`);\n }\n\n // Remove the private key property ('d') and make a shallow copy of the provided key.\n const { d, ...publicKey } = key;\n\n // If the key ID is undefined, set it to the JWK thumbprint.\n publicKey.kid ??= await computeJwkThumbprint({ jwk: publicKey });\n\n return publicKey;\n }\n\n /**\n * Converts a private key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n *\n * @remarks\n * This method accepts a private key in JWK format and extracts its raw byte representation.\n *\n * This method accepts a public key in JWK format and converts it into its raw binary\n * form. The conversion process involves decoding the 'd' parameter of the JWK\n * from base64url format into a byte array.\n *\n * This conversion is essential for operations that require the private key in its raw\n * binary form, such as certain low-level cryptographic operations or when interfacing\n * with systems and libraries that expect keys in a byte array format.\n *\n * @example\n * ```ts\n * const privateKey = { ... }; // An X25519 private key in JWK format\n * const privateKeyBytes = await X25519.privateKeyToBytes({ privateKey });\n * ```\n *\n * @param params - The parameters for the private key conversion.\n * @param params.privateKey - The private key in JWK format.\n *\n * @returns A Promise that resolves to the private key as a Uint8Array.\n */\n public static async privateKeyToBytes({ privateKey }: {\n privateKey: Jwk;\n }): Promise<Uint8Array> {\n // Verify the provided JWK represents a valid OKP private key.\n if (!isOkpPrivateJwk(privateKey)) {\n throw new Error(`X25519: The provided key is not a valid OKP private key.`);\n }\n\n // Decode the provided private key to bytes.\n const privateKeyBytes = Convert.base64Url(privateKey.d).toUint8Array();\n\n return privateKeyBytes;\n }\n\n /**\n * Converts a public key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n *\n * @remarks\n * This method accepts a public key in JWK format and converts it into its raw binary form.\n * The conversion process involves decoding the 'x' parameter of the JWK (which represent the\n * x coordinate of the elliptic curve point) from base64url format into a byte array.\n *\n * This conversion is essential for operations that require the public key in its raw\n * binary form, such as certain low-level cryptographic operations or when interfacing\n * with systems and libraries that expect keys in a byte array format.\n *\n * @example\n * ```ts\n * const publicKey = { ... }; // An X25519 public key in JWK format\n * const publicKeyBytes = await X25519.publicKeyToBytes({ publicKey });\n * ```\n *\n * @param params - The parameters for the public key conversion.\n * @param params.publicKey - The public key in JWK format.\n *\n * @returns A Promise that resolves to the public key as a Uint8Array.\n */\n public static async publicKeyToBytes({ publicKey }: {\n publicKey: Jwk;\n }): Promise<Uint8Array> {\n // Verify the provided JWK represents a valid OKP public key.\n if (!isOkpPublicJwk(publicKey)) {\n throw new Error(`X25519: The provided key is not a valid OKP public key.`);\n }\n\n // Decode the provided public key to bytes.\n const publicKeyBytes = Convert.base64Url(publicKey.x).toUint8Array();\n\n return publicKeyBytes;\n }\n\n /**\n * Computes an RFC6090-compliant Elliptic Curve Diffie-Hellman (ECDH) shared secret\n * using secp256k1 private and public keys in JSON Web Key (JWK) format.\n *\n * @remarks\n * This method facilitates the ECDH key agreement protocol, which is a method of securely\n * deriving a shared secret between two parties based on their private and public keys.\n * It takes the private key of one party (privateKeyA) and the public key of another\n * party (publicKeyB) to compute a shared secret. The shared secret is derived from the\n * x-coordinate of the elliptic curve point resulting from the multiplication of the\n * public key with the private key.\n *\n * Note: When performing Elliptic Curve Diffie-Hellman (ECDH) key agreement,\n * the resulting shared secret is a point on the elliptic curve, which\n * consists of an x-coordinate and a y-coordinate. With a 256-bit curve like\n * secp256k1, each of these coordinates is 32 bytes (256 bits) long. However,\n * in the ECDH process, it's standard practice to use only the x-coordinate\n * of the shared secret point as the resulting shared key. This is because\n * the y-coordinate does not add to the entropy of the key, and both parties\n * can independently compute the x-coordinate. Consquently, this implementation\n * omits the y-coordinate for simplicity and standard compliance.\n *\n * @example\n * ```ts\n * const privateKeyA = { ... }; // A Jwk object for party A\n * const publicKeyB = { ... }; // A PublicKeyJwk object for party B\n * const sharedSecret = await Secp256k1.sharedSecret({\n * privateKeyA,\n * publicKeyB\n * });\n * ```\n *\n * @param params - The parameters for the shared secret computation.\n * @param params.privateKeyA - The private key in JWK format of one party.\n * @param params.publicKeyB - The public key in JWK format of the other party.\n *\n * @returns A Promise that resolves to the computed shared secret as a Uint8Array.\n */\n public static async sharedSecret({ privateKeyA, publicKeyB }: {\n privateKeyA: Jwk;\n publicKeyB: Jwk;\n }): Promise<Uint8Array> {\n // Ensure that keys from the same key pair are not specified.\n if ('x' in privateKeyA && 'x' in publicKeyB && privateKeyA.x === publicKeyB.x) {\n throw new Error(`X25519: ECDH shared secret cannot be computed from a single key pair's public and private keys.`);\n }\n\n // Convert the provided private and public keys to bytes.\n const privateKeyABytes = await X25519.privateKeyToBytes({ privateKey: privateKeyA });\n const publicKeyBBytes = await X25519.publicKeyToBytes({ publicKey: publicKeyB });\n\n // Compute the shared secret between the public and private keys.\n const sharedSecret = x25519.getSharedSecret(privateKeyABytes, publicKeyBBytes);\n\n return sharedSecret;\n }\n}", "import { exists as aexists, bytes as abytes, output as aoutput } from './_assert.js';\nimport { Input, toBytes, Hash } from './utils.js';\n\n// Poly1305 is a fast and parallel secret-key message-authentication code.\n// https://cr.yp.to/mac.html, https://cr.yp.to/mac/poly1305-20050329.pdf\n// https://datatracker.ietf.org/doc/html/rfc8439\n\n// Based on Public Domain poly1305-donna https://github.com/floodyberry/poly1305-donna\nconst u8to16 = (a: Uint8Array, i: number) => (a[i++] & 0xff) | ((a[i++] & 0xff) << 8);\nclass Poly1305 implements Hash<Poly1305> {\n readonly blockLen = 16;\n readonly outputLen = 16;\n private buffer = new Uint8Array(16);\n private r = new Uint16Array(10);\n private h = new Uint16Array(10);\n private pad = new Uint16Array(8);\n private pos = 0;\n protected finished = false;\n\n constructor(key: Input) {\n key = toBytes(key);\n abytes(key, 32);\n const t0 = u8to16(key, 0);\n const t1 = u8to16(key, 2);\n const t2 = u8to16(key, 4);\n const t3 = u8to16(key, 6);\n const t4 = u8to16(key, 8);\n const t5 = u8to16(key, 10);\n const t6 = u8to16(key, 12);\n const t7 = u8to16(key, 14);\n\n // https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47\n this.r[0] = t0 & 0x1fff;\n this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;\n this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;\n this.r[5] = (t4 >>> 1) & 0x1ffe;\n this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;\n this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n this.r[9] = (t7 >>> 5) & 0x007f;\n for (let i = 0; i < 8; i++) this.pad[i] = u8to16(key, 16 + 2 * i);\n }\n\n private process(data: Uint8Array, offset: number, isLast = false) {\n const hibit = isLast ? 0 : 1 << 11;\n const { h, r } = this;\n const r0 = r[0];\n const r1 = r[1];\n const r2 = r[2];\n const r3 = r[3];\n const r4 = r[4];\n const r5 = r[5];\n const r6 = r[6];\n const r7 = r[7];\n const r8 = r[8];\n const r9 = r[9];\n\n const t0 = u8to16(data, offset + 0);\n const t1 = u8to16(data, offset + 2);\n const t2 = u8to16(data, offset + 4);\n const t3 = u8to16(data, offset + 6);\n const t4 = u8to16(data, offset + 8);\n const t5 = u8to16(data, offset + 10);\n const t6 = u8to16(data, offset + 12);\n const t7 = u8to16(data, offset + 14);\n\n let h0 = h[0] + (t0 & 0x1fff);\n let h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 0x1fff);\n let h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 0x1fff);\n let h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 0x1fff);\n let h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 0x1fff);\n let h5 = h[5] + ((t4 >>> 1) & 0x1fff);\n let h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 0x1fff);\n let h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 0x1fff);\n let h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 0x1fff);\n let h9 = h[9] + ((t7 >>> 5) | hibit);\n\n let c = 0;\n\n let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6);\n c = d0 >>> 13;\n d0 &= 0x1fff;\n d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1);\n c += d0 >>> 13;\n d0 &= 0x1fff;\n\n let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7);\n c = d1 >>> 13;\n d1 &= 0x1fff;\n d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2);\n c += d1 >>> 13;\n d1 &= 0x1fff;\n\n let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);\n c = d2 >>> 13;\n d2 &= 0x1fff;\n d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3);\n c += d2 >>> 13;\n d2 &= 0x1fff;\n\n let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);\n c = d3 >>> 13;\n d3 &= 0x1fff;\n d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4);\n c += d3 >>> 13;\n d3 &= 0x1fff;\n\n let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;\n c = d4 >>> 13;\n d4 &= 0x1fff;\n d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5);\n c += d4 >>> 13;\n d4 &= 0x1fff;\n\n let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;\n c = d5 >>> 13;\n d5 &= 0x1fff;\n d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6);\n c += d5 >>> 13;\n d5 &= 0x1fff;\n\n let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;\n c = d6 >>> 13;\n d6 &= 0x1fff;\n d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);\n c += d6 >>> 13;\n d6 &= 0x1fff;\n\n let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;\n c = d7 >>> 13;\n d7 &= 0x1fff;\n d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);\n c += d7 >>> 13;\n d7 &= 0x1fff;\n\n let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;\n c = d8 >>> 13;\n d8 &= 0x1fff;\n d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);\n c += d8 >>> 13;\n d8 &= 0x1fff;\n\n let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;\n c = d9 >>> 13;\n d9 &= 0x1fff;\n d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;\n c += d9 >>> 13;\n d9 &= 0x1fff;\n\n c = ((c << 2) + c) | 0;\n c = (c + d0) | 0;\n d0 = c & 0x1fff;\n c = c >>> 13;\n d1 += c;\n\n h[0] = d0;\n h[1] = d1;\n h[2] = d2;\n h[3] = d3;\n h[4] = d4;\n h[5] = d5;\n h[6] = d6;\n h[7] = d7;\n h[8] = d8;\n h[9] = d9;\n }\n\n private finalize() {\n const { h, pad } = this;\n const g = new Uint16Array(10);\n let c = h[1] >>> 13;\n h[1] &= 0x1fff;\n for (let i = 2; i < 10; i++) {\n h[i] += c;\n c = h[i] >>> 13;\n h[i] &= 0x1fff;\n }\n h[0] += c * 5;\n c = h[0] >>> 13;\n h[0] &= 0x1fff;\n h[1] += c;\n c = h[1] >>> 13;\n h[1] &= 0x1fff;\n h[2] += c;\n\n g[0] = h[0] + 5;\n c = g[0] >>> 13;\n g[0] &= 0x1fff;\n for (let i = 1; i < 10; i++) {\n g[i] = h[i] + c;\n c = g[i] >>> 13;\n g[i] &= 0x1fff;\n }\n g[9] -= 1 << 13;\n\n let mask = (c ^ 1) - 1;\n for (let i = 0; i < 10; i++) g[i] &= mask;\n mask = ~mask;\n for (let i = 0; i < 10; i++) h[i] = (h[i] & mask) | g[i];\n h[0] = (h[0] | (h[1] << 13)) & 0xffff;\n h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 0xffff;\n h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 0xffff;\n h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 0xffff;\n h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 0xffff;\n h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 0xffff;\n h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 0xffff;\n h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 0xffff;\n\n let f = h[0] + pad[0];\n h[0] = f & 0xffff;\n for (let i = 1; i < 8; i++) {\n f = (((h[i] + pad[i]) | 0) + (f >>> 16)) | 0;\n h[i] = f & 0xffff;\n }\n }\n update(data: Input): this {\n aexists(this);\n const { buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input\n if (take === blockLen) {\n for (; blockLen <= len - pos; pos += blockLen) this.process(data, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(buffer, 0, false);\n this.pos = 0;\n }\n }\n return this;\n }\n destroy() {\n this.h.fill(0);\n this.r.fill(0);\n this.buffer.fill(0);\n this.pad.fill(0);\n }\n digestInto(out: Uint8Array) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const { buffer, h } = this;\n let { pos } = this;\n if (pos) {\n buffer[pos++] = 1;\n // buffer.subarray(pos).fill(0);\n for (; pos < 16; pos++) buffer[pos] = 0;\n this.process(buffer, 0, true);\n }\n this.finalize();\n let opos = 0;\n for (let i = 0; i < 8; i++) {\n out[opos++] = h[i] >>> 0;\n out[opos++] = h[i] >>> 8;\n }\n return out;\n }\n digest(): Uint8Array {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n}\n\nexport type CHash = ReturnType<typeof wrapConstructorWithKey>;\nexport function wrapConstructorWithKey<H extends Hash<H>>(hashCons: (key: Input) => Hash<H>) {\n const hashC = (msg: Input, key: Input): Uint8Array => hashCons(key).update(toBytes(msg)).digest();\n const tmp = hashCons(new Uint8Array(32));\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (key: Input) => hashCons(key);\n return hashC;\n}\n\nexport const poly1305 = wrapConstructorWithKey((key) => new Poly1305(key));\n", "// Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.\nimport { number as anumber, bytes as abytes, bool as abool } from './_assert.js';\nimport { XorStream, checkOpts, u32 } from './utils.js';\n\n/*\nRFC8439 requires multi-step cipher stream, where\nauthKey starts with counter: 0, actual msg with counter: 1.\n\nFor this, we need a way to re-use nonce / counter:\n\n const counter = new Uint8Array(4);\n chacha(..., counter, ...); // counter is now 1\n chacha(..., counter, ...); // counter is now 2\n\nThis is complicated:\n\n- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB\n- Original papers don't allow mutating counters\n- Counter overflow is undefined [^1]\n- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it\n- Caveat: Cannot be re-used through all cases:\n- * chacha has (counter | nonce)\n- * xchacha has (nonce16 | counter | nonce16)\n- Idea B: separate nonce / counter and provide separate API for counter re-use\n- Caveat: there are different counter sizes depending on an algorithm.\n- salsa & chacha also differ in structures of key & sigma:\n salsa20: s[0] | k(4) | s[1] | nonce(2) | ctr(2) | s[2] | k(4) | s[3]\n chacha: s(4) | k(8) | ctr(1) | nonce(3)\n chacha20orig: s(4) | k(8) | ctr(2) | nonce(2)\n- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`\n- Caveat: we can't re-use counter array\n\nxchacha [^2] uses the subkey and remaining 8 byte nonce with ChaCha20 as normal\n(prefixed by 4 NUL bytes, since [RFC8439] specifies a 12-byte nonce).\n\n[^1]: https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/\n[^2]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2\n*/\n\n// We can't make top-level var depend on utils.utf8ToBytes\n// because it's not present in all envs. Creating a similar fn here\nconst _utf8ToBytes = (str: string) => Uint8Array.from(str.split('').map((c) => c.charCodeAt(0)));\nconst sigma16 = _utf8ToBytes('expand 16-byte k');\nconst sigma32 = _utf8ToBytes('expand 32-byte k');\nconst sigma16_32 = u32(sigma16);\nconst sigma32_32 = u32(sigma32);\nexport const sigma = sigma32_32.slice();\n\nexport function rotl(a: number, b: number): number {\n return (a << b) | (a >>> (32 - b));\n}\n\nexport type CipherCoreFn = (\n sigma: Uint32Array,\n key: Uint32Array,\n nonce: Uint32Array,\n output: Uint32Array,\n counter: number,\n rounds?: number\n) => void;\n\nexport type ExtendNonceFn = (\n sigma: Uint32Array,\n key: Uint32Array,\n input: Uint32Array,\n output: Uint32Array\n) => void;\n\nexport type CipherOpts = {\n allowShortKeys?: boolean; // Original salsa / chacha allow 16-byte keys\n extendNonceFn?: ExtendNonceFn;\n counterLength?: number;\n counterRight?: boolean; // right: nonce|counter; left: counter|nonce\n rounds?: number;\n};\n\n// Is byte array aligned to 4 byte offset (u32)?\nfunction isAligned32(b: Uint8Array) {\n return b.byteOffset % 4 === 0;\n}\n\n// Salsa and Chacha block length is always 512-bit\nconst BLOCK_LEN = 64;\nconst BLOCK_LEN32 = 16;\n\n// new Uint32Array([2**32]) // => Uint32Array(1) [ 0 ]\n// new Uint32Array([2**32-1]) // => Uint32Array(1) [ 4294967295 ]\nconst MAX_COUNTER = 2 ** 32 - 1;\n\nconst U32_EMPTY = new Uint32Array();\nfunction runCipher(\n core: CipherCoreFn,\n sigma: Uint32Array,\n key: Uint32Array,\n nonce: Uint32Array,\n data: Uint8Array,\n output: Uint8Array,\n counter: number,\n rounds: number\n): void {\n const len = data.length;\n const block = new Uint8Array(BLOCK_LEN);\n const b32 = u32(block);\n // Make sure that buffers aligned to 4 bytes\n const isAligned = isAligned32(data) && isAligned32(output);\n const d32 = isAligned ? u32(data) : U32_EMPTY;\n const o32 = isAligned ? u32(output) : U32_EMPTY;\n for (let pos = 0; pos < len; counter++) {\n core(sigma, key, nonce, b32, counter, rounds);\n if (counter >= MAX_COUNTER) throw new Error('arx: counter overflow');\n const take = Math.min(BLOCK_LEN, len - pos);\n // aligned to 4 bytes\n if (isAligned && take === BLOCK_LEN) {\n const pos32 = pos / 4;\n if (pos % 4 !== 0) throw new Error('arx: invalid block position');\n for (let j = 0, posj: number; j < BLOCK_LEN32; j++) {\n posj = pos32 + j;\n o32[posj] = d32[posj] ^ b32[j];\n }\n pos += BLOCK_LEN;\n continue;\n }\n for (let j = 0, posj; j < take; j++) {\n posj = pos + j;\n output[posj] = data[posj] ^ block[j];\n }\n pos += take;\n }\n}\n\nexport function createCipher(core: CipherCoreFn, opts: CipherOpts): XorStream {\n const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts(\n { allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 },\n opts\n );\n if (typeof core !== 'function') throw new Error('core must be a function');\n anumber(counterLength);\n anumber(rounds);\n abool(counterRight);\n abool(allowShortKeys);\n return (\n key: Uint8Array,\n nonce: Uint8Array,\n data: Uint8Array,\n output?: Uint8Array,\n counter = 0\n ): Uint8Array => {\n abytes(key);\n abytes(nonce);\n abytes(data);\n const len = data.length;\n if (!output) output = new Uint8Array(len);\n abytes(output);\n anumber(counter);\n if (counter < 0 || counter >= MAX_COUNTER) throw new Error('arx: counter overflow');\n if (output.length < len)\n throw new Error(`arx: output (${output.length}) is shorter than data (${len})`);\n const toClean = [];\n\n // Key & sigma\n // key=16 -> sigma16, k=key|key\n // key=32 -> sigma32, k=key\n let l = key.length,\n k: Uint8Array,\n sigma: Uint32Array;\n if (l === 32) {\n k = key.slice();\n toClean.push(k);\n sigma = sigma32_32;\n } else if (l === 16 && allowShortKeys) {\n k = new Uint8Array(32);\n k.set(key);\n k.set(key, 16);\n sigma = sigma16_32;\n toClean.push(k);\n } else {\n throw new Error(`arx: invalid 32-byte key, got length=${l}`);\n }\n\n // Nonce\n // salsa20: 8 (8-byte counter)\n // chacha20orig: 8 (8-byte counter)\n // chacha20: 12 (4-byte counter)\n // xsalsa20: 24 (16 -> hsalsa, 8 -> old nonce)\n // xchacha20: 24 (16 -> hchacha, 8 -> old nonce)\n // Align nonce to 4 bytes\n if (!isAligned32(nonce)) {\n nonce = nonce.slice();\n toClean.push(nonce);\n }\n\n const k32 = u32(k);\n // hsalsa & hchacha: handle extended nonce\n if (extendNonceFn) {\n if (nonce.length !== 24) throw new Error(`arx: extended nonce must be 24 bytes`);\n extendNonceFn(sigma, k32, u32(nonce.subarray(0, 16)), k32);\n nonce = nonce.subarray(16);\n }\n\n // Handle nonce counter\n const nonceNcLen = 16 - counterLength;\n if (nonceNcLen !== nonce.length)\n throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);\n\n // Pad counter when nonce is 64 bit\n if (nonceNcLen !== 12) {\n const nc = new Uint8Array(12);\n nc.set(nonce, counterRight ? 0 : 12 - nonce.length);\n nonce = nc;\n toClean.push(nonce);\n }\n const n32 = u32(nonce);\n runCipher(core, sigma, k32, n32, data, output, counter, rounds);\n while (toClean.length > 0) toClean.pop()!.fill(0);\n return output;\n };\n}\n", "// prettier-ignore\nimport {\n wrapCipher, CipherWithOutput, XorStream, createView, equalBytes, setBigUint64,\n} from './utils.js';\nimport { poly1305 } from './_poly1305.js';\nimport { createCipher, rotl } from './_arx.js';\nimport { bytes as abytes } from './_assert.js';\n\n// ChaCha20 stream cipher was released in 2008. ChaCha aims to increase\n// the diffusion per round, but had slightly less cryptanalysis.\n// https://cr.yp.to/chacha.html, http://cr.yp.to/chacha/chacha-20080128.pdf\n\n/**\n * ChaCha core function.\n */\n// prettier-ignore\nfunction chachaCore(\n s: Uint32Array, k: Uint32Array, n: Uint32Array, out: Uint32Array, cnt: number, rounds = 20\n): void {\n let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], // \"expa\" \"nd 3\" \"2-by\" \"te k\"\n y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], // Key Key Key Key\n y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], // Key Key Key Key\n y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; // Counter Counter\tNonce Nonce\n // Save state to temporary variables\n let x00 = y00, x01 = y01, x02 = y02, x03 = y03,\n x04 = y04, x05 = y05, x06 = y06, x07 = y07,\n x08 = y08, x09 = y09, x10 = y10, x11 = y11,\n x12 = y12, x13 = y13, x14 = y14, x15 = y15;\n for (let r = 0; r < rounds; r += 2) {\n x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 16);\n x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 12);\n x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 8);\n x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 7);\n\n x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 16);\n x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 12);\n x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 8);\n x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 7);\n\n x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 16);\n x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 12);\n x02 = (x02 + x06) | 0; x14 = rotl(x14 ^x02, 8);\n x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 7);\n\n x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 16);\n x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 12);\n x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 8)\n x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 7);\n\n x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 16);\n x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 12);\n x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 8);\n x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 7);\n\n x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 16);\n x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 12);\n x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 8);\n x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 7);\n\n x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 16);\n x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 12);\n x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 8);\n x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 7);\n\n x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 16)\n x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 12);\n x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 8);\n x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 7);\n }\n // Write output\n let oi = 0;\n out[oi++] = (y00 + x00) | 0; out[oi++] = (y01 + x01) | 0;\n out[oi++] = (y02 + x02) | 0; out[oi++] = (y03 + x03) | 0;\n out[oi++] = (y04 + x04) | 0; out[oi++] = (y05 + x05) | 0;\n out[oi++] = (y06 + x06) | 0; out[oi++] = (y07 + x07) | 0;\n out[oi++] = (y08 + x08) | 0; out[oi++] = (y09 + x09) | 0;\n out[oi++] = (y10 + x10) | 0; out[oi++] = (y11 + x11) | 0;\n out[oi++] = (y12 + x12) | 0; out[oi++] = (y13 + x13) | 0;\n out[oi++] = (y14 + x14) | 0; out[oi++] = (y15 + x15) | 0;\n}\n/**\n * hchacha helper method, used primarily in xchacha, to hash\n * key and nonce into key' and nonce'.\n * Same as chachaCore, but there doesn't seem to be a way to move the block\n * out without 25% performance hit.\n */\n// prettier-ignore\nexport function hchacha(\n s: Uint32Array, k: Uint32Array, i: Uint32Array, o32: Uint32Array\n) {\n let x00 = s[0], x01 = s[1], x02 = s[2], x03 = s[3],\n x04 = k[0], x05 = k[1], x06 = k[2], x07 = k[3],\n x08 = k[4], x09 = k[5], x10 = k[6], x11 = k[7],\n x12 = i[0], x13 = i[1], x14 = i[2], x15 = i[3];\n for (let r = 0; r < 20; r += 2) {\n x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 16);\n x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 12);\n x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 8);\n x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 7);\n\n x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 16);\n x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 12);\n x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 8);\n x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 7);\n\n x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 16);\n x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 12);\n x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 8);\n x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 7);\n\n x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 16);\n x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 12);\n x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 8)\n x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 7);\n\n x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 16);\n x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 12);\n x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 8);\n x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 7);\n\n x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 16);\n x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 12);\n x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 8);\n x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 7);\n\n x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 16);\n x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 12);\n x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 8);\n x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 7);\n\n x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 16)\n x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 12);\n x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 8);\n x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 7);\n }\n let oi = 0;\n o32[oi++] = x00; o32[oi++] = x01;\n o32[oi++] = x02; o32[oi++] = x03;\n o32[oi++] = x12; o32[oi++] = x13;\n o32[oi++] = x14; o32[oi++] = x15;\n}\n/**\n * Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter.\n */\nexport const chacha20orig = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 8,\n allowShortKeys: true,\n});\n/**\n * ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.\n * With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance.\n */\nexport const chacha20 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n allowShortKeys: false,\n});\n\n/**\n * XChaCha eXtended-nonce ChaCha. 24-byte nonce.\n * With 24-byte nonce, it's safe to use fill it with random (CSPRNG).\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha\n */\nexport const xchacha20 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 8,\n extendNonceFn: hchacha,\n allowShortKeys: false,\n});\n\n/**\n * Reduced 8-round chacha, described in original paper.\n */\nexport const chacha8 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n rounds: 8,\n});\n\n/**\n * Reduced 12-round chacha, described in original paper.\n */\nexport const chacha12 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n rounds: 12,\n});\n\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\n// Pad to digest size with zeros\nconst updatePadded = (h: ReturnType<typeof poly1305.create>, msg: Uint8Array) => {\n h.update(msg);\n const left = msg.length % 16;\n if (left) h.update(ZEROS16.subarray(left));\n};\n\nconst ZEROS32 = /* @__PURE__ */ new Uint8Array(32);\nfunction computeTag(\n fn: XorStream,\n key: Uint8Array,\n nonce: Uint8Array,\n data: Uint8Array,\n AAD?: Uint8Array\n): Uint8Array {\n const authKey = fn(key, nonce, ZEROS32);\n const h = poly1305.create(authKey);\n if (AAD) updatePadded(h, AAD);\n updatePadded(h, data);\n const num = new Uint8Array(16);\n const view = createView(num);\n setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true);\n setBigUint64(view, 8, BigInt(data.length), true);\n h.update(num);\n const res = h.digest();\n authKey.fill(0);\n return res;\n}\n\n/**\n * AEAD algorithm from RFC 8439.\n * Salsa20 and chacha (RFC 8439) use poly1305 differently.\n * We could have composed them similar to:\n * https://github.com/paulmillr/scure-base/blob/b266c73dde977b1dd7ef40ef7a23cc15aab526b3/index.ts#L250\n * But it's hard because of authKey:\n * In salsa20, authKey changes position in salsa stream.\n * In chacha, authKey can't be computed inside computeTag, it modifies the counter.\n */\nexport const _poly1305_aead =\n (xorStream: XorStream) =>\n (key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array): CipherWithOutput => {\n const tagLength = 16;\n abytes(key, 32);\n abytes(nonce);\n return {\n encrypt: (plaintext: Uint8Array, output?: Uint8Array) => {\n const plength = plaintext.length;\n const clength = plength + tagLength;\n if (output) {\n abytes(output, clength);\n } else {\n output = new Uint8Array(clength);\n }\n xorStream(key, nonce, plaintext, output, 1);\n const tag = computeTag(xorStream, key, nonce, output.subarray(0, -tagLength), AAD);\n output.set(tag, plength); // append tag\n return output;\n },\n decrypt: (ciphertext: Uint8Array, output?: Uint8Array) => {\n const clength = ciphertext.length;\n const plength = clength - tagLength;\n if (clength < tagLength)\n throw new Error(`encrypted data must be at least ${tagLength} bytes`);\n if (output) {\n abytes(output, plength);\n } else {\n output = new Uint8Array(plength);\n }\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = computeTag(xorStream, key, nonce, data, AAD);\n if (!equalBytes(passedTag, tag)) throw new Error('invalid tag');\n xorStream(key, nonce, data, output, 1);\n return output;\n },\n };\n };\n\n/**\n * ChaCha20-Poly1305 from RFC 8439.\n * With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance.\n */\nexport const chacha20poly1305 = /* @__PURE__ */ wrapCipher(\n { blockSize: 64, nonceLength: 12, tagLength: 16 },\n _poly1305_aead(chacha20)\n);\n/**\n * XChaCha20-Poly1305 extended-nonce chacha.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha\n * With 24-byte nonce, it's safe to use fill it with random (CSPRNG).\n */\nexport const xchacha20poly1305 = /* @__PURE__ */ wrapCipher(\n { blockSize: 64, nonceLength: 24, tagLength: 16 },\n _poly1305_aead(xchacha20)\n);\n", "import { Convert } from '@enbox/common';\nimport { getWebcryptoSubtle } from '@noble/ciphers/webcrypto';\nimport { xchacha20 } from '@noble/ciphers/chacha';\n\nimport type { Jwk } from '../jose/jwk.js';\n\nimport { computeJwkThumbprint, isOctPrivateJwk } from '../jose/jwk.js';\n\n/**\n * The `XChaCha20` class provides a comprehensive suite of utilities for cryptographic operations\n * using the XChaCha20 symmetric encryption algorithm. This class includes methods for key\n * generation, encryption, decryption, and conversions between raw byte arrays and JSON Web Key\n * (JWK) formats. XChaCha20 is an extended nonce variant of ChaCha20, a stream cipher designed for\n * high-speed encryption with substantial security margins.\n *\n * The XChaCha20 algorithm is particularly well-suited for encrypting large volumes of data or\n * data streams, especially where random access is required. The class adheres to standard\n * cryptographic practices, ensuring robustness and security in its implementations.\n *\n * Key Features:\n * - Key Generation: Generate XChaCha20 symmetric keys in JWK format.\n * - Key Conversion: Transform keys between raw byte arrays and JWK formats.\n * - Encryption: Encrypt data using XChaCha20 with the provided symmetric key.\n * - Decryption: Decrypt data encrypted with XChaCha20 using the corresponding symmetric key.\n *\n * The methods in this class are asynchronous, returning Promises to accommodate various\n * JavaScript environments.\n *\n * @example\n * ```ts\n * // Key Generation\n * const privateKey = await XChaCha20.generateKey();\n *\n * // Encryption\n * const data = new TextEncoder().encode('Messsage');\n * const nonce = utils.randomBytes(24); // 24-byte nonce for XChaCha20\n * const encryptedData = await XChaCha20.encrypt({\n * data,\n * nonce,\n * key: privateKey\n * });\n *\n * // Decryption\n * const decryptedData = await XChaCha20.decrypt({\n * data: encryptedData,\n * nonce,\n * key: privateKey\n * });\n *\n * // Key Conversion\n * const privateKeyBytes = await XChaCha20.privateKeyToBytes({ privateKey });\n * ```\n */\nexport class XChaCha20 {\n /**\n * Converts a raw private key in bytes to its corresponding JSON Web Key (JWK) format.\n *\n * @remarks\n * This method takes a symmetric key represented as a byte array (Uint8Array) and\n * converts it into a JWK object for use with the XChaCha20 symmetric encryption algorithm. The\n * conversion process involves encoding the key into base64url format and setting the appropriate\n * JWK parameters.\n *\n * The resulting JWK object includes the following properties:\n * - `kty`: Key Type, set to 'oct' for Octet Sequence (representing a symmetric key).\n * - `k`: The symmetric key, base64url-encoded.\n * - `kid`: Key ID, generated based on the JWK thumbprint.\n *\n * @example\n * ```ts\n * const privateKeyBytes = new Uint8Array([...]); // Replace with actual symmetric key bytes\n * const privateKey = await XChaCha20.bytesToPrivateKey({ privateKeyBytes });\n * ```\n *\n * @param params - The parameters for the symmetric key conversion.\n * @param params.privateKeyBytes - The raw symmetric key as a Uint8Array.\n *\n * @returns A Promise that resolves to the symmetric key in JWK format.\n */\n public static async bytesToPrivateKey({ privateKeyBytes }: {\n privateKeyBytes: Uint8Array;\n }): Promise<Jwk> {\n // Construct the private key in JWK format.\n const privateKey: Jwk = {\n k : Convert.uint8Array(privateKeyBytes).toBase64Url(),\n kty : 'oct'\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n return privateKey;\n }\n\n /**\n * Decrypts the provided data using XChaCha20.\n *\n * @remarks\n * This method performs XChaCha20 decryption on the given encrypted data using the specified key\n * and nonce. The nonce should be the same as used in the encryption process and must be 24 bytes\n * long. The method returns the decrypted data as a Uint8Array.\n *\n * @example\n * ```ts\n * const encryptedData = new Uint8Array([...]); // Encrypted data\n * const nonce = new Uint8Array(24); // 24-byte nonce used during encryption\n * const key = { ... }; // A Jwk object representing the XChaCha20 key\n * const decryptedData = await XChaCha20.decrypt({\n * data: encryptedData,\n * nonce,\n * key\n * });\n * ```\n *\n * @param params - The parameters for the decryption operation.\n * @param params.data - The encrypted data to decrypt, represented as a Uint8Array.\n * @param params.key - The key to use for decryption, represented in JWK format.\n * @param params.nonce - The nonce used during the encryption process.\n *\n * @returns A Promise that resolves to the decrypted data as a Uint8Array.\n */\n public static async decrypt({ data, key, nonce }: {\n data: Uint8Array;\n key: Jwk;\n nonce: Uint8Array;\n }): Promise<Uint8Array> {\n // Convert the private key from JWK format to bytes.\n const privateKeyBytes = await XChaCha20.privateKeyToBytes({ privateKey: key });\n\n const ciphertext = xchacha20(privateKeyBytes, nonce, data);\n\n return ciphertext;\n }\n\n /**\n * Encrypts the provided data using XChaCha20.\n *\n * @remarks\n * This method performs XChaCha20 encryption on the given data using the specified key and nonce.\n * The nonce must be 24 bytes long, ensuring a high level of security through a vast nonce space,\n * reducing the risks associated with nonce reuse. The method returns the encrypted data as a\n * Uint8Array.\n *\n * @example\n * ```ts\n * const data = new TextEncoder().encode('Messsage');\n * const nonce = utils.randomBytes(24); // 24-byte nonce for XChaCha20\n * const key = { ... }; // A Jwk object representing an XChaCha20 key\n * const encryptedData = await XChaCha20.encrypt({\n * data,\n * nonce,\n * key\n * });\n * ```\n *\n * @param params - The parameters for the encryption operation.\n * @param params.data - The data to encrypt, represented as a Uint8Array.\n * @param params.key - The key to use for encryption, represented in JWK format.\n * @param params.nonce - A 24-byte nonce for the encryption process.\n *\n * @returns A Promise that resolves to the encrypted data as a Uint8Array.\n */\n public static async encrypt({ data, key, nonce }: {\n data: Uint8Array;\n key: Jwk;\n nonce: Uint8Array;\n }): Promise<Uint8Array> {\n // Convert the private key from JWK format to bytes.\n const privateKeyBytes = await XChaCha20.privateKeyToBytes({ privateKey: key });\n\n const plaintext = xchacha20(privateKeyBytes, nonce, data);\n\n return plaintext;\n }\n\n /**\n * Generates a symmetric key for XChaCha20 in JSON Web Key (JWK) format.\n *\n * @remarks\n * This method creates a new symmetric key suitable for use with the XChaCha20 encryption\n * algorithm. The key is generated using cryptographically secure random number generation\n * to ensure its uniqueness and security. The XChaCha20 algorithm requires a 256-bit key\n * (32 bytes), and this method adheres to that specification.\n *\n * Key components included in the JWK:\n * - `kty`: Key Type, set to 'oct' for Octet Sequence.\n * - `k`: The symmetric key component, base64url-encoded.\n * - `kid`: Key ID, generated based on the JWK thumbprint.\n *\n * @example\n * ```ts\n * const privateKey = await XChaCha20.generateKey();\n * ```\n *\n * @returns A Promise that resolves to the generated symmetric key in JWK format.\n */\n public static async generateKey(): Promise<Jwk> {\n // Get the Web Crypto API interface.\n const webCrypto = getWebcryptoSubtle();\n\n // Generate a random private key.\n // See https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#usage_notes for\n // an explanation for why Web Crypto generateKey() is used instead of getRandomValues().\n const webCryptoKey = await webCrypto.generateKey( { name: 'AES-CTR', length: 256 }, true, ['encrypt']);\n\n // Export the private key in JWK format.\n const { alg, ext, key_ops, ...privateKey } = await webCrypto.exportKey('jwk', webCryptoKey);\n\n // Compute the JWK thumbprint and set as the key ID.\n privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n return privateKey;\n }\n\n /**\n * Converts a private key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n *\n * @remarks\n * This method takes a symmetric key in JWK format and extracts its raw byte representation.\n * It decodes the 'k' parameter of the JWK value, which represents the symmetric key in base64url\n * encoding, into a byte array.\n *\n * @example\n * ```ts\n * const privateKey = { ... }; // A symmetric key in JWK format\n * const privateKeyBytes = await XChaCha20.privateKeyToBytes({ privateKey });\n * ```\n *\n * @param params - The parameters for the symmetric key conversion.\n * @param params.privateKey - The symmetric key in JWK format.\n *\n * @returns A Promise that resolves to the symmetric key as a Uint8Array.\n */\n public static async privateKeyToBytes({ privateKey }: {\n privateKey: Jwk;\n }): Promise<Uint8Array> {\n // Verify the provided JWK represents a valid oct private key.\n if (!isOctPrivateJwk(privateKey)) {\n throw new Error(`XChaCha20: The provided key is not a valid oct private key.`);\n }\n\n // Decode the provided private key to bytes.\n const privateKeyBytes = Convert.base64Url(privateKey.k).toUint8Array();\n\n return privateKeyBytes;\n }\n}", "import { Convert } from '@enbox/common';\nimport { getWebcryptoSubtle } from '@noble/ciphers/webcrypto';\nimport { xchacha20poly1305 } from '@noble/ciphers/chacha';\n\nimport type { Jwk } from '../jose/jwk.js';\n\nimport { computeJwkThumbprint, isOctPrivateJwk } from '../jose/jwk.js';\n\n/**\n * Constant defining the length of the authentication tag in bytes for XChaCha20-Poly1305.\n *\n * @remarks\n * The `POLY1305_TAG_LENGTH` is set to 16 bytes (128 bits), which is the standard size for the\n * Poly1305 authentication tag in XChaCha20-Poly1305 encryption. This tag length ensures\n * a strong level of security for message authentication, verifying the integrity and\n * authenticity of the data during decryption.\n */\nexport const POLY1305_TAG_LENGTH = 16;\n\n/**\n * The `XChaCha20Poly1305` class provides a suite of utilities for cryptographic operations\n * using the XChaCha20-Poly1305 algorithm, a combination of the XChaCha20 stream cipher and the\n * Poly1305 message authentication code (MAC). This class encompasses methods for key generation,\n * encryption, decryption, and conversions between raw byte arrays and JSON Web Key (JWK) formats.\n *\n * XChaCha20-Poly1305 is renowned for its high security and efficiency, especially in scenarios\n * involving large data volumes or where data integrity and confidentiality are paramount. The\n * extended nonce size of XChaCha20 reduces the risks of nonce reuse, while Poly1305 provides\n * a strong MAC ensuring data integrity.\n *\n * Key Features:\n * - Key Generation: Generate XChaCha20-Poly1305 symmetric keys in JWK format.\n * - Key Conversion: Transform keys between raw byte arrays and JWK formats.\n * - Encryption: Encrypt data using XChaCha20-Poly1305, returning both ciphertext and MAC tag.\n * - Decryption: Decrypt data and verify integrity using the XChaCha20-Poly1305 algorithm.\n *\n * The methods in this class are asynchronous, returning Promises to accommodate various\n * JavaScript environments.\n *\n * @example\n * ```ts\n * // Key Generation\n * const privateKey = await XChaCha20Poly1305.generateKey();\n *\n * // Encryption\n * const data = new TextEncoder().encode('Messsage');\n * const nonce = utils.randomBytes(24); // 24-byte nonce\n * const additionalData = new TextEncoder().encode('Associated data');\n * const { ciphertext, tag } = await XChaCha20Poly1305.encrypt({\n * data,\n * nonce,\n * additionalData,\n * key: privateKey\n * });\n *\n * // Decryption\n * const decryptedData = await XChaCha20Poly1305.decrypt({\n * data: ciphertext,\n * nonce,\n * tag,\n * additionalData,\n * key: privateKey\n * });\n *\n * // Key Conversion\n * const privateKeyBytes = await XChaCha20Poly1305.privateKeyToBytes({ privateKey });\n * ```\n */\nexport class XChaCha20Poly1305 {\n /**\n * Converts a raw private key in bytes to its corresponding JSON Web Key (JWK) format.\n *\n * @remarks\n * This method takes a symmetric key represented as a byte array (Uint8Array) and converts it into\n * a JWK object for use with the XChaCha20-Poly1305 algorithm. The process involves encoding the\n * key into base64url format and setting the appropriate JWK parameters.\n *\n * The resulting JWK object includes the following properties:\n * - `kty`: Key Type, set to 'oct' for Octet Sequence (representing a symmetric key).\n * - `k`: The symmetric key, base64url-encoded.\n * - `kid`: Key ID, generated based on the JWK thumbprint.\n *\n * @example\n * ```ts\n * const privateKeyBytes = new Uint8Array([...]); // Replace with actual symmetric key bytes\n * const privateKey = await XChaCha20Poly1305.bytesToPrivateKey({ privateKeyBytes });\n * ```\n *\n * @param params - The parameters for the symmetric key conversion.\n * @param params.privateKeyBytes - The raw symmetric key as a Uint8Array.\n *\n * @returns A Promise that resolves to the symmetric key in JWK format.\n */\n public static async bytesToPrivateKey({ privateKeyBytes }: {\n privateKeyBytes: Uint8Array;\n }): Promise<Jwk> {\n // Construct the private key in JWK format.\n const privateKey: Jwk = {\n k : Convert.uint8Array(privateKeyBytes).toBase64Url(),\n kty : 'oct'\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n return privateKey;\n }\n\n /**\n * Decrypts the provided data using XChaCha20-Poly1305.\n *\n * @remarks\n * This method performs XChaCha20-Poly1305 decryption on the given encrypted data using the\n * specified key, nonce, and authentication tag. It supports optional additional authenticated\n * data (AAD) for enhanced security. The nonce must be 24 bytes long, consistent with XChaCha20's\n * specifications.\n *\n * @example\n * ```ts\n * const encryptedData = new Uint8Array([...]); // Encrypted data\n * const nonce = new Uint8Array(24); // 24-byte nonce\n * const additionalData = new Uint8Array([...]); // Optional AAD\n * const key = { ... }; // A Jwk object representing the XChaCha20-Poly1305 key\n * const decryptedData = await XChaCha20Poly1305.decrypt({\n * data: encryptedData,\n * nonce,\n * additionalData,\n * key\n * });\n * ```\n *\n * @param params - The parameters for the decryption operation.\n * @param params.data - The encrypted data to decrypt including the authentication tag,\n * represented as a Uint8Array.\n * @param params.key - The key to use for decryption, represented in JWK format.\n * @param params.nonce - The nonce used during the encryption process.\n * @param params.additionalData - Optional additional authenticated data.\n *\n * @returns A Promise that resolves to the decrypted data as a Uint8Array.\n */\n public static async decrypt({ data, key, nonce, additionalData }: {\n additionalData?: Uint8Array;\n data: Uint8Array;\n key: Jwk;\n nonce: Uint8Array;\n }): Promise<Uint8Array> {\n // Convert the private key from JWK format to bytes.\n const privateKeyBytes = await XChaCha20Poly1305.privateKeyToBytes({ privateKey: key });\n\n return XChaCha20Poly1305.decryptRaw({ data, keyBytes: privateKeyBytes, nonce, additionalData });\n }\n\n /**\n * Decrypts data using XChaCha20-Poly1305 with a raw byte array key.\n *\n * @remarks\n * This is a lower-level method that accepts the key as a raw `Uint8Array` instead of a JWK.\n * It is useful in scenarios where the key material is already in byte form (e.g., derived\n * from ECDH + HKDF) and constructing a JWK would add unnecessary overhead.\n *\n * @param params - The parameters for the decryption operation.\n * @param params.data - The encrypted data including the authentication tag.\n * @param params.keyBytes - The 256-bit (32-byte) decryption key as a Uint8Array.\n * @param params.nonce - The 24-byte nonce used during encryption.\n * @param params.additionalData - Optional additional authenticated data.\n *\n * @returns A Promise that resolves to the decrypted plaintext as a Uint8Array.\n */\n public static async decryptRaw({ data, keyBytes, nonce, additionalData }: {\n additionalData?: Uint8Array;\n data: Uint8Array;\n keyBytes: Uint8Array;\n nonce: Uint8Array;\n }): Promise<Uint8Array> {\n const xc20p = xchacha20poly1305(keyBytes, nonce, additionalData);\n const plaintext = xc20p.decrypt(data);\n\n return plaintext;\n }\n\n /**\n * Encrypts the provided data using XChaCha20-Poly1305.\n *\n * @remarks\n * This method performs XChaCha20-Poly1305 encryption on the given data using the specified key\n * and nonce. It supports optional additional authenticated data (AAD) for enhanced security. The\n * nonce must be 24 bytes long, as per XChaCha20's specifications. The method returns the\n * encrypted data along with an authentication tag as a Uint8Array, ensuring both confidentiality\n * and integrity of the data.\n *\n * @example\n * ```ts\n * const data = new TextEncoder().encode('Messsage');\n * const nonce = utils.randomBytes(24); // 24-byte nonce\n * const additionalData = new TextEncoder().encode('Associated data'); // Optional AAD\n * const key = { ... }; // A Jwk object representing an XChaCha20-Poly1305 key\n * const encryptedData = await XChaCha20Poly1305.encrypt({\n * data,\n * nonce,\n * additionalData,\n * key\n * });\n * ```\n *\n * @param params - The parameters for the encryption operation.\n * @param params.data - The data to encrypt, represented as a Uint8Array.\n * @param params.key - The key to use for encryption, represented in JWK format.\n * @param params.nonce - A 24-byte nonce for the encryption process.\n * @param params.additionalData - Optional additional authenticated data.\n *\n * @returns A Promise that resolves to a byte array containing the encrypted data and the\n * authentication tag.\n */\n public static async encrypt({ data, key, nonce, additionalData }: {\n additionalData?: Uint8Array;\n data: Uint8Array;\n key: Jwk;\n nonce: Uint8Array;\n }): Promise<Uint8Array> {\n // Convert the private key from JWK format to bytes.\n const privateKeyBytes = await XChaCha20Poly1305.privateKeyToBytes({ privateKey: key });\n\n return XChaCha20Poly1305.encryptRaw({ data, keyBytes: privateKeyBytes, nonce, additionalData });\n }\n\n /**\n * Encrypts data using XChaCha20-Poly1305 with a raw byte array key.\n *\n * @remarks\n * This is a lower-level method that accepts the key as a raw `Uint8Array` instead of a JWK.\n * It is useful in scenarios where the key material is already in byte form (e.g., derived\n * from ECDH + HKDF) and constructing a JWK would add unnecessary overhead.\n *\n * The returned `Uint8Array` contains the ciphertext followed by the 16-byte Poly1305\n * authentication tag.\n *\n * @param params - The parameters for the encryption operation.\n * @param params.data - The plaintext data to encrypt.\n * @param params.keyBytes - The 256-bit (32-byte) encryption key as a Uint8Array.\n * @param params.nonce - A 24-byte nonce for the encryption process.\n * @param params.additionalData - Optional additional authenticated data.\n *\n * @returns A Promise that resolves to the ciphertext + authentication tag as a Uint8Array.\n */\n public static async encryptRaw({ data, keyBytes, nonce, additionalData }: {\n additionalData?: Uint8Array;\n data: Uint8Array;\n keyBytes: Uint8Array;\n nonce: Uint8Array;\n }): Promise<Uint8Array> {\n const xc20p = xchacha20poly1305(keyBytes, nonce, additionalData);\n const ciphertext = xc20p.encrypt(data);\n\n return ciphertext;\n }\n\n /**\n * Generates a symmetric key for XChaCha20-Poly1305 in JSON Web Key (JWK) format.\n *\n * @remarks\n * This method creates a new symmetric key suitable for use with the XChaCha20-Poly1305 algorithm.\n * The key is generated using cryptographically secure random number generation to ensure its\n * uniqueness and security. The XChaCha20-Poly1305 algorithm requires a 256-bit key (32 bytes),\n * and this method adheres to that specification.\n *\n * Key components included in the JWK:\n * - `kty`: Key Type, set to 'oct' for Octet Sequence.\n * - `k`: The symmetric key component, base64url-encoded.\n * - `kid`: Key ID, generated based on the JWK thumbprint.\n *\n * @example\n * ```ts\n * const privateKey = await XChaCha20Poly1305.generateKey();\n * ```\n *\n * @returns A Promise that resolves to the generated symmetric key in JWK format.\n */\n public static async generateKey(): Promise<Jwk> {\n // Get the Web Crypto API interface.\n const webCrypto = getWebcryptoSubtle();\n\n // Generate a random private key.\n // See https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#usage_notes for\n // an explanation for why Web Crypto generateKey() is used instead of getRandomValues().\n const webCryptoKey = await webCrypto.generateKey( { name: 'AES-CTR', length: 256 }, true, ['encrypt']);\n\n // Export the private key in JWK format.\n const { alg, ext, key_ops, ...privateKey } = await webCrypto.exportKey('jwk', webCryptoKey);\n\n // Compute the JWK thumbprint and set as the key ID.\n privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n return privateKey;\n }\n\n /**\n * Converts a private key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n *\n * This method takes a symmetric key in JWK format and extracts its raw byte representation.\n * It decodes the 'k' parameter of the JWK value, which represents the symmetric key in base64url\n * encoding, into a byte array.\n *\n * @example\n * ```ts\n * const privateKey = { ... }; // A symmetric key in JWK format\n * const privateKeyBytes = await XChaCha20Poly1305.privateKeyToBytes({ privateKey });\n * ```\n *\n * @param params - The parameters for the symmetric key conversion.\n * @param params.privateKey - The symmetric key in JWK format.\n *\n * @returns A Promise that resolves to the symmetric key as a Uint8Array.\n */\n public static async privateKeyToBytes({ privateKey }: {\n privateKey: Jwk;\n }): Promise<Uint8Array> {\n // Verify the provided JWK represents a valid oct private key.\n if (!isOctPrivateJwk(privateKey)) {\n throw new Error(`XChaCha20Poly1305: The provided key is not a valid oct private key.`);\n }\n\n // Decode the provided private key to bytes.\n const privateKeyBytes = Convert.base64Url(privateKey.k).toUint8Array();\n\n return privateKeyBytes;\n }\n}"],
5
- "mappings": "8pBAAA,IAAAA,GAAAC,EAAA,CAAAC,GAAAC,KAAA,CAMA,IAAMC,GACJ,OAAO,aAAgB,UACvB,aACA,OAAO,YAAY,KAAQ,WACvB,YACA,KAEAC,GAAM,IAAMD,GAAK,IAAI,EACrBE,GAAWC,GAAKA,GAAKA,IAAM,KAAK,MAAMA,CAAC,GAAKA,EAAI,GAAK,SAASA,CAAC,EAC/DC,GAAgBD,GAAKA,IAAM,KAAYD,GAASC,CAAC,EAEjDE,GAAN,MAAMC,CAAS,CACb,YAAY,CACV,IAAAC,EAAM,IACN,IAAAC,EACA,eAAAC,EAAiB,GACjB,cAAAC,EAAgB,GAChB,YAAAC,EAAc,GACd,QAAAC,EACA,eAAAC,EAAiB,EACnB,EAAI,CAAC,EAAG,CAON,GALA,KAAK,YAA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CAAW,EAAI,MAAMS,EAAU,UAAU,MAAOE,CAAY,EAG1F,OAAAX,EAAW,IAAM,MAAME,EAAqB,CAAE,IAAKF,CAAW,CAAC,EAExDA,CACT,CAoBA,aAAoB,kBAAkB,CAAE,WAAAA,CAAW,EAE3B,CAEtB,GAAI,CAACe,GAAgBf,CAAU,EAC7B,MAAM,IAAI,MAAM,qEAAqE,EAMvF,OAFwBC,EAAQ,UAAUD,EAAW,CAAC,EAAE,aAAa,CAGvE,CACF",
6
- "names": ["require_ttlcache", "__commonJSMin", "exports", "module", "perf", "now", "isPosInt", "n", "isPosIntOrInf", "TTLCache", "_TTLCache", "max", "ttl", "updateAgeOnGet", "checkAgeOnGet", "noUpdateTTL", "dispose", "noDisposeOnSet", "expiration", "t", "exp", "entries", "key", "val", "current", "k", "oldValue", "_", "__", "value", "keys", "s", "require_level_supports", "__commonJSMin", "exports", "manifests", "manifest", "acc", "m", "require_module_error", "__commonJSMin", "exports", "module", "message", "options", "require_base64_js", "__commonJSMin", "exports", "byteLength", "toByteArray", "fromByteArray", "lookup", "revLookup", "Arr", "code", "i", "len", "getLens", "b64", "validLen", "placeHoldersLen", "lens", "_byteLength", "tmp", "arr", "curByte", "tripletToBase64", "num", "encodeChunk", "uint8", "start", "end", "output", "extraBytes", "parts", "maxChunkLength", "len2", "require_ieee754", "__commonJSMin", "exports", "buffer", "offset", "isLE", "mLen", "nBytes", "e", "m", "eLen", "eMax", "eBias", "nBits", "i", "d", "s", "value", "c", "rt", "require_buffer", "__commonJSMin", "exports", "base64", "ieee754", "customInspectSymbol", "Buffer", "SlowBuffer", "K_MAX_LENGTH", "typedArraySupport", "arr", "proto", "createBuffer", "length", "buf", "arg", "encodingOrOffset", "allocUnsafe", "from", "value", "fromString", "fromArrayView", "isInstance", "fromArrayBuffer", "valueOf", "b", "fromObject", "assertSize", "size", "alloc", "fill", "encoding", "checked", "string", "byteLength", "actual", "fromArrayLike", "array", "i", "arrayView", "copy", "byteOffset", "obj", "len", "numberIsNaN", "a", "x", "y", "list", "buffer", "pos", "mustMatch", "loweredCase", "utf8ToBytes", "base64ToBytes", "slowToString", "start", "end", "hexSlice", "utf8Slice", "asciiSlice", "latin1Slice", "base64Slice", "utf16leSlice", "swap", "n", "m", "str", "max", "target", "thisStart", "thisEnd", "thisCopy", "targetCopy", "bidirectionalIndexOf", "val", "dir", "arrayIndexOf", "indexSize", "arrLength", "valLength", "read", "foundIndex", "found", "j", "hexWrite", "offset", "remaining", "strLen", "parsed", "utf8Write", "blitBuffer", "asciiWrite", "asciiToBytes", "base64Write", "ucs2Write", "utf16leToBytes", "res", "firstByte", "codePoint", "bytesPerSequence", "secondByte", "thirdByte", "fourthByte", "tempCodePoint", "decodeCodePointsArray", "MAX_ARGUMENTS_LENGTH", "codePoints", "ret", "out", "hexSliceLookupTable", "bytes", "newBuf", "checkOffset", "ext", "noAssert", "mul", "defineBigIntMethod", "validateNumber", "first", "last", "boundsError", "lo", "hi", "checkInt", "min", "maxBytes", "wrtBigUInt64LE", "checkIntBI", "wrtBigUInt64BE", "limit", "sub", "checkIEEE754", "writeFloat", "littleEndian", "writeDouble", "targetStart", "code", "errors", "E", "sym", "getMessage", "Base", "name", "range", "input", "msg", "received", "addNumericalSeparator", "checkBounds", "type", "INVALID_BASE64_RE", "base64clean", "units", "leadSurrogate", "byteArray", "c", "src", "dst", "alphabet", "table", "i16", "fn", "BufferBigIntNotDefined", "require_text_endec", "__commonJSMin", "exports", "module", "lazy", "require_encoding", "__commonJSMin", "exports", "ModuleError", "formats", "Encoding", "options", "require_formats", "__commonJSMin", "exports", "Buffer", "Encoding", "textEndec", "BufferFormat", "options", "ViewFormat", "data", "view", "UTF8Format", "textEncoder", "textDecoder", "require_encodings", "__commonJSMin", "exports", "Buffer", "textEncoder", "textDecoder", "BufferFormat", "ViewFormat", "UTF8Format", "identity", "v", "data", "buffer", "require_level_transcoder", "__commonJSMin", "exports", "ModuleError", "encodings", "Encoding", "BufferFormat", "ViewFormat", "UTF8Format", "kFormats", "kEncodings", "validFormats", "Transcoder", "formats", "f", "k", "err", "encoding", "resolved", "lookup", "from", "name", "format", "options", "maybeType", "anonymousCount", "detectFormat", "aliases", "require_events", "__commonJSMin", "exports", "module", "R", "ReflectApply", "target", "receiver", "args", "ReflectOwnKeys", "ProcessEmitWarning", "warning", "NumberIsNaN", "value", "EventEmitter", "once", "defaultMaxListeners", "checkListener", "listener", "arg", "n", "_getMaxListeners", "that", "type", "i", "doError", "events", "er", "err", "handler", "len", "listeners", "arrayClone", "_addListener", "prepend", "m", "existing", "w", "onceWrapper", "_onceWrap", "state", "wrapped", "list", "position", "originalListener", "spliceOne", "keys", "key", "_listeners", "unwrap", "evlistener", "unwrapListeners", "emitter", "listenerCount", "arr", "copy", "index", "ret", "name", "resolve", "reject", "errorListener", "resolver", "eventTargetAgnosticAddListener", "addErrorHandlerIfEventEmitter", "flags", "wrapListener", "require_next_tick_browser", "__commonJSMin", "exports", "module", "fn", "require_catering", "__commonJSMin", "exports", "nextTick", "callback", "symbol", "promise", "resolve", "reject", "err", "res", "require_common", "__commonJSMin", "exports", "options", "callback", "def", "require_abstract_iterator", "__commonJSMin", "exports", "fromCallback", "ModuleError", "getOptions", "getCallback", "kPromise", "kCallback", "kWorking", "kHandleOne", "kHandleMany", "kAutoClose", "kFinishWork", "kReturnMany", "kClosing", "kHandleClose", "kClosed", "kCloseCallbacks", "kKeyEncoding", "kValueEncoding", "kAbortOnClose", "kLegacy", "kKeys", "kValues", "kLimit", "kCount", "emptyOptions", "noop", "warnedEnd", "CommonIterator", "db", "options", "legacy", "hint", "callback", "promise", "resolve", "reject", "err", "key", "value", "size", "acc", "onnext", "count", "nextv", "onnextv", "items", "cb", "target", "keyEncoding", "keyFormat", "mapped", "callbacks", "item", "AbstractIterator", "IteratorDecodeError", "entries", "entry", "AbstractKeyIterator", "keys", "AbstractValueIterator", "values", "subject", "cause", "k", "require_default_kv_iterator", "__commonJSMin", "exports", "AbstractKeyIterator", "AbstractValueIterator", "kIterator", "kCallback", "kHandleOne", "kHandleMany", "DefaultKeyIterator", "db", "options", "DefaultValueIterator", "Iterator", "keys", "mapEntry", "entry", "callback", "err", "key", "value", "size", "entries", "target", "require_deferred_iterator", "__commonJSMin", "exports", "AbstractIterator", "AbstractKeyIterator", "AbstractValueIterator", "ModuleError", "kNut", "kUndefer", "kFactory", "DeferredIterator", "db", "options", "DeferredKeyIterator", "DeferredValueIterator", "Iterator", "callback", "size", "target", "require_abstract_chained_batch", "__commonJSMin", "exports", "fromCallback", "ModuleError", "getCallback", "getOptions", "kPromise", "kStatus", "kOperations", "kFinishClose", "kCloseCallbacks", "AbstractChainedBatch", "db", "hint", "key", "value", "options", "err", "original", "keyEncoding", "valueEncoding", "keyFormat", "mappedKey", "mappedValue", "callback", "callbacks", "cb", "require_default_chained_batch", "__commonJSMin", "exports", "AbstractChainedBatch", "ModuleError", "kEncoded", "DefaultChainedBatch", "db", "key", "value", "options", "callback", "require_range_options", "__commonJSMin", "exports", "module", "ModuleError", "hasOwnProperty", "rangeOptions", "options", "keyEncoding", "result", "k", "require_queue_microtask", "__commonJSMin", "exports", "module", "promise", "cb", "err", "require_next_tick_browser", "__commonJSMin", "exports", "module", "queueMicrotask", "fn", "args", "require_abstract_sublevel_iterator", "__commonJSMin", "exports", "AbstractIterator", "AbstractKeyIterator", "AbstractValueIterator", "kUnfix", "kIterator", "kHandleOne", "kHandleMany", "kCallback", "AbstractSublevelIterator", "db", "options", "iterator", "unfix", "err", "key", "value", "callback", "entries", "entry", "AbstractSublevelKeyIterator", "keys", "AbstractSublevelValueIterator", "Iterator", "size", "target", "require_abstract_sublevel", "__commonJSMin", "exports", "module", "ModuleError", "Buffer", "AbstractSublevelIterator", "AbstractSublevelKeyIterator", "AbstractSublevelValueIterator", "kPrefix", "kUpperBound", "kPrefixRange", "kParent", "kUnfix", "textEncoder", "defaults", "AbstractLevel", "AbstractSublevel", "options", "db", "name", "separator", "manifest", "forward", "trim", "reserved", "parent", "mergeManifests", "prefix", "upperBound", "MultiFormat", "Unfixer", "key", "keyFormat", "view", "result", "buffer", "range", "callback", "value", "keys", "operations", "iterator", "unfix", "supportsEncoding", "encoding", "prefixLength", "str", "char", "start", "end", "require_abstract_level", "__commonJSMin", "exports", "supports", "Transcoder", "EventEmitter", "fromCallback", "ModuleError", "AbstractIterator", "DefaultKeyIterator", "DefaultValueIterator", "DeferredIterator", "DeferredKeyIterator", "DeferredValueIterator", "DefaultChainedBatch", "getCallback", "getOptions", "rangeOptions", "kPromise", "kLanded", "kResources", "kCloseResources", "kOperations", "kUndefer", "kDeferOpen", "kOptions", "kStatus", "kDefaultOptions", "kTranscoder", "kKeyEncoding", "kValueEncoding", "noop", "AbstractLevel", "manifest", "options", "keyEncoding", "valueEncoding", "passive", "forward", "formats", "encoding", "callback", "maybeOpened", "err", "maybeClosed", "cancel", "pending", "sync", "next", "resource", "key", "maybeError", "keyFormat", "valueFormat", "value", "keys", "mappedKeys", "i", "values", "mappedKey", "mappedValue", "operations", "mapped", "ke", "ve", "op", "db", "valueErr", "name", "AbstractSublevel", "original", "fn", "k", "require_abstract_level", "__commonJSMin", "exports", "require_run_parallel_limit", "__commonJSMin", "exports", "module", "runParallelLimit", "queueMicrotask", "tasks", "limit", "cb", "results", "len", "pending", "keys", "isErrored", "isSync", "next", "done", "err", "end", "each", "i", "result", "key", "task", "require_key_range", "__commonJSMin", "exports", "module", "options", "lower", "upper", "lowerExclusive", "upperExclusive", "require_deserialize", "__commonJSMin", "exports", "module", "textEncoder", "data", "require_iterator", "__commonJSMin", "exports", "AbstractIterator", "createKeyRange", "deserialize", "kCache", "kFinished", "kOptions", "kCurrentOptions", "kPosition", "kLocation", "kFirst", "emptyOptions", "Iterator", "db", "location", "options", "size", "callback", "keyRange", "transaction", "store", "entries", "method", "ev", "cursor", "key", "value", "maybeCommit", "keys", "values", "complete", "length", "i", "err", "cache", "target", "require_clear", "__commonJSMin", "exports", "module", "db", "location", "keyRange", "options", "callback", "transaction", "store", "count", "method", "direction", "ev", "cursor", "require_browser_level", "__commonJSMin", "exports", "AbstractLevel", "ModuleError", "parallel", "fromCallback", "Iterator", "deserialize", "clear", "createKeyRange", "DEFAULT_PREFIX", "kIDB", "kNamePrefix", "kLocation", "kVersion", "kStore", "kOnComplete", "kPromise", "BrowserLevel", "location", "options", "_", "prefix", "version", "forward", "callback", "req", "ev", "db", "mode", "request", "transaction", "key", "store", "err", "value", "keys", "tasks", "next", "operations", "index", "error", "loop", "op", "keyRange", "require_browser", "__commonJSMin", "exports", "src_exports", "__export", "AES_GCM_TAG_LENGTHS", "AesCtr", "AesCtrAlgorithm", "AesGcm", "AesGcmAlgorithm", "AesKw", "ConcatKdf", "CryptoAlgorithm", "CryptoError", "CryptoErrorCode", "CryptoUtils", "EcdsaAlgorithm", "Ed25519", "EdDsaAlgorithm", "Hkdf", "KEY_URI_PREFIX_JWK", "LocalKeyManager", "Secp256r1", "POLY1305_TAG_LENGTH", "Pbkdf2", "Secp256k1", "Sha256", "Sha2Algorithm", "X25519", "XChaCha20", "XChaCha20Poly1305", "canonicalize", "computeJwkThumbprint", "isEcPrivateJwk", "isEcPublicJwk", "isOctPrivateJwk", "isOkpPrivateJwk", "isOkpPublicJwk", "isPrivateJwk", "isPublicJwk", "CryptoError", "_CryptoError", "code", "message", "CryptoErrorCode", "import_ttlcache", "empty", "equals", "aa", "bb", "ii", "coerce", "o", "base", "ALPHABET", "name", "BASE_MAP", "j", "x", "xc", "BASE", "LEADER", "FACTOR", "iFACTOR", "encode", "source", "zeroes", "length", "pbegin", "pend", "size", "b58", "carry", "i", "it1", "it2", "str", "decodeUnsafe", "psz", "b256", "it3", "it4", "vch", "decode", "string", "buffer", "src", "_brrp__multiformats_scope_baseX", "base_x_default", "Encoder", "name", "prefix", "baseEncode", "bytes", "Decoder", "baseDecode", "text", "decoder", "or", "ComposedDecoder", "decoders", "input", "left", "right", "Codec", "from", "encode", "decode", "baseX", "alphabet", "base_x_default", "coerce", "string", "bitsPerChar", "codes", "i", "end", "out", "bits", "buffer", "written", "value", "data", "pad", "mask", "rfc4648", "base32", "rfc4648", "base32upper", "base32pad", "base32padupper", "base32hex", "base32hexupper", "base32hexpad", "base32hexpadupper", "base32z", "base58btc", "baseX", "base58flickr", "base64", "rfc4648", "base64pad", "base64url", "base64urlpad", "isArrayBufferSlice", "arrayBufferView", "isAsyncIterable", "obj", "universalTypeOf", "value", "match", "_", "type", "textEncoder", "textDecoder", "Convert", "_Convert", "data", "format", "isAsyncIterable", "base58btc", "base64url", "universalTypeOf", "isArrayBufferSlice", "base32z", "u8a", "string", "chunks", "_d", "_e", "__asyncValues", "_f", "_a", "_c", "chunk", "hexes", "v", "i", "hex", "text", "str", "dataType", "byteValue", "arrayBuffer", "Web5LogLevel", "Web5Logger", "logLevel", "message", "logger", "varint_exports", "__export", "decode", "encodeTo", "encodingLength", "encode_1", "encode", "MSB", "REST", "MSBALL", "INT", "num", "out", "offset", "oldOffset", "decode", "read", "MSB$1", "REST$1", "buf", "res", "shift", "counter", "b", "l", "N1", "N2", "N3", "N4", "N5", "N6", "N7", "N8", "N9", "length", "value", "varint", "_brrp_varint", "varint_default", "decode", "data", "offset", "varint_default", "encodeTo", "int", "target", "encodingLength", "create", "code", "digest", "size", "sizeOffset", "encodingLength", "digestOffset", "bytes", "encodeTo", "Digest", "decode", "multihash", "coerce", "equals", "a", "b", "data", "format", "link", "base", "bytes", "version", "toStringV0", "baseCache", "base58btc", "toStringV1", "base32", "cache", "baseCache", "cid", "CID", "_CID", "version", "code", "multihash", "bytes", "DAG_PB_CODE", "SHA_256_CODE", "digest", "create", "other", "self", "unknown", "equals", "base", "format", "input", "value", "encodeCID", "cidSymbol", "decode", "remainder", "specs", "prefixSize", "multihashBytes", "coerce", "digestBytes", "Digest", "initialBytes", "offset", "next", "i", "length", "codec", "multihashCode", "digestSize", "size", "multihashSize", "source", "prefix", "parseCIDtoBytes", "decoder", "base58btc", "base32", "toStringV0", "toStringV1", "codeOffset", "encodingLength", "hashOffset", "encodeTo", "Multicodec", "_Multicodec", "options", "code", "data", "name", "_a", "prefixLength", "varint_exports", "dataWithPrefix", "prefixedData", "_", "codec", "codeByteLength", "removeUndefinedProperties", "obj", "key", "import_level", "MemoryStore", "id", "key", "CryptoAlgorithm", "utils_exports", "__export", "bitGet", "bitLen", "bitMask", "bitSet", "bytesToHex", "bytesToNumberBE", "bytesToNumberLE", "concatBytes", "createHmacDrbg", "ensureBytes", "equalBytes", "hexToBytes", "hexToNumber", "isBytes", "numberToBytesBE", "numberToBytesLE", "numberToHexUnpadded", "numberToVarBytesBE", "utf8ToBytes", "validateObject", "_0n", "_1n", "_2n", "a", "hexes", "_", "i", "bytes", "hex", "num", "asciis", "asciiToBase16", "char", "hl", "al", "array", "ai", "hi", "n1", "n2", "n", "len", "title", "expectedLength", "res", "e", "arrays", "sum", "pad", "b", "diff", "str", "pos", "value", "u8n", "data", "u8fr", "arr", "hashLen", "qByteLen", "hmacFn", "v", "k", "reset", "h", "reseed", "seed", "gen", "out", "sl", "pred", "validatorFns", "val", "object", "validators", "optValidators", "checkField", "fieldName", "type", "isOptional", "checkVal", "number", "n", "isBytes", "a", "bytes", "b", "lengths", "hash", "number", "exists", "instance", "checkFinished", "output", "out", "min", "crypto", "isBytes", "a", "createView", "arr", "rotr", "word", "shift", "isLE", "utf8ToBytes", "str", "toBytes", "data", "isBytes", "concatBytes", "arrays", "sum", "i", "a", "res", "pad", "Hash", "toStr", "wrapConstructor", "hashCons", "hashC", "msg", "toBytes", "tmp", "randomBytes", "bytesLength", "crypto", "setBigUint64", "view", "byteOffset", "value", "isLE", "_32n", "_u32_max", "wh", "wl", "h", "l", "SHA2", "Hash", "blockLen", "outputLen", "padOffset", "createView", "data", "exists", "buffer", "toBytes", "len", "pos", "take", "dataView", "out", "output", "i", "oview", "outLen", "state", "res", "to", "length", "finished", "destroyed", "Chi", "a", "b", "c", "Maj", "SHA256_K", "IV", "SHA256_W", "SHA256", "SHA2", "A", "B", "C", "D", "E", "F", "G", "H", "view", "offset", "i", "W15", "W2", "s0", "rotr", "s1", "sigma1", "T1", "T2", "sha256", "wrapConstructor", "SHA256", "_0n", "_1n", "_2n", "_3n", "_4n", "_5n", "_8n", "_9n", "_16n", "mod", "a", "b", "result", "pow", "num", "power", "modulo", "res", "pow2", "x", "invert", "number", "y", "u", "v", "q", "r", "m", "n", "tonelliShanks", "P", "legendreC", "Q", "S", "Z", "p1div4", "Fp", "root", "Q1div2", "g", "t2", "ge", "FpSqrt", "c1", "n2", "nv", "i", "isNegativeLE", "FIELD_FIELDS", "validateField", "field", "initial", "opts", "map", "val", "validateObject", "FpPow", "f", "p", "d", "FpInvertBatch", "nums", "tmp", "lastMultiplied", "acc", "inverted", "nLength", "n", "nBitLength", "_nBitLength", "nByteLength", "Field", "ORDER", "bitLen", "isLE", "redef", "_0n", "BITS", "BYTES", "sqrtP", "FpSqrt", "f", "bitMask", "_1n", "num", "mod", "lhs", "rhs", "power", "FpPow", "invert", "lst", "FpInvertBatch", "b", "c", "numberToBytesLE", "numberToBytesBE", "bytes", "bytesToNumberLE", "bytesToNumberBE", "FpSqrtEven", "Fp", "elm", "root", "getFieldBytesLength", "fieldOrder", "bitLength", "getMinHashLength", "length", "mapHashToField", "key", "isLE", "len", "fieldLen", "minLen", "num", "bytesToNumberBE", "bytesToNumberLE", "reduced", "mod", "_1n", "numberToBytesLE", "numberToBytesBE", "_0n", "_1n", "wNAF", "c", "bits", "constTimeNegate", "condition", "item", "neg", "opts", "W", "windows", "windowSize", "elm", "n", "p", "d", "points", "base", "window", "i", "precomputes", "f", "mask", "maxNumber", "shiftBy", "offset", "wbits", "offset1", "offset2", "cond1", "cond2", "P", "precomputesMap", "transform", "comp", "validateBasic", "curve", "validateField", "validateObject", "nLength", "validatePointOpts", "curve", "opts", "validateBasic", "validateObject", "endo", "Fp", "a", "b2n", "h2b", "utils_exports", "DER", "m", "data", "E", "len", "res", "hex", "isBytes", "l", "r", "sBytes", "rBytesLeft", "sig", "slice", "s", "h", "num", "shl", "rhl", "sl", "rl", "_0n", "_1n", "_2n", "_3n", "_4n", "weierstrassPoints", "CURVE", "toBytes", "_c", "point", "_isCompressed", "concatBytes", "fromBytes", "bytes", "tail", "x", "y", "weierstrassEquation", "b", "x2", "x3", "isWithinCurveOrder", "assertGE", "normPrivateKeyToScalar", "key", "lengths", "nByteLength", "wrapPrivateKey", "n", "bytesToHex", "bytesToNumberBE", "ensureBytes", "mod", "pointPrecomputes", "assertPrjPoint", "other", "Point", "px", "py", "pz", "p", "is0", "i", "points", "toInv", "P", "privateKey", "windowSize", "left", "right", "X1", "Y1", "Z1", "X2", "Y2", "Z2", "U1", "U2", "b3", "X3", "Y3", "Z3", "t0", "t1", "t2", "t3", "t4", "t5", "wnaf", "comp", "I", "k1neg", "k1", "k2neg", "k2", "k1p", "k2p", "d", "scalar", "fake", "f1p", "f2p", "f", "Q", "G", "mul", "sum", "iz", "z", "ax", "ay", "zz", "cofactor", "isTorsionFree", "clearCofactor", "isCompressed", "_bits", "wNAF", "validateOpts", "weierstrass", "curveDef", "CURVE_ORDER", "compressedLen", "uncompressedLen", "isValidFieldElement", "modN", "invN", "invert", "cat", "head", "y2", "isYOdd", "numToNByteStr", "numberToBytesBE", "isBiggerThanHalfOrder", "number", "HALF", "normalizeS", "slcNum", "from", "to", "Signature", "recovery", "msgHash", "rec", "bits2int_modN", "radj", "prefix", "R", "ir", "u1", "u2", "hexToBytes", "utils", "length", "getMinHashLength", "mapHashToField", "getPublicKey", "isProbPub", "item", "arr", "str", "getSharedSecret", "privateA", "publicB", "bits2int", "delta", "ORDER_MASK", "bitMask", "int2octets", "prepSig", "defaultSigOpts", "k", "hash", "randomBytes", "lowS", "prehash", "ent", "h1int", "seedArgs", "e", "seed", "k2sig", "kBytes", "ik", "q", "normS", "defaultVerOpts", "sign", "privKey", "C", "createHmacDrbg", "verify", "signature", "publicKey", "sg", "_sig", "derError", "error", "is", "HMAC", "Hash", "hash", "_key", "key", "toBytes", "blockLen", "pad", "i", "buf", "exists", "out", "bytes", "to", "oHash", "iHash", "finished", "destroyed", "outputLen", "hmac", "message", "getHash", "hash", "key", "msgs", "hmac", "concatBytes", "randomBytes", "createCurve", "curveDef", "defHash", "create", "weierstrass", "secp256k1P", "secp256k1N", "_1n", "_2n", "divNearest", "a", "b", "sqrtMod", "y", "P", "_3n", "_6n", "_11n", "_22n", "_23n", "_44n", "_88n", "b2", "b3", "b6", "pow2", "b9", "b11", "b22", "b44", "b88", "b176", "b220", "b223", "t1", "t2", "root", "Fp", "Field", "secp256k1", "createCurve", "k", "n", "a1", "b1", "a2", "POW_2_128", "c1", "c2", "k1", "mod", "k2", "k1neg", "k2neg", "sha256", "_0n", "Point", "secp256k1", "isBytes", "a", "bytes", "b", "lengths", "exists", "instance", "checkFinished", "output", "out", "bytes", "min", "crypto", "createView", "arr", "rotr", "word", "shift", "isLE", "utf8ToBytes", "str", "toBytes", "data", "bytes", "concatBytes", "arrays", "sum", "i", "a", "res", "pad", "Hash", "toStr", "wrapConstructor", "hashCons", "hashC", "msg", "toBytes", "tmp", "randomBytes", "bytesLength", "crypto", "setBigUint64", "view", "byteOffset", "value", "isLE", "_32n", "_u32_max", "wh", "wl", "h", "l", "Chi", "a", "b", "c", "Maj", "HashMD", "Hash", "blockLen", "outputLen", "padOffset", "createView", "data", "exists", "buffer", "toBytes", "len", "pos", "take", "dataView", "out", "output", "i", "oview", "outLen", "state", "res", "to", "length", "finished", "destroyed", "SHA256_K", "SHA256_IV", "SHA256_W", "SHA256", "HashMD", "A", "B", "C", "D", "E", "F", "G", "H", "view", "offset", "i", "W15", "W2", "s0", "rotr", "s1", "sigma1", "T1", "Chi", "T2", "Maj", "sha256", "wrapConstructor", "SHA256", "canonicalize", "obj", "sortObjKeys", "sortedKeys", "sortedObj", "key", "Sha256", "data", "sha256", "KEY_URI_PREFIX_JWK", "computeJwkThumbprint", "jwk", "keyType", "normalizedJwk", "removeUndefinedProperties", "serializedJwk", "canonicalize", "utf8Bytes", "Convert", "digest", "Sha256", "isEcPrivateJwk", "obj", "isEcPublicJwk", "isOctPrivateJwk", "isOkpPrivateJwk", "isOkpPublicJwk", "isPrivateJwk", "isPublicJwk", "Secp256k1", "_Secp256k1", "signature", "signatureObject", "secp256k1", "privateKeyBytes", "point", "privateKey", "Convert", "computeJwkThumbprint", "publicKeyBytes", "publicKey", "key", "derSignature", "isEcPrivateJwk", "d", "isEcPublicJwk", "prefix", "x", "y", "privateKeyA", "publicKeyB", "privateKeyABytes", "publicKeyBBytes", "data", "digest", "sha256", "keyBytes", "numberToBytesBE", "Fp", "Field", "CURVE_A", "CURVE_B", "p256", "createCurve", "sha256", "secp256r1", "Secp256r1", "_Secp256r1", "signature", "signatureObject", "secp256r1", "privateKeyBytes", "point", "privateKey", "Convert", "computeJwkThumbprint", "publicKeyBytes", "publicKey", "key", "derSignature", "isEcPrivateJwk", "d", "isEcPublicJwk", "prefix", "x", "y", "privateKeyA", "publicKeyB", "privateKeyABytes", "publicKeyBBytes", "data", "digest", "sha256", "keyBytes", "numberToBytesBE", "EcdsaAlgorithm", "CryptoAlgorithm", "key", "isEcPrivateJwk", "publicKey", "Secp256k1", "Secp256r1", "algorithm", "privateKey", "data", "signature", "isEcPublicJwk", "U32_MASK64", "_32n", "fromBig", "n", "le", "split", "lst", "Ah", "Al", "h", "l", "toBig", "shrSH", "_l", "s", "shrSL", "rotrSH", "rotrSL", "rotrBH", "rotrBL", "rotr32H", "_h", "rotr32L", "rotlSH", "rotlSL", "rotlBH", "rotlBL", "add", "Bh", "Bl", "add3L", "Cl", "add3H", "low", "Ch", "add4L", "Dl", "add4H", "Dh", "add5L", "El", "add5H", "Eh", "u64", "fromBig", "split", "toBig", "shrSH", "shrSL", "rotrSH", "rotrSL", "rotrBH", "rotrBL", "rotr32H", "rotr32L", "rotlSH", "rotlSL", "rotlBH", "rotlBL", "add", "add3L", "add3H", "add4L", "add4H", "add5H", "add5L", "u64_default", "SHA512_Kh", "SHA512_Kl", "u64_default", "n", "SHA512_W_H", "SHA512_W_L", "SHA512", "SHA2", "Ah", "Al", "Bh", "Bl", "Ch", "Cl", "Dh", "Dl", "Eh", "El", "Fh", "Fl", "Gh", "Gl", "Hh", "Hl", "view", "offset", "i", "W15h", "W15l", "s0h", "s0l", "W2h", "W2l", "s1h", "s1l", "SUMl", "SUMh", "sigma1h", "sigma1l", "CHIh", "CHIl", "T1ll", "T1h", "T1l", "sigma0h", "sigma0l", "MAJh", "MAJl", "All", "sha512", "wrapConstructor", "SHA512", "_0n", "_1n", "_2n", "_8n", "VERIFY_DEFAULT", "validateOpts", "curve", "opts", "validateBasic", "validateObject", "twistedEdwards", "curveDef", "CURVE", "Fp", "CURVE_ORDER", "prehash", "cHash", "randomBytes", "nByteLength", "cofactor", "MASK", "modP", "uvRatio", "u", "v", "adjustScalarBytes", "bytes", "domain", "data", "ctx", "phflag", "inBig", "n", "inRange", "max", "in0MaskRange", "assertInRange", "assertGE0", "pointPrecomputes", "isPoint", "other", "Point", "ex", "ey", "ez", "et", "p", "x", "y", "points", "toInv", "i", "windowSize", "a", "d", "X", "Y", "Z", "T", "X2", "Y2", "Z2", "Z4", "aX2", "left", "right", "XY", "ZT", "X1", "Y1", "Z1", "X1Z2", "X2Z1", "Y1Z2", "Y2Z1", "A", "B", "C", "D", "x1y1", "E", "G", "F", "H", "X3", "Y3", "T3", "Z3", "T1", "T2", "wnaf", "scalar", "f", "I", "iz", "z", "is0", "ax", "ay", "zz", "hex", "zip215", "len", "ensureBytes", "normed", "lastByte", "bytesToNumberLE", "y2", "isValid", "isXOdd", "isLastByteOdd", "privKey", "getExtendedPublicKey", "numberToBytesLE", "bytesToHex", "wNAF", "modN", "mod", "modN_LE", "hash", "key", "hashed", "head", "prefix", "point", "pointBytes", "getPublicKey", "hashDomainToScalar", "context", "msgs", "msg", "concatBytes", "sign", "options", "r", "R", "k", "s", "res", "verifyOpts", "verify", "sig", "publicKey", "SB", "_0n", "_1n", "validateOpts", "curve", "validateObject", "montgomery", "curveDef", "CURVE", "P", "modP", "n", "mod", "montgomeryBits", "montgomeryBytes", "fieldLen", "adjustScalarBytes", "bytes", "powPminus2", "x", "pow", "cswap", "swap", "x_2", "x_3", "dummy", "assertFieldElement", "a24", "montgomeryLadder", "pointU", "scalar", "u", "k", "x_1", "z_2", "z_3", "sw", "t", "k_t", "A", "AA", "B", "BB", "E", "D", "DA", "CB", "dacb", "da_cb", "z2", "encodeUCoordinate", "numberToBytesLE", "decodeUCoordinate", "uEnc", "ensureBytes", "bytesToNumberLE", "decodeScalar", "len", "scalarMult", "_scalar", "pu", "GuBytes", "scalarMultBase", "privateKey", "publicKey", "ED25519_P", "ED25519_SQRT_M1", "_0n", "_1n", "_2n", "_5n", "_10n", "_20n", "_40n", "_80n", "ed25519_pow_2_252_3", "x", "P", "b2", "b4", "pow2", "b5", "b10", "b20", "b40", "b80", "b160", "b240", "b250", "adjustScalarBytes", "bytes", "uvRatio", "u", "v", "v3", "mod", "v7", "pow", "vx2", "root1", "root2", "useRoot1", "useRoot2", "noRoot", "isNegativeLE", "Fp", "Field", "ED25519_P", "ed25519Defaults", "sha512", "randomBytes", "adjustScalarBytes", "uvRatio", "ed25519", "twistedEdwards", "ed25519_domain", "data", "ctx", "phflag", "concatBytes", "utf8ToBytes", "ed25519ctx", "ed25519ph", "x25519", "montgomery", "x", "P", "pow_p_5_8", "b2", "ed25519_pow_2_252_3", "mod", "pow2", "edwardsToMontgomeryPub", "edwardsPub", "y", "_1n", "edwardsToMontgomeryPriv", "edwardsPriv", "hashed", "ed25519Defaults", "ELL2_C1", "Fp", "ELL2_C2", "_2n", "ELL2_C3", "ELL2_C4", "ELL2_J", "ELL2_C1_EDWARDS", "FpSqrtEven", "Fp", "SQRT_AD_MINUS_ONE", "INVSQRT_A_MINUS_D", "ONE_MINUS_D_SQ", "D_MINUS_ONE_SQ", "MAX_255B", "Ed25519", "_Ed25519", "privateKeyBytes", "publicKeyBytes", "ed25519", "privateKey", "Convert", "computeJwkThumbprint", "publicKey", "key", "ed25519PrivateKeyBytes", "x25519PrivateKeyBytes", "edwardsToMontgomeryPriv", "x25519PublicKeyBytes", "x25519", "x25519PrivateKey", "ed25519PublicKeyBytes", "edwardsToMontgomeryPub", "x25519PublicKey", "isOkpPrivateJwk", "d", "isOkpPublicJwk", "data", "signature", "EdDsaAlgorithm", "CryptoAlgorithm", "key", "isOkpPrivateJwk", "publicKey", "Ed25519", "algorithm", "privateKey", "data", "signature", "isOkpPublicJwk", "Sha2Algorithm", "CryptoAlgorithm", "algorithm", "data", "Sha256", "supportedAlgorithms", "EdDsaAlgorithm", "EcdsaAlgorithm", "Sha2Algorithm", "LocalKeyManager", "params", "MemoryStore", "algorithm", "data", "keyUri", "key", "KEY_URI_PREFIX_JWK", "jwkThumbprint", "computeJwkThumbprint", "privateKey", "isPrivateJwk", "signature", "AlgorithmImplementation", "algProperty", "crvProperty", "algName", "algorithmInfo", "CryptoUtils", "_CryptoUtils", "publicKey", "curveToJoseAlgorithm", "bytesLength", "randomBytes", "crypto", "length", "max", "pin", "rejectionRange", "randomBuffer", "cr", "getWebcryptoSubtle", "cr", "AES_BLOCK_SIZE", "AES_KEY_LENGTHS", "COUNTER_MAX_LENGTH", "AesCtr", "privateKeyBytes", "privateKey", "Convert", "computeJwkThumbprint", "key", "data", "counter", "length", "webCrypto", "getWebcryptoSubtle", "webCryptoKey", "plaintextBuffer", "ciphertextBuffer", "ext", "key_ops", "isOctPrivateJwk", "AesCtrAlgorithm", "CryptoAlgorithm", "params", "AesCtr", "algorithm", "length", "privateKey", "number", "n", "bool", "b", "isBytes", "a", "bytes", "lengths", "exists", "instance", "checkFinished", "output", "out", "bytes", "min", "u32", "arr", "createView", "isLE", "utf8ToBytes", "str", "toBytes", "data", "utf8ToBytes", "isBytes", "checkOpts", "defaults", "opts", "equalBytes", "a", "b", "diff", "i", "wrapCipher", "params", "c", "setBigUint64", "view", "byteOffset", "value", "isLE", "_32n", "_u32_max", "wh", "wl", "h", "l", "utils", "key", "keyParams", "cryptParams", "plaintext", "cr", "getWebcryptoSubtle", "iKey", "ciphertext", "mode", "getCryptParams", "algo", "nonce", "AAD", "generate", "bytes", "cbc", "ctr", "gcm", "AES_GCM_IV_LENGTH", "AES_KEY_LENGTHS", "AES_GCM_TAG_LENGTHS", "AesGcm", "privateKeyBytes", "privateKey", "Convert", "computeJwkThumbprint", "key", "data", "iv", "additionalData", "tagLength", "webCrypto", "getWebcryptoSubtle", "webCryptoKey", "algorithm", "plaintextBuffer", "ciphertextBuffer", "length", "ext", "key_ops", "isOctPrivateJwk", "AesGcmAlgorithm", "CryptoAlgorithm", "params", "AesGcm", "algorithm", "length", "privateKey", "AES_KEY_LENGTHS", "AesKw", "privateKeyBytes", "privateKey", "Convert", "computeJwkThumbprint", "lengthInBits", "length", "webCrypto", "getWebcryptoSubtle", "webCryptoKey", "ext", "key_ops", "isOctPrivateJwk", "wrappedKeyBytes", "wrappedKeyAlgorithm", "decryptionKey", "CryptoError", "decryptionCryptoKey", "webCryptoAlgorithm", "unwrappedCryptoKey", "unwrappedJsonWebKey", "unwrappedKey", "encryptionKey", "encryptionCryptoKey", "wrappedKeyBuffer", "ConcatKdf", "_ConcatKdf", "keyDataLen", "fixedInfo", "sharedSecret", "roundCount", "counter", "fixedInfoBytes", "sha256", "concatBytes", "params", "algorithmId", "partyUInfo", "partyVInfo", "suppPubInfo", "suppPrivInfo", "data", "variableLength", "encodedData", "dataType", "universalTypeOf", "dataU8A", "Convert", "bufferLength", "Hkdf", "baseKeyBytes", "length", "hash", "salt", "info", "webCrypto", "getWebcryptoSubtle", "webCryptoKey", "saltBytes", "Convert", "infoBytes", "derivedKeyBuffer", "Pbkdf2", "hash", "password", "salt", "iterations", "length", "webCryptoKey", "crypto", "derivedKeyBuffer", "baseKeyBytes", "webCrypto", "getWebcryptoSubtle", "X25519", "_X25519", "privateKeyBytes", "publicKeyBytes", "x25519", "privateKey", "Convert", "computeJwkThumbprint", "publicKey", "key", "isOkpPrivateJwk", "d", "isOkpPublicJwk", "privateKeyA", "publicKeyB", "privateKeyABytes", "publicKeyBBytes", "u8to16", "a", "i", "Poly1305", "key", "toBytes", "bytes", "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "data", "offset", "isLast", "hibit", "h", "r", "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "h0", "h1", "h2", "h3", "h4", "h5", "h6", "h7", "h8", "h9", "c", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "pad", "g", "mask", "f", "exists", "buffer", "blockLen", "len", "pos", "take", "out", "output", "opos", "outputLen", "res", "wrapConstructorWithKey", "hashCons", "hashC", "msg", "tmp", "poly1305", "_utf8ToBytes", "str", "c", "sigma16", "sigma32", "sigma16_32", "u32", "sigma32_32", "sigma", "rotl", "a", "b", "isAligned32", "BLOCK_LEN", "BLOCK_LEN32", "MAX_COUNTER", "U32_EMPTY", "runCipher", "core", "key", "nonce", "data", "output", "counter", "rounds", "len", "block", "b32", "isAligned", "d32", "o32", "pos", "take", "pos32", "j", "posj", "createCipher", "opts", "allowShortKeys", "extendNonceFn", "counterLength", "counterRight", "checkOpts", "number", "bool", "bytes", "toClean", "l", "k", "k32", "nonceNcLen", "nc", "n32", "chachaCore", "s", "k", "n", "out", "cnt", "rounds", "y00", "y01", "y02", "y03", "y04", "y05", "y06", "y07", "y08", "y09", "y10", "y11", "y12", "y13", "y14", "y15", "x00", "x01", "x02", "x03", "x04", "x05", "x06", "x07", "x08", "x09", "x10", "x11", "x12", "x13", "x14", "x15", "r", "rotl", "oi", "hchacha", "i", "o32", "chacha20", "createCipher", "chachaCore", "xchacha20", "hchacha", "ZEROS16", "updatePadded", "h", "msg", "left", "ZEROS32", "computeTag", "fn", "key", "nonce", "data", "AAD", "authKey", "poly1305", "num", "view", "createView", "setBigUint64", "res", "_poly1305_aead", "xorStream", "bytes", "plaintext", "output", "plength", "clength", "tag", "ciphertext", "passedTag", "equalBytes", "chacha20poly1305", "wrapCipher", "chacha20", "xchacha20poly1305", "xchacha20", "XChaCha20", "_XChaCha20", "privateKeyBytes", "privateKey", "Convert", "computeJwkThumbprint", "data", "key", "nonce", "xchacha20", "webCrypto", "getWebcryptoSubtle", "webCryptoKey", "alg", "ext", "key_ops", "isOctPrivateJwk", "POLY1305_TAG_LENGTH", "XChaCha20Poly1305", "_XChaCha20Poly1305", "privateKeyBytes", "privateKey", "Convert", "computeJwkThumbprint", "data", "key", "nonce", "additionalData", "keyBytes", "xchacha20poly1305", "webCrypto", "getWebcryptoSubtle", "webCryptoKey", "alg", "ext", "key_ops", "isOctPrivateJwk"]
7
- }