@pacspace-io/sdk 0.9.0 → 0.15.2
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.
- package/README.md +53 -132
- package/dist/blinding-file.d.ts +13 -0
- package/dist/blinding-file.d.ts.map +1 -0
- package/dist/blinding-guard.d.ts +7 -0
- package/dist/blinding-guard.d.ts.map +1 -0
- package/dist/blinding.d.ts +32 -0
- package/dist/blinding.d.ts.map +1 -0
- package/dist/client.d.ts +28 -4
- package/dist/client.d.ts.map +1 -1
- package/dist/fingerprint.d.ts +26 -5
- package/dist/fingerprint.d.ts.map +1 -1
- package/dist/index.d.ts +35 -35
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7366 -186
- package/dist/index.js.map +7 -1
- package/dist/inputs.txt +132 -0
- package/dist/records-crypto-libraries.json +42 -0
- package/dist/records-crypto-types/proof/hiding-commitment-v1.d.ts +19 -0
- package/dist/records-crypto-types/proof/jcs.d.ts +4 -0
- package/dist/records-crypto-types/proof/layout-document-v1.d.ts +72 -0
- package/dist/records-crypto-types/proof/ledger-head-v1.d.ts +22 -0
- package/dist/records-crypto-types/proof/merkle-v2.d.ts +5 -0
- package/dist/records-crypto-types/proof/payload-ref-v1.d.ts +17 -0
- package/dist/records-crypto-types/proof/seal-input.d.ts +2 -0
- package/dist/records-crypto-types/proof/semantic-receipt-v2.d.ts +89 -0
- package/dist/records-crypto-types/proof/semantic-receipt-v3.d.ts +20 -0
- package/dist/records-crypto-types/proof/slot-encoding-v1.d.ts +169 -0
- package/dist/records-crypto-types/records/flag-threads-v1.d.ts +53 -0
- package/dist/records-crypto-types/records/labels.d.ts +37 -0
- package/dist/records-crypto-types/records/reader-crypto-v1.d.ts +198 -0
- package/dist/records-crypto-types/records/reader-link-v1.d.ts +164 -0
- package/dist/records-crypto-types/records/shared-record-ack-v2.d.ts +72 -0
- package/dist/records-crypto-types/records/signed-acknowledgment-v1.d.ts +38 -0
- package/dist/records-crypto-types/records/signed-acknowledgment-v2.d.ts +12 -0
- package/dist/records-crypto-types/records/trail-index-v1.d.ts +89 -0
- package/dist/records-crypto-types/records/trail-rule.d.ts +54 -0
- package/dist/records-crypto-types/records-crypto/asymmetric/ack-flag-notes-v1.d.ts +57 -0
- package/dist/records-crypto-types/records-crypto/asymmetric/flag-notes-v1.d.ts +55 -0
- package/dist/records-crypto-types/records-crypto/asymmetric/index.d.ts +4 -0
- package/dist/records-crypto-types/records-crypto/asymmetric/reader-wraps-v1.d.ts +83 -0
- package/dist/records-crypto-types/records-crypto/asymmetric/records-asymmetric-v1.d.ts +201 -0
- package/dist/records-crypto-types/records-crypto/base64url.d.ts +3 -0
- package/dist/records-crypto-types/records-crypto/blinding-file.d.ts +16 -0
- package/dist/records-crypto-types/records-crypto/blinding-value.d.ts +10 -0
- package/dist/records-crypto-types/records-crypto/bundle-entry.d.ts +2 -0
- package/dist/records-crypto-types/records-crypto/disclosure-envelope-v1.d.ts +42 -0
- package/dist/records-crypto-types/records-crypto/held-file.d.ts +17 -0
- package/dist/records-crypto-types/records-crypto/hmac-node.d.ts +8 -0
- package/dist/records-crypto-types/records-crypto/hmac-web.d.ts +8 -0
- package/dist/records-crypto-types/records-crypto/index.d.ts +13 -0
- package/dist/records-crypto-types/records-crypto/platform-crypto.d.ts +9 -0
- package/dist/records-crypto-types/records-crypto/record-disclosure-v1.d.ts +171 -0
- package/dist/records-crypto-types/records-crypto/record-hash-v2.d.ts +49 -0
- package/dist/records-crypto-types/records-crypto/record-hash-v3.d.ts +36 -0
- package/dist/records-crypto-types/records-crypto/records-encryption-v1.d.ts +185 -0
- package/dist/records-crypto-types/records-crypto/wrap-shapes-v1.d.ts +23 -0
- package/dist/records-crypto.d.ts +1 -0
- package/dist/records-crypto.js +16105 -0
- package/dist/records-crypto.js.map +7 -0
- package/dist/records-encryption/base64url.d.ts +5 -0
- package/dist/records-encryption/base64url.d.ts.map +1 -0
- package/dist/records-encryption/encrypted-records.d.ts +338 -0
- package/dist/records-encryption/encrypted-records.d.ts.map +1 -0
- package/dist/records-encryption/index.d.ts +14 -0
- package/dist/records-encryption/index.d.ts.map +1 -0
- package/dist/records-encryption/keys.d.ts +40 -0
- package/dist/records-encryption/keys.d.ts.map +1 -0
- package/dist/records-encryption/loader.d.ts +15 -0
- package/dist/records-encryption/loader.d.ts.map +1 -0
- package/dist/records-encryption/pin-store-file.d.ts +8 -0
- package/dist/records-encryption/pin-store-file.d.ts.map +1 -0
- package/dist/records-encryption/pin-store.d.ts +17 -0
- package/dist/records-encryption/pin-store.d.ts.map +1 -0
- package/dist/records-encryption/transport.d.ts +23 -0
- package/dist/records-encryption/transport.d.ts.map +1 -0
- package/dist/records-encryption/words.d.ts +40 -0
- package/dist/records-encryption/words.d.ts.map +1 -0
- package/dist/records-encryption/workspace-secret.d.ts +9 -0
- package/dist/records-encryption/workspace-secret.d.ts.map +1 -0
- package/dist/resources/records.d.ts +112 -2
- package/dist/resources/records.d.ts.map +1 -1
- package/dist/types/common.d.ts +0 -8
- package/dist/types/common.d.ts.map +1 -1
- package/dist/types/config.d.ts +7 -5
- package/dist/types/config.d.ts.map +1 -1
- package/dist/types/records-encryption.d.ts +136 -0
- package/dist/types/records-encryption.d.ts.map +1 -0
- package/dist/types/records.d.ts +171 -20
- package/dist/types/records.d.ts.map +1 -1
- package/dist/types/verify.d.ts +84 -0
- package/dist/types/verify.d.ts.map +1 -0
- package/dist/webhooks/index.d.ts +1 -1
- package/dist/webhooks/index.d.ts.map +1 -1
- package/dist/webhooks/index.js +229 -5
- package/dist/webhooks/index.js.map +7 -1
- package/dist/webhooks/types.d.ts +15 -7
- package/dist/webhooks/types.d.ts.map +1 -1
- package/dist/workspace-secret-file.d.ts +18 -0
- package/dist/workspace-secret-file.d.ts.map +1 -0
- package/package.json +16 -13
- package/dist/client.js +0 -553
- package/dist/client.js.map +0 -1
- package/dist/errors/index.js +0 -223
- package/dist/errors/index.js.map +0 -1
- package/dist/fingerprint.js +0 -132
- package/dist/fingerprint.js.map +0 -1
- package/dist/resources/balance.d.ts +0 -384
- package/dist/resources/balance.d.ts.map +0 -1
- package/dist/resources/balance.js +0 -1120
- package/dist/resources/balance.js.map +0 -1
- package/dist/resources/customers.d.ts +0 -33
- package/dist/resources/customers.d.ts.map +0 -1
- package/dist/resources/customers.js +0 -26
- package/dist/resources/customers.js.map +0 -1
- package/dist/resources/internal/batch-transport.d.ts +0 -65
- package/dist/resources/internal/batch-transport.d.ts.map +0 -1
- package/dist/resources/internal/batch-transport.js +0 -42
- package/dist/resources/internal/batch-transport.js.map +0 -1
- package/dist/resources/receipts.d.ts +0 -46
- package/dist/resources/receipts.d.ts.map +0 -1
- package/dist/resources/receipts.js +0 -133
- package/dist/resources/receipts.js.map +0 -1
- package/dist/resources/records.js +0 -232
- package/dist/resources/records.js.map +0 -1
- package/dist/resources/submission.d.ts +0 -79
- package/dist/resources/submission.d.ts.map +0 -1
- package/dist/resources/submission.js +0 -398
- package/dist/resources/submission.js.map +0 -1
- package/dist/types/balance.d.ts +0 -966
- package/dist/types/balance.d.ts.map +0 -1
- package/dist/types/balance.js +0 -3
- package/dist/types/balance.js.map +0 -1
- package/dist/types/common.js +0 -3
- package/dist/types/common.js.map +0 -1
- package/dist/types/config.js +0 -3
- package/dist/types/config.js.map +0 -1
- package/dist/types/records.js +0 -5
- package/dist/types/records.js.map +0 -1
- package/dist/types/submission.d.ts +0 -125
- package/dist/types/submission.d.ts.map +0 -1
- package/dist/types/submission.js +0 -3
- package/dist/types/submission.js.map +0 -1
- package/dist/utils/polling.d.ts +0 -32
- package/dist/utils/polling.d.ts.map +0 -1
- package/dist/utils/polling.js +0 -52
- package/dist/utils/polling.js.map +0 -1
- package/dist/utils/retry.js +0 -21
- package/dist/utils/retry.js.map +0 -1
- package/dist/webhooks/types.js +0 -3
- package/dist/webhooks/types.js.map +0 -1
- package/dist/webhooks/verify.js +0 -191
- package/dist/webhooks/verify.js.map +0 -1
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../node_modules/hpke/index.js", "../../../node_modules/@noble/ciphers/utils.js", "../../../node_modules/@noble/ciphers/_arx.js", "../../../node_modules/@noble/ciphers/_poly1305.js", "../../../node_modules/@noble/ciphers/chacha.js", "../../../node_modules/@noble/ciphers/_polyval.js", "../../../node_modules/@noble/ciphers/aes.js", "../../../node_modules/@panva/hpke-noble/node_modules/@noble/hashes/_u64.js", "../../../node_modules/@panva/hpke-noble/node_modules/@noble/hashes/utils.js", "../../../node_modules/@panva/hpke-noble/node_modules/@noble/hashes/sha3.js", "../../../node_modules/@panva/hpke-noble/node_modules/@noble/hashes/sha3-addons.js", "../../../node_modules/@panva/hpke-noble/node_modules/@noble/hashes/hmac.js", "../../../node_modules/@panva/hpke-noble/node_modules/@noble/hashes/hkdf.js", "../../../node_modules/@panva/hpke-noble/node_modules/@noble/hashes/_md.js", "../../../node_modules/@panva/hpke-noble/node_modules/@noble/hashes/sha2.js", "../../../node_modules/@noble/post-quantum/node_modules/@noble/hashes/_u64.js", "../../../node_modules/@noble/post-quantum/node_modules/@noble/hashes/utils.js", "../../../node_modules/@noble/post-quantum/node_modules/@noble/hashes/sha3.js", "../../../node_modules/@noble/post-quantum/node_modules/@noble/curves/utils.js", "../../../node_modules/@noble/post-quantum/node_modules/@noble/curves/abstract/modular.js", "../../../node_modules/@noble/post-quantum/node_modules/@noble/curves/abstract/fft.js", "../../../node_modules/@noble/post-quantum/utils.js", "../../../node_modules/@noble/post-quantum/_crystals.js", "../../../node_modules/@noble/post-quantum/ml-kem.js", "../../../node_modules/@noble/post-quantum/node_modules/@noble/curves/abstract/curve.js", "../../../node_modules/@noble/post-quantum/node_modules/@noble/curves/abstract/edwards.js", "../../../node_modules/@noble/post-quantum/node_modules/@noble/curves/abstract/montgomery.js", "../../../node_modules/@noble/post-quantum/node_modules/@noble/hashes/hmac.js", "../../../node_modules/@noble/post-quantum/node_modules/@noble/curves/abstract/der.js", "../../../node_modules/@noble/post-quantum/node_modules/@noble/curves/abstract/weierstrass.js", "../../../node_modules/@noble/post-quantum/node_modules/@noble/hashes/_md.js", "../../../node_modules/@noble/post-quantum/node_modules/@noble/hashes/sha2.js", "../../../node_modules/@noble/post-quantum/node_modules/@noble/curves/ed25519.js", "../../../node_modules/@noble/post-quantum/node_modules/@noble/curves/nist.js", "../../../node_modules/@noble/post-quantum/node_modules/@noble/hashes/hkdf.js", "../../../node_modules/@noble/post-quantum/hybrid.js", "../../../node_modules/@panva/hpke-noble/node_modules/@noble/curves/utils.js", "../../../node_modules/@panva/hpke-noble/node_modules/@noble/curves/abstract/modular.js", "../../../node_modules/@panva/hpke-noble/node_modules/@noble/curves/abstract/curve.js", "../../../node_modules/@panva/hpke-noble/node_modules/@noble/curves/abstract/edwards.js", "../../../node_modules/@panva/hpke-noble/node_modules/@noble/curves/abstract/montgomery.js", "../../../node_modules/@panva/hpke-noble/node_modules/@noble/curves/ed25519.js", "../../../node_modules/@panva/hpke-noble/node_modules/@noble/curves/ed448.js", "../../../node_modules/@panva/hpke-noble/node_modules/@noble/curves/abstract/der.js", "../../../node_modules/@panva/hpke-noble/node_modules/@noble/curves/abstract/weierstrass.js", "../../../node_modules/@panva/hpke-noble/node_modules/@noble/curves/nist.js", "../../../node_modules/@panva/hpke-noble/index.js", "../../../node_modules/@noble/post-quantum/ml-dsa.js", "../../shared/src/records-crypto/bundle-entry.ts", "../../shared/src/records-crypto/blinding-value.ts", "../../shared/src/records-crypto/hmac-node.ts", "../../shared/src/records-crypto/hmac-web.ts", "../../shared/src/proof/layout-document-v1.ts", "../../shared/src/proof/jcs.ts", "../../shared/src/proof/payload-ref-v1.ts", "../../shared/src/records-crypto/blinding-file.ts", "../../shared/src/records-crypto/held-file.ts", "../../shared/src/records-crypto/platform-crypto.ts", "../../shared/src/records-crypto/record-hash-v2.ts", "../../shared/src/records-crypto/record-hash-v3.ts", "../../shared/src/proof/hiding-commitment-v1.ts", "../../shared/src/proof/merkle-v2.ts", "../../shared/src/proof/seal-input.ts", "../../shared/src/proof/slot-encoding-v1.ts", "../../shared/src/proof/ledger-head-v1.ts", "../../shared/src/records-crypto/record-disclosure-v1.ts", "../../shared/src/records-crypto/base64url.ts", "../../shared/src/records-crypto/disclosure-envelope-v1.ts", "../../shared/src/records-crypto/wrap-shapes-v1.ts", "../../shared/src/records-crypto/records-encryption-v1.ts", "../../shared/src/records-crypto/index.ts", "../../shared/src/records/signed-acknowledgment-v2.ts", "../../shared/src/records-crypto/asymmetric/records-asymmetric-v1.ts", "../../shared/src/records/reader-crypto-v1.ts", "../../shared/src/records-crypto/asymmetric/reader-wraps-v1.ts", "../../shared/src/records/shared-record-ack-v2.ts", "../../shared/src/records-crypto/asymmetric/ack-flag-notes-v1.ts", "../../shared/src/records/trail-index-v1.ts", "../../shared/src/records/reader-link-v1.ts", "../../shared/src/records/flag-threads-v1.ts", "../../shared/src/records-crypto/asymmetric/flag-notes-v1.ts"],
|
|
4
|
+
"sourcesContent": ["\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n\n \nfunction ComputeNonce(base_nonce , seq , Nn ) {\n \n \n \n const nonce = new Uint8Array(Nn)\n nonce.set(base_nonce)\n let s = seq\n for (let i = Nn - 1; i >= 0 && s > 0; i--) {\n nonce[i] = nonce[i] ^ (s & 0xff)\n s = Math.floor(s / 256)\n }\n return nonce\n}\n\nfunction MaxSeq(Nn ) {\n \n \n return Math.min(2 ** (8 * Nn) - 1, Number.MAX_SAFE_INTEGER)\n}\n\n \nfunction IncrementSeq(seq , maxSeq ) {\n if (seq >= maxSeq) {\n throw new MessageLimitReachedError('Sequence number overflow')\n }\n return ++seq\n}\n\n \nasync function ContextExport(\n suite ,\n exporterSecret ,\n exporterContext ,\n L ,\n) {\n checkUint8Array(exporterContext, 'exporterContext')\n const stages = KDFStages(suite.KDF)\n if (!Number.isInteger(L) || L <= 0 || L > 0xffff) {\n throw new TypeError('\"L\" must be a positive integer not exceeding 65535')\n }\n if (stages === 2 && L > 255 * suite.KDF.Nh) {\n throw new TypeError('\"L\" must not exceed 255*Nh of the cipher suite KDF')\n }\n const Export = stages === 1 ? Export_OneStage : Export_TwoStage\n return await Export(suite.KDF, suite.id, exporterSecret, exporterContext, L)\n}\n\nclass Mutex {\n #locked = Promise.resolve()\n\n async lock() {\n let releaseLock \n const nextLock = new Promise ((resolve) => {\n releaseLock = resolve\n })\n const previousLock = this.#locked\n this.#locked = nextLock\n await previousLock\n return releaseLock\n }\n}\n\n \n \n \n \n \n \n \n \n \n \n\nfunction createContextState(\n suite ,\n mode ,\n key ,\n base_nonce ,\n exporter_secret ,\n) {\n return {\n suite,\n mode,\n key,\n base_nonce,\n exporter_secret,\n max_seq: MaxSeq(suite.AEAD.Nn),\n seq: 0,\n mutex: undefined,\n }\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nclass SenderContext {\n #state \n\n constructor(\n suite ,\n mode ,\n key ,\n base_nonce ,\n exporter_secret ,\n ) {\n this.#state = createContextState(suite, mode, key, base_nonce, exporter_secret)\n }\n\n \n\n\n\n\n get mode() {\n return this.#state.mode\n }\n\n \n\n\n\n\n\n get seq() {\n return this.#state.seq\n }\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n async Seal(plaintext , aad ) {\n checkUint8Array(plaintext, 'plaintext')\n aad ??= new Uint8Array()\n checkUint8Array(aad, 'aad')\n const state = this.#state\n if (state.suite.AEAD.id === EXPORT_ONLY) {\n throw new TypeError('Export-only AEAD cannot be used with Seal')\n }\n\n state.mutex ??= new Mutex()\n const release = await state.mutex.lock()\n let ct \n try {\n ct = await state.suite.AEAD.Seal(\n state.key,\n ComputeNonce(state.base_nonce, state.seq, state.suite.AEAD.Nn),\n aad,\n plaintext,\n )\n state.seq = IncrementSeq(state.seq, state.max_seq)\n return ct\n } finally {\n release()\n }\n }\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n async Export(exporterContext , length ) {\n return await ContextExport(\n this.#state.suite,\n this.#state.exporter_secret,\n exporterContext,\n length,\n )\n }\n\n \n\n\n\n get Nt() {\n return this.#state.suite.AEAD.Nt\n }\n}\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nclass RecipientContext {\n #state \n\n constructor(\n suite ,\n mode ,\n key ,\n base_nonce ,\n exporter_secret ,\n ) {\n this.#state = createContextState(suite, mode, key, base_nonce, exporter_secret)\n }\n\n \n\n\n\n\n get mode() {\n return this.#state.mode\n }\n\n \n\n\n\n\n\n get seq() {\n return this.#state.seq\n }\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n async Open(ciphertext , aad ) {\n checkUint8Array(ciphertext, 'ciphertext')\n aad ??= new Uint8Array()\n checkUint8Array(aad, 'aad')\n\n const state = this.#state\n if (state.suite.AEAD.id === EXPORT_ONLY) {\n throw new TypeError('Export-only AEAD cannot be used with Open')\n }\n\n state.mutex ??= new Mutex()\n const release = await state.mutex.lock()\n try {\n let pt \n try {\n pt = await state.suite.AEAD.Open(\n state.key,\n ComputeNonce(state.base_nonce, state.seq, state.suite.AEAD.Nn),\n aad,\n ciphertext,\n )\n } catch (cause) {\n if (cause instanceof MessageLimitReachedError || cause instanceof NotSupportedError) {\n throw cause\n }\n\n throw new OpenError('AEAD decryption failed', { cause })\n }\n state.seq = IncrementSeq(state.seq, state.max_seq)\n return pt\n } finally {\n release()\n }\n }\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n async Export(exporterContext , length ) {\n return await ContextExport(\n this.#state.suite,\n this.#state.exporter_secret,\n exporterContext,\n length,\n )\n }\n}\n \n\n \n \n \n\nconst validate = (factory , type ) => {\n try {\n const result = factory()\n if (result.type !== type) {\n throw new Error(`Invalid \"${type}\" return discriminator`)\n }\n return result\n } catch (cause) {\n throw new TypeError(`Invalid \"${type}\"`, { cause })\n }\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nexport class CipherSuite {\n #suite \n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n constructor(KEM , KDF , AEAD ) {\n const kem = validate(KEM, 'KEM')\n const kdf = validate(KDF, 'KDF')\n const aead = validate(AEAD, 'AEAD')\n\n this.#suite = {\n KEM: kem,\n KDF: kdf,\n AEAD: aead,\n id: concat(L_HPKE, I2OSP(kem.id, 2), I2OSP(kdf.id, 2), I2OSP(aead.id, 2)),\n }\n }\n\n \n\n\n\n\n get KEM() \n \n \n \n \n \n \n \n \n \n \n \n \n {\n return {\n id: this.#suite.KEM.id,\n name: this.#suite.KEM.name,\n Nsecret: this.#suite.KEM.Nsecret,\n Nenc: this.#suite.KEM.Nenc,\n Npk: this.#suite.KEM.Npk,\n Nsk: this.#suite.KEM.Nsk,\n }\n }\n\n \n\n\n\n\n get KDF() \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n {\n return {\n id: this.#suite.KDF.id,\n name: this.#suite.KDF.name,\n stages: this.#suite.KDF.stages,\n Nh: this.#suite.KDF.Nh,\n }\n }\n\n \n\n\n\n\n\n get AEAD() \n \n \n \n \n \n \n \n \n \n \n {\n return {\n id: this.#suite.AEAD.id,\n name: this.#suite.AEAD.name,\n Nk: this.#suite.AEAD.Nk,\n Nn: this.#suite.AEAD.Nn,\n Nt: this.#suite.AEAD.Nt,\n }\n }\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n async GenerateKeyPair(extractable ) {\n extractable ??= false\n checkExtractable(extractable)\n return await this.#suite.KEM.GenerateKeyPair(extractable)\n }\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n async DeriveKeyPair(ikm , extractable ) {\n extractable ??= false\n checkExtractable(extractable)\n checkUint8Array(ikm, 'ikm')\n if (ikm.byteLength < this.#suite.KEM.Nsk) {\n throw new DeriveKeyPairError('Insufficient \"ikm\" length')\n }\n try {\n return await this.#suite.KEM.DeriveKeyPair(ikm, extractable)\n } catch (cause) {\n if (cause instanceof NotSupportedError) {\n throw cause\n }\n throw new DeriveKeyPairError('Key derivation failed', { cause })\n }\n }\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n async SerializePrivateKey(privateKey ) {\n isKey(privateKey, 'private', true)\n\n return await this.#suite.KEM.SerializePrivateKey(privateKey)\n }\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n async SerializePublicKey(publicKey ) {\n isKey(publicKey, 'public', true)\n\n return await this.#suite.KEM.SerializePublicKey(publicKey)\n }\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n async DeserializePrivateKey(privateKey , extractable ) {\n extractable ??= false\n checkExtractable(extractable)\n checkUint8Array(privateKey, 'privateKey')\n\n try {\n if (privateKey.byteLength !== this.#suite.KEM.Nsk) {\n throw new Error('Invalid \"privateKey\" length')\n }\n return await this.#suite.KEM.DeserializePrivateKey(privateKey, extractable)\n } catch (cause) {\n if (cause instanceof NotSupportedError) {\n throw cause\n }\n throw new DeserializeError('Private key deserialization failed', { cause })\n }\n }\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n async DeserializePublicKey(publicKey ) {\n checkUint8Array(publicKey, 'publicKey')\n\n try {\n if (publicKey.byteLength !== this.#suite.KEM.Npk) {\n throw new Error('Invalid \"publicKey\" length')\n }\n return await this.#suite.KEM.DeserializePublicKey(publicKey)\n } catch (cause) {\n if (cause instanceof NotSupportedError) {\n throw cause\n }\n throw new DeserializeError('Public key deserialization failed', { cause })\n }\n }\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n async Seal(\n publicKey ,\n plaintext ,\n options ,\n ) {\n if (this.#suite.AEAD.id === EXPORT_ONLY) {\n throw new TypeError('Export-only AEAD cannot be used with Seal')\n }\n const { encapsulatedSecret, ctx } = await this.SetupSender(publicKey, options)\n const ciphertext = await ctx.Seal(plaintext, options?.aad)\n return { encapsulatedSecret, ciphertext }\n }\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n async Open(\n privateKey ,\n encapsulatedSecret ,\n ciphertext ,\n options ,\n ) {\n if (this.#suite.AEAD.id === EXPORT_ONLY) {\n throw new TypeError('Export-only AEAD cannot be used with Open')\n }\n const ctx = await this.SetupRecipient(privateKey, encapsulatedSecret, options)\n return await ctx.Open(ciphertext, options?.aad)\n }\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n async SendExport(\n publicKey ,\n exporterContext ,\n length ,\n options ,\n ) {\n const { encapsulatedSecret, ctx } = await this.SetupSender(publicKey, options)\n const exportedSecret = await ctx.Export(exporterContext, length)\n return { encapsulatedSecret, exportedSecret }\n }\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n async ReceiveExport(\n privateKey ,\n encapsulatedSecret ,\n exporterContext ,\n length ,\n options ,\n ) {\n const ctx = await this.SetupRecipient(privateKey, encapsulatedSecret, options)\n return await ctx.Export(exporterContext, length)\n }\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n async SetupSender(\n publicKey ,\n options ,\n ) {\n isKey(publicKey, 'public')\n\n let shared_secret \n let enc \n try {\n const result = await this.#suite.KEM.Encap(publicKey)\n shared_secret = result.shared_secret\n enc = result.enc\n } catch (cause) {\n if (cause instanceof ValidationError || cause instanceof NotSupportedError) {\n throw cause\n }\n throw new EncapError('Encapsulation failed', { cause })\n }\n\n const mode = options?.psk?.byteLength ? MODE_PSK : MODE_BASE\n const { key, base_nonce, exporter_secret } = await KeySchedule(\n this.#suite,\n mode,\n shared_secret,\n options?.info,\n options?.psk,\n options?.pskId,\n )\n\n const ctx = new SenderContext(this.#suite, mode, key, base_nonce, exporter_secret)\n return { encapsulatedSecret: enc, ctx }\n }\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n async SetupRecipient(\n privateKey ,\n encapsulatedSecret ,\n options ,\n ) {\n const { skR, pkR } = this.#extractRecipientKeys(privateKey)\n checkUint8Array(encapsulatedSecret, 'encapsulatedSecret')\n if (encapsulatedSecret.byteLength !== this.#suite.KEM.Nenc) {\n throw new DecapError('Invalid encapsulated secret length')\n }\n\n let shared_secret \n try {\n shared_secret = await this.#suite.KEM.Decap(encapsulatedSecret, skR, pkR)\n } catch (cause) {\n if (cause instanceof ValidationError || cause instanceof NotSupportedError) {\n throw cause\n }\n throw new DecapError('Decapsulation failed', { cause })\n }\n\n const mode = options?.psk?.byteLength ? MODE_PSK : MODE_BASE\n const { key, base_nonce, exporter_secret } = await KeySchedule(\n this.#suite,\n mode,\n shared_secret,\n options?.info,\n options?.psk,\n options?.pskId,\n )\n\n return new RecipientContext(this.#suite, mode, key, base_nonce, exporter_secret)\n }\n\n #extractRecipientKeys(skR ) {\n if (isKeyPair(skR)) {\n return { skR: skR.privateKey, pkR: skR.publicKey }\n }\n\n isKey(skR, 'private')\n return { skR, pkR: undefined }\n }\n}\n\n \n \n \n\n\n\n\n\n\n\nexport class ValidationError extends Error {\n constructor(message , options ) {\n super(message, options)\n this.name = 'ValidationError'\n \n Error.captureStackTrace?.(this, ValidationError)\n }\n}\n\n\n\n\n\n\n\nexport class DeserializeError extends Error {\n constructor(message , options ) {\n super(message, options)\n this.name = 'DeserializeError'\n \n Error.captureStackTrace?.(this, DeserializeError)\n }\n}\n\n\n\n\n\n\n\nexport class EncapError extends Error {\n constructor(message , options ) {\n super(message, options)\n this.name = 'EncapError'\n \n Error.captureStackTrace?.(this, EncapError)\n }\n}\n\n\n\n\n\n\n\nexport class DecapError extends Error {\n constructor(message , options ) {\n super(message, options)\n this.name = 'DecapError'\n \n Error.captureStackTrace?.(this, DecapError)\n }\n}\n\n\n\n\n\n\n\nexport class OpenError extends Error {\n constructor(message , options ) {\n super(message, options)\n this.name = 'OpenError'\n \n Error.captureStackTrace?.(this, OpenError)\n }\n}\n\n\n\n\n\n\n\nexport class MessageLimitReachedError extends Error {\n constructor(message , options ) {\n super(message, options)\n this.name = 'MessageLimitReachedError'\n \n Error.captureStackTrace?.(this, MessageLimitReachedError)\n }\n}\n\n\n\n\n\n\n\nexport class DeriveKeyPairError extends Error {\n constructor(message , options ) {\n super(message, options)\n this.name = 'DeriveKeyPairError'\n \n Error.captureStackTrace?.(this, DeriveKeyPairError)\n }\n}\n\n\n\n\n\n\n\nexport class NotSupportedError extends Error {\n constructor(message , options ) {\n super(message, options)\n this.name = 'NotSupportedError'\n \n Error.captureStackTrace?.(this, NotSupportedError)\n }\n}\n\n \n \n \n\n \n \n \n \n \n \n\n\n\n\n\n\n\n\n\nexport const MODE_BASE = 0x00\n\n\n\n\n\n\n\n\n\n\nexport const MODE_PSK = 0x01\n\n \n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n\n \n \n\n \n \n \n\n\n\n\n\n\n\n\n \n \n \n \n \n\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n\n \n \n \n\n\n\n\n\n\n\n\n\n\nexport function concat(...buffers ) {\n const size = buffers.reduce((acc, { length }) => acc + length, 0)\n const buf = new Uint8Array(size)\n let i = 0\n for (const buffer of buffers) {\n buf.set(buffer, i)\n i += buffer.length\n }\n return buf\n}\n\nfunction slice(buffer , start , end ) {\n return Uint8Array.prototype.slice.call(buffer, start, end)\n}\n\n\n\n\n\n\n\n\n\n\n\n\nexport function encode(string ) {\n const bytes = new Uint8Array(string.length)\n for (let i = 0; i < string.length; i++) {\n const code = string.charCodeAt(i)\n if (code > 0x7f) {\n throw new TypeError('Input string must contain only ASCII characters')\n }\n bytes[i] = code\n }\n return bytes\n}\n\n \n \n \n \nconst L_HPKE_v1 = /* @__PURE__ */ encode('HPKE-v1')\nconst L_HPKE = /* @__PURE__ */ encode('HPKE')\nconst L_KEM = /* @__PURE__ */ encode('KEM')\nconst L_sec = /* @__PURE__ */ encode('sec')\nconst L_secret = /* @__PURE__ */ encode('secret')\nconst L_key = /* @__PURE__ */ encode('key')\nconst L_base_nonce = /* @__PURE__ */ encode('base_nonce')\nconst L_exp = /* @__PURE__ */ encode('exp')\nconst L_psk_id_hash = /* @__PURE__ */ encode('psk_id_hash')\nconst L_info_hash = /* @__PURE__ */ encode('info_hash')\nconst L_dkp_prk = /* @__PURE__ */ encode('dkp_prk')\nconst L_candidate = /* @__PURE__ */ encode('candidate')\nconst L_eae_prk = /* @__PURE__ */ encode('eae_prk')\nconst L_shared_secret = /* @__PURE__ */ encode('shared_secret')\nconst L_sk = /* @__PURE__ */ encode('sk')\nconst L_public_key_recovery = /* @__PURE__ */ encode('HPKE public key recovery')\nconst L_DeriveKeyPair = /* @__PURE__ */ encode('DeriveKeyPair')\n\nfunction lengthPrefixed(x ) {\n return concat(I2OSP(x.byteLength, 2), x)\n}\n\n \n \n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nexport async function LabeledDerive(\n KDF ,\n suite_id ,\n ikm ,\n label ,\n context ,\n L ,\n) {\n const labeled_ikm = concat(ikm, L_HPKE_v1, suite_id, lengthPrefixed(label), I2OSP(L, 2), context)\n return await KDF.Derive(labeled_ikm, L)\n}\n\n \nasync function Export_OneStage(\n KDF ,\n suite_id ,\n exporter_secret ,\n exporter_context ,\n L ,\n) {\n checkLength(exporter_context, 'Exporter context', MAX_LENGTH_ONE_STAGE)\n return await LabeledDerive(KDF, suite_id, exporter_secret, L_sec, exporter_context, L)\n}\n\n \nasync function CombineSecrets_OneStage(\n suite ,\n mode ,\n shared_secret ,\n info ,\n psk ,\n psk_id ,\n) {\n checkLength(psk, 'PSK', MAX_LENGTH_ONE_STAGE)\n checkLength(psk_id, 'PSK ID', MAX_LENGTH_ONE_STAGE)\n checkLength(info, 'Info', MAX_LENGTH_ONE_STAGE)\n\n const secrets = concat(lengthPrefixed(psk), lengthPrefixed(shared_secret))\n const context = concat(I2OSP(mode, 1), lengthPrefixed(psk_id), lengthPrefixed(info))\n\n const secret = await LabeledDerive(\n suite.KDF,\n suite.id,\n secrets,\n L_secret,\n context,\n suite.AEAD.Nk + suite.AEAD.Nn + suite.KDF.Nh,\n )\n\n const key = slice(secret, 0, suite.AEAD.Nk)\n const base_nonce = slice(secret, suite.AEAD.Nk, suite.AEAD.Nk + suite.AEAD.Nn)\n const exporter_secret = slice(secret, suite.AEAD.Nk + suite.AEAD.Nn)\n\n return { key, base_nonce, exporter_secret }\n}\n\n \n \nconst MAX_LENGTH_TWO_STAGE = 0xffff\n \nconst MAX_LENGTH_ONE_STAGE = 0xffff\n\nfunction checkLength(data , name , maxLength ) {\n if (data.byteLength > maxLength) {\n throw new TypeError(`${name} length must not exceed ${maxLength} bytes`)\n }\n}\nfunction checkUint8Array(input , name ) {\n if (!(input instanceof Uint8Array)) {\n throw new TypeError(`\"${name}\" must be Uint8Array`)\n }\n if (typeof SharedArrayBuffer !== 'undefined' && input.buffer instanceof SharedArrayBuffer) {\n throw new TypeError(`\"${name}\" must not be backed by a SharedArrayBuffer`)\n }\n}\nfunction checkExtractable(extractable ) {\n if (typeof extractable !== 'boolean') {\n throw new TypeError('\"extractable\" must be boolean')\n }\n}\n\n \nasync function CombineSecrets_TwoStage(\n suite ,\n mode ,\n shared_secret ,\n info ,\n psk ,\n psk_id ,\n) {\n checkLength(psk, 'PSK', MAX_LENGTH_TWO_STAGE)\n checkLength(psk_id, 'PSK ID', MAX_LENGTH_TWO_STAGE)\n checkLength(info, 'Info', MAX_LENGTH_TWO_STAGE)\n\n const [psk_id_hash, info_hash] = await Promise.all([\n LabeledExtract(suite.KDF, suite.id, new Uint8Array(), L_psk_id_hash, psk_id),\n LabeledExtract(suite.KDF, suite.id, new Uint8Array(), L_info_hash, info),\n ])\n\n const key_schedule_context = concat(I2OSP(mode, 1), psk_id_hash, info_hash)\n const secret = await LabeledExtract(suite.KDF, suite.id, shared_secret, L_secret, psk)\n\n \n if (suite.AEAD.id === EXPORT_ONLY) {\n const exporter_secret = await LabeledExpand(\n suite.KDF,\n suite.id,\n secret,\n L_exp,\n key_schedule_context,\n suite.KDF.Nh,\n )\n return { key: new Uint8Array(), base_nonce: new Uint8Array(), exporter_secret }\n }\n\n const [key, base_nonce, exporter_secret] = await Promise.all([\n LabeledExpand(suite.KDF, suite.id, secret, L_key, key_schedule_context, suite.AEAD.Nk),\n LabeledExpand(suite.KDF, suite.id, secret, L_base_nonce, key_schedule_context, suite.AEAD.Nn),\n LabeledExpand(suite.KDF, suite.id, secret, L_exp, key_schedule_context, suite.KDF.Nh),\n ])\n\n return { key, base_nonce, exporter_secret }\n}\n\n \nasync function Export_TwoStage(\n KDF ,\n suite_id ,\n exporter_secret ,\n exporter_context ,\n L ,\n) {\n checkLength(exporter_context, 'Exporter context', MAX_LENGTH_TWO_STAGE)\n return await LabeledExpand(KDF, suite_id, exporter_secret, L_sec, exporter_context, L)\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n\n \n \n\n \n \n\n \n \n \n \n \n \n\n \n \n\n \n \n \n \n \n \n \n \n \n\n \n \n \n \n \n \n \n \n \n \n\n \n \n \n \n \n \n \n \n \n \n\n \n \n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nexport async function LabeledExtract(\n KDF ,\n suite_id ,\n salt ,\n label ,\n ikm ,\n) {\n const labeled_ikm = concat(L_HPKE_v1, suite_id, label, ikm)\n return await KDF.Extract(salt, labeled_ikm)\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nexport async function LabeledExpand(\n KDF ,\n suite_id ,\n prk ,\n label ,\n info ,\n L ,\n) {\n const labeled_info = concat(I2OSP(L, 2), L_HPKE_v1, suite_id, label, info)\n return await KDF.Expand(prk, labeled_info, L)\n}\n\n \n \n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n\n \n \n\n \n \n\n \n \n\n \n \n\n \n \n\n \n \n\n \n \n \n \n \n \n \n \n \n\n \n \n \n \n \n \n \n \n\n \n \n \n \n \n \n \n \n\n \n \n \n \n \n \n \n \n\n \n \n \n \n \n \n \n \n\n \n \n \n \n \n \n \n \n \n\n \n \n \n \n \n \n \n \n \n \n \n \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\nfunction isKeyPair (skR ) {\n if (!skR || typeof skR !== 'object') return false\n if ('publicKey' in skR && 'privateKey' in skR) {\n const pkR = skR.publicKey\n skR = skR.privateKey\n try {\n isKey(pkR, 'public')\n isKey(skR, 'private')\n if (pkR.algorithm.name !== skR.algorithm.name) {\n throw new TypeError('key pair algorithms do not match')\n }\n } catch (cause) {\n throw new TypeError('Invalid \"privateKey\"', { cause })\n }\n return true\n }\n return false\n}\n\nfunction isKey(key , type , extractable ) {\n const k = key \n if (\n typeof k.algorithm !== 'object' ||\n typeof k.algorithm.name !== 'string' ||\n typeof k.extractable !== 'boolean' ||\n typeof k.type !== 'string' ||\n k.type !== type\n ) {\n throw new TypeError(`Invalid \"${type}Key\"`)\n }\n\n if (extractable && k.extractable !== true) {\n throw new TypeError(`\"${type}Key\" must be extractable`)\n }\n}\n\n \n \n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n\n \n \n\n \n \n\n \n \n\n \n \n\n \n \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n \n \n \n \n \n \n \n \n \n \n \n \n\n \n \n \n\n\n\n\n\n\n\n\n\n\n\n\n\nexport function I2OSP(n , w ) {\n if (!Number.isSafeInteger(w) || w <= 0) {\n throw new Error('w must be a positive safe integer')\n }\n if (!Number.isSafeInteger(n) || n < 0) {\n throw new Error('n must be a non-negative safe integer')\n }\n const max = Math.pow(256, w)\n if (n >= max) {\n throw new Error('n too large to fit in w-length byte string')\n }\n const ret = new Uint8Array(w)\n let num = n\n for (let i = 0; i < w && num; i++) {\n ret[w - (i + 1)] = num % 256\n num = Math.floor(num / 256)\n }\n return ret\n}\n\nfunction KDFStages(KDF ) {\n if (KDF.stages === 1 || KDF.stages === 2) {\n return KDF.stages\n }\n \n throw new Error('unreachable')\n}\n\n \nasync function KeySchedule(\n suite ,\n mode ,\n shared_secret ,\n info ,\n psk ,\n pskId ,\n) {\n info ??= new Uint8Array()\n checkUint8Array(info, 'info')\n psk ??= new Uint8Array()\n checkUint8Array(psk, 'psk')\n pskId ??= new Uint8Array()\n checkUint8Array(pskId, 'pskId')\n\n const stages = KDFStages(suite.KDF)\n const CombineSecrets = stages === 1 ? CombineSecrets_OneStage : CombineSecrets_TwoStage\n\n VerifyPSKInputs(psk, pskId)\n return await CombineSecrets(suite, mode, shared_secret, info, psk, pskId)\n}\n\n \nfunction VerifyPSKInputs(psk , psk_id ) {\n if (psk.byteLength && psk_id.byteLength) {\n if (psk.byteLength < 32) {\n throw new TypeError('Insufficient PSK length')\n }\n return\n }\n if (!psk.byteLength && !psk_id.byteLength) {\n return\n }\n throw new TypeError('Inconsistent PSK inputs')\n}\n\n \nconst NotApplicable = () => {\n throw new Error('unreachable')\n}\n\nconst EXPORT_ONLY = 0xffff\nconst AES_GCM_P_MAX = 2 ** 36 - 31\nconst CHACHA20_POLY1305_P_MAX = 2 ** 38 - 64\n\n\n\n\n\n\n\n\n\n\n\n\nexport const AEAD_EXPORT_ONLY = function () {\n return {\n id: EXPORT_ONLY,\n type: 'AEAD',\n name: 'Export-only',\n Nk: 0,\n Nn: 0,\n Nt: 0,\n Seal: NotApplicable,\n Open: NotApplicable,\n }\n}\n\n \n \n \n\nasync function subtle (promise , name ) {\n try {\n return await promise(crypto.subtle)\n } catch (cause) {\n if (\n cause instanceof TypeError ||\n (cause instanceof DOMException && cause.name === 'NotSupportedError')\n ) {\n throw new NotSupportedError(`${name} is unsupported in this runtime`, { cause })\n }\n throw cause\n }\n}\n\n \n \n \n\n \n\n \n \n \n \n\nasync function getCachedCryptoKey(\n cache ,\n keyBytes ,\n init ,\n) {\n const cached = cache.get(keyBytes)\n if (\n cached &&\n cached.bytes.byteLength === keyBytes.byteLength &&\n cached.bytes.every((byte, index) => byte === keyBytes[index])\n ) {\n return cached.key\n }\n\n const bytes = slice(keyBytes)\n const entry = { bytes, key: init(bytes) }\n cache.set(keyBytes, entry)\n try {\n return await entry.key\n } catch (cause) {\n if (cache.get(keyBytes) === entry) cache.delete(keyBytes)\n throw cause\n }\n}\n\nfunction HKDF_SHARED() {\n let emptySalt \n async function importKey( salt ) {\n return await subtle(\n (c) => c.importKey('raw', salt, { name: 'HMAC', hash: this.hash }, false, ['sign']),\n this.name,\n )\n }\n const cache = new WeakMap ()\n return {\n stages: 2,\n Derive: NotApplicable,\n async Extract( salt, ikm) {\n const key =\n salt.byteLength === 0\n ? (emptySalt ??= await importKey.call(this, new ArrayBuffer(this.Nh)))\n : await importKey.call(this, salt )\n return new Uint8Array(\n await subtle((c) => c.sign('HMAC', key, ikm ), this.name),\n )\n },\n async Expand( prk, info, L) {\n if (prk.byteLength < this.Nh) {\n throw new Error('prk.byteLength < this.Nh')\n }\n if (L > 255 * this.Nh) {\n throw new Error('L must be <= 255*Nh')\n }\n const N = Math.ceil(L / this.Nh)\n const key = await getCachedCryptoKey(cache, prk, (bytes) =>\n importKey.call(this, bytes ),\n )\n\n const T = new Uint8Array(N * this.Nh)\n let T_prev = new Uint8Array()\n\n for (let i = 0; i < N; i++) {\n const input = new Uint8Array(T_prev.byteLength + info.byteLength + 1)\n input.set(T_prev)\n input.set(info, T_prev.byteLength)\n input[T_prev.byteLength + info.byteLength] = i + 1\n\n const T_i = new Uint8Array(await subtle((c) => c.sign('HMAC', key, input), this.name))\n\n T.set(T_i, i * this.Nh)\n T_prev = T_i\n }\n\n return slice(T, 0, L)\n },\n }\n}\n\n \n \n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nexport const KDF_HKDF_SHA256 = function () {\n return { id: 0x0001, type: 'KDF', name: 'HKDF-SHA256', Nh: 32, hash: 'SHA-256', ...HKDF_SHARED() }\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nexport const KDF_HKDF_SHA384 = function () {\n return { id: 0x0002, type: 'KDF', name: 'HKDF-SHA384', Nh: 48, hash: 'SHA-384', ...HKDF_SHARED() }\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nexport const KDF_HKDF_SHA512 = function () {\n return { id: 0x0003, type: 'KDF', name: 'HKDF-SHA512', Nh: 64, hash: 'SHA-512', ...HKDF_SHARED() }\n}\n\n \n \n \n\n \n \n \n\nasync function ShakeDerive(name , variant , ikm , L ) {\n const bits = L << 3\n const alg = { name: variant, length: bits, outputLength: bits }\n return new Uint8Array(await subtle((c) => c.digest(alg, ikm), name))\n}\n\nfunction SHAKE_SHARED() {\n return {\n stages: 1,\n async Derive( labeled_ikm, L ) {\n return await ShakeDerive(this.name, this.algorithm, labeled_ikm , L)\n },\n Extract: NotApplicable,\n Expand: NotApplicable,\n }\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nexport const KDF_SHAKE128 = function () {\n return {\n id: 0x0010,\n type: 'KDF',\n name: 'SHAKE128',\n Nh: 32,\n algorithm: 'cSHAKE128',\n ...SHAKE_SHARED(),\n }\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nexport const KDF_SHAKE256 = function () {\n return {\n id: 0x0011,\n type: 'KDF',\n name: 'SHAKE256',\n Nh: 64,\n algorithm: 'cSHAKE256',\n ...SHAKE_SHARED(),\n }\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nexport const KDF_TurboSHAKE128 = function () {\n return {\n id: 0x0012,\n type: 'KDF',\n name: 'TurboSHAKE128',\n Nh: 32,\n algorithm: 'TurboSHAKE128',\n ...SHAKE_SHARED(),\n }\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nexport const KDF_TurboSHAKE256 = function () {\n return {\n id: 0x0013,\n type: 'KDF',\n name: 'TurboSHAKE256',\n Nh: 64,\n algorithm: 'TurboSHAKE256',\n ...SHAKE_SHARED(),\n }\n}\n\nasync function getPublicKeyByExport(\n name ,\n key ,\n usages ,\n) {\n if (!key.extractable) {\n throw new TypeError(\n '\"privateKey\" must be extractable or a Key Pair must be used in this runtime',\n )\n }\n\n return await subtle(async (c) => {\n const jwk = await c.exportKey('jwk', key)\n return c.importKey(\n 'jwk',\n { kty: jwk.kty, crv: jwk.crv, x: jwk.x, y: jwk.y } ,\n key.algorithm,\n true,\n usages,\n )\n }, name)\n}\n\nasync function getPublicKey(name , key , usages ) {\n return (\n \n ((await subtle((c) => c.getPublicKey?.(key, usages), name)) ) ||\n (await getPublicKeyByExport(name, key, usages))\n )\n}\n\n \n \n \n \n \n \n \n \n \n \n \n\n \n \n \n \n \n \n\nfunction fromBase64(input ) {\n input = input.replace(/-/g, '+').replace(/_/g, '/')\n const binary = atob(input)\n const bytes = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i)\n }\n return bytes\n}\n\nfunction toBase64Url(bytes ) {\n let binary = ''\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i] )\n }\n return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '')\n}\n\nfunction toB64u(input ) {\n \n return input.toBase64?.({ alphabet: 'base64url', omitPadding: true }) || toBase64Url(input)\n}\n\nfunction b64u(input ) {\n \n return Uint8Array.fromBase64?.(input, { alphabet: 'base64url' }) || fromBase64(input)\n}\n\n \n \n \n\n \nasync function DeriveKeyPairBytes(\n DHKEM ,\n ikm ,\n label ,\n context ,\n) {\n if (KDFStages(DHKEM.kdf) === 1) {\n return await LabeledDerive(DHKEM.kdf, DHKEM.suite_id, ikm, label, context, DHKEM.Nsk)\n }\n\n const dkp_prk = await LabeledExtract(DHKEM.kdf, DHKEM.suite_id, new Uint8Array(), L_dkp_prk, ikm)\n return await LabeledExpand(DHKEM.kdf, DHKEM.suite_id, dkp_prk, label, context, DHKEM.Nsk)\n}\n\nfunction OS2IP(x ) {\n let result = 0n\n for (let i = 0; i < x.byteLength; i++) {\n result = result * 256n + BigInt(x[i] )\n }\n return result\n}\n\nfunction bigIntToUint8Array(value , byteLength ) {\n const result = new Uint8Array(byteLength)\n let n = value\n\n for (let i = byteLength - 1; i >= 0; i--) {\n result[i] = Number(n & 0xffn)\n n = n >> 8n\n }\n\n return result\n}\n\nfunction assertKeyAlgorithm(key , expectedAlgorithm ) {\n if (key.algorithm.name !== expectedAlgorithm.name) {\n throw new TypeError(`key algorithm must be ${expectedAlgorithm.name}`)\n }\n if (\n (key.algorithm ).namedCurve !==\n (expectedAlgorithm ).namedCurve\n ) {\n throw new TypeError(\n `key namedCurve must be ${(expectedAlgorithm ).namedCurve}`,\n )\n }\n}\n\nfunction assertCryptoKey(key ) {\n \n if (key[Symbol.toStringTag] !== 'CryptoKey') {\n if (key instanceof CryptoKey) return\n throw new TypeError('unexpected key constructor')\n }\n}\n\n \nasync function ExtractAndExpand_OneStage(\n DHKEM ,\n dh ,\n kem_context ,\n) {\n return await LabeledDerive(\n DHKEM.kdf,\n DHKEM.suite_id,\n dh,\n L_shared_secret,\n kem_context,\n DHKEM.Nsecret,\n )\n}\n\n \nasync function ExtractAndExpand_TwoStage(\n DHKEM ,\n dh ,\n kem_context ,\n) {\n const eae_prk = await LabeledExtract(DHKEM.kdf, DHKEM.suite_id, new Uint8Array(), L_eae_prk, dh)\n return await LabeledExpand(\n DHKEM.kdf,\n DHKEM.suite_id,\n eae_prk,\n L_shared_secret,\n kem_context,\n DHKEM.Nsecret,\n )\n}\n\n \nasync function ExtractAndExpand(\n DHKEM ,\n dh ,\n kem_context ,\n) {\n const Fn = KDFStages(DHKEM.kdf) === 1 ? ExtractAndExpand_OneStage : ExtractAndExpand_TwoStage\n return await Fn(DHKEM, dh, kem_context)\n}\n\n \n \n \n\nfunction DHKEM_SHARED() \n \n {\n return {\n async GenerateKeyPair( extractable) {\n return (await subtle(\n (c) => c.generateKey(this.algorithm, extractable, ['deriveBits']),\n this.name,\n )) \n },\n async SerializePublicKey( key) {\n assertKeyAlgorithm(key, this.algorithm)\n assertCryptoKey(key)\n return new Uint8Array(await subtle((c) => c.exportKey('raw', key), this.name))\n },\n async DeserializePublicKey( key) {\n return await subtle(\n (c) => c.importKey('raw', key , this.algorithm, true, []),\n this.name,\n )\n },\n async SerializePrivateKey( key) {\n assertKeyAlgorithm(key, this.algorithm)\n assertCryptoKey(key)\n const { d } = await subtle((c) => c.exportKey('jwk', key), this.name)\n return b64u(d )\n },\n async Encap( pkR) {\n assertKeyAlgorithm(pkR, this.algorithm)\n assertCryptoKey(pkR)\n\n const ekp = (await this.GenerateKeyPair(false)) \n const skE = ekp.privateKey\n const pkE = ekp.publicKey\n\n \n \n const dh = new Uint8Array(\n await subtle(\n (c) => c.deriveBits({ name: skE.algorithm.name, public: pkR }, skE, this.Ndh << 3),\n this.name,\n ),\n )\n\n const enc = await this.SerializePublicKey(pkE)\n const pkRm = await this.SerializePublicKey(pkR)\n const kem_context = concat(enc, pkRm)\n const shared_secret = await ExtractAndExpand(this, dh, kem_context)\n return { shared_secret, enc }\n },\n async Decap( enc, skR, pkR) {\n assertKeyAlgorithm(skR, this.algorithm)\n assertCryptoKey(skR)\n if (pkR) {\n assertKeyAlgorithm(pkR, this.algorithm)\n assertCryptoKey(pkR)\n } else {\n pkR = await getPublicKey(this.name, skR, [])\n }\n\n const pkE = (await this.DeserializePublicKey(enc)) \n\n \n \n const dh = new Uint8Array(\n await subtle(\n (c) => c.deriveBits({ name: skR.algorithm.name, public: pkE }, skR, this.Ndh << 3),\n this.name,\n ),\n )\n\n const pkRm = await this.SerializePublicKey(pkR)\n const kem_context = concat(enc, pkRm)\n const shared_secret = await ExtractAndExpand(this, dh, kem_context)\n return shared_secret\n },\n }\n}\n\n \n \n \n\nasync function createKeyPairFromPrivateKey(\n DHKEM ,\n key ,\n extractable ,\n) {\n let privateKey \n let publicKey \n \n if (!extractable && typeof crypto.subtle.getPublicKey !== 'function') {\n privateKey = (await DHKEM.DeserializePrivateKey(key, true)) \n publicKey = await getPublicKey(DHKEM.name, privateKey, [])\n privateKey = (await DHKEM.DeserializePrivateKey(key, false)) \n } else {\n privateKey = (await DHKEM.DeserializePrivateKey(key, extractable)) \n publicKey = await getPublicKey(DHKEM.name, privateKey, [])\n }\n return { privateKey, publicKey }\n}\n\nasync function CurveKeyFromD(\n name ,\n Nsk ,\n template ,\n algorithm ,\n key ,\n extractable ,\n) {\n const tmpl = slice(template)\n const pkcs8 = new Uint8Array(Nsk + tmpl.byteLength)\n pkcs8.set(tmpl)\n pkcs8.set(key, tmpl.byteLength)\n return await subtle(\n (c) => c.importKey('pkcs8', pkcs8, algorithm, extractable, ['deriveBits']),\n name,\n )\n}\n\n \n \n \n\n \n \n \n \n \n \n \n \n \n \n \n\nasync function importKeyNist(\n curve ,\n key ,\n name ,\n extractable ,\n includePublicKey ,\n) {\n const d = OS2IP(key)\n if (d === 0n || d >= curve.order) {\n throw new Error('Invalid scalar')\n }\n\n \n const pkcs8 = concat(curve.pkcs8, key)\n return await subtle(async (c) => {\n async function fromJwk(jwk , privateKey ) {\n privateKey ??= await c.importKey('jwk', jwk, curve.algorithm, extractable, ['deriveBits'])\n delete jwk.d\n return {\n privateKey,\n publicKey: includePublicKey\n ? await c.importKey('jwk', jwk, curve.algorithm, true, [])\n : undefined,\n }\n }\n\n let privateKey \n \n const nativePublicKey = typeof c.getPublicKey === 'function'\n try {\n privateKey = await c.importKey(\n 'pkcs8',\n pkcs8 ,\n curve.algorithm,\n nativePublicKey ? extractable : true,\n ['deriveBits'],\n )\n if (nativePublicKey) {\n \n \n const recovered = await c.getPublicKey(privateKey, [])\n return { privateKey, publicKey: includePublicKey ? recovered : undefined }\n }\n const { x, y, d } = await c.exportKey('jwk', privateKey)\n return fromJwk(\n { kty: 'EC', crv: curve.algorithm.namedCurve, x, y, d },\n extractable ? privateKey : undefined,\n )\n } catch (cause) {\n \n \n \n \n if (\n !(cause instanceof DOMException) ||\n (cause.name !== 'DataError' && cause.name !== 'OperationError')\n ) {\n throw cause\n }\n }\n\n const generator = {\n kty: 'EC',\n crv: curve.algorithm.namedCurve,\n x: toB64u(bigIntToUint8Array(curve.Gx, curve.Nsk)),\n y: toB64u(bigIntToUint8Array(curve.Gy, curve.Nsk)),\n }\n const jwk = { ...generator, d: toB64u(slice(pkcs8, curve.pkcs8.length)) }\n const signingAlgorithm = { name: 'ECDSA', namedCurve: curve.algorithm.namedCurve }\n const signingKey = privateKey\n ? await c.importKey('pkcs8', pkcs8 , signingAlgorithm, false, ['sign'])\n : await c.importKey('jwk', jwk, signingAlgorithm, false, ['sign'])\n privateKey ??= await c.importKey('jwk', jwk, curve.algorithm, false, ['deriveBits'])\n\n \n \n const generatorKey = await c.importKey('jwk', generator, curve.algorithm, true, [])\n const x = new Uint8Array(\n await c.deriveBits({ name: 'ECDH', public: generatorKey }, privateKey, curve.Nsk << 3),\n )\n\n \n \n const message = L_public_key_recovery \n const signatureAlgorithm = { name: 'ECDSA', hash: 'SHA-256' }\n const signature = await c.sign(signatureAlgorithm, signingKey, message)\n for (const prefix of [0x02, 0x03]) {\n const spki = concat(curve.spki, Uint8Array.of(prefix), x)\n const candidate = await c.importKey('spki', spki , signingAlgorithm, true, [\n 'verify',\n ])\n if (await c.verify(signatureAlgorithm, candidate, signature, message)) {\n const { x, y } = await c.exportKey('jwk', candidate)\n return fromJwk({ kty: 'EC', crv: generator.crv, d: jwk.d, x, y })\n }\n }\n throw new Error('Public key recovery failed')\n }, name)\n}\n\nasync function DeserializePrivateKeyNist(\n \n key ,\n extractable ,\n) {\n return (await importKeyNist(this, key, this.name, extractable, false)).privateKey\n}\n\n \nasync function DeriveKeyPairNist(\n \n ikm ,\n extractable ,\n) {\n let sk = 0n\n let counter = 0\n let candidate \n while (sk === 0n || sk >= this.order) {\n if (counter > 255) {\n throw new DeriveKeyPairError('Key derivation exceeded maximum iterations')\n }\n candidate = await DeriveKeyPairBytes(this, ikm, L_candidate, I2OSP(counter, 1))\n candidate[0] = candidate[0] & this.bitmask\n sk = OS2IP(candidate)\n counter = counter + 1\n }\n\n return GetKeyPairNist(this, candidate , extractable, this.name)\n}\n\nasync function GetKeyPairNist(\n curveConfig ,\n sk ,\n extractable ,\n name ,\n) {\n return (await importKeyNist(curveConfig, sk, name, extractable, true)) \n}\n\n \n \n \n\n \nasync function DeriveKeyPairX( ikm , extractable ) {\n const sk = await DeriveKeyPairBytes(this, ikm, L_sk, new Uint8Array())\n return await createKeyPairFromPrivateKey(this, sk, extractable)\n}\n\n \n \n \n\nconst P256 = {\n algorithm: { name: 'ECDH', namedCurve: 'P-256' },\n Npk: 65,\n Nsk: 32,\n order: 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n,\n bitmask: 0xff,\n pkcs8: /* @__PURE__ */ Uint8Array.of(0x30, 0x41, 0x02, 0x01, 0x00, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x04, 0x27, 0x30, 0x25, 0x02, 0x01, 0x01, 0x04, 0x20), \n spki: /* @__PURE__ */ Uint8Array.of(0x30, 0x39, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x22, 0x00), \n Gx: 0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296n,\n Gy: 0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5n,\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nexport const KEM_DHKEM_P256_HKDF_SHA256 = function () \n {\n const id = 0x0010\n const name = 'DHKEM(P-256, HKDF-SHA256)'\n const kdf = KDF_HKDF_SHA256()\n \n kdf.name = name\n return {\n id,\n suite_id: concat(L_KEM, I2OSP(id, 2)),\n type: 'KEM',\n name,\n kdf,\n Nsecret: 32,\n Nenc: 65,\n Ndh: 32,\n ...P256,\n DeriveKeyPair: DeriveKeyPairNist,\n DeserializePrivateKey: DeserializePrivateKeyNist,\n ...DHKEM_SHARED(),\n }\n}\n\nconst P384 = {\n algorithm: { name: 'ECDH', namedCurve: 'P-384' },\n Npk: 97,\n Nsk: 48,\n order:\n 0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973n,\n bitmask: 0xff,\n pkcs8: /* @__PURE__ */ Uint8Array.of(0x30, 0x4e, 0x02, 0x01, 0x00, 0x30, 0x10, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x22, 0x04, 0x37, 0x30, 0x35, 0x02, 0x01, 0x01, 0x04, 0x30), \n spki: /* @__PURE__ */ Uint8Array.of(0x30, 0x46, 0x30, 0x10, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x22, 0x03, 0x32, 0x00), \n Gx: 0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7n,\n Gy: 0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5fn,\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nexport const KEM_DHKEM_P384_HKDF_SHA384 = function () \n {\n const id = 0x0011\n const name = 'DHKEM(P-384, HKDF-SHA384)'\n const kdf = KDF_HKDF_SHA384()\n \n kdf.name = name\n return {\n id,\n suite_id: concat(L_KEM, I2OSP(id, 2)),\n type: 'KEM',\n name,\n kdf,\n Nsecret: 48,\n Nenc: 97,\n Ndh: 48,\n ...P384,\n DeriveKeyPair: DeriveKeyPairNist,\n DeserializePrivateKey: DeserializePrivateKeyNist,\n ...DHKEM_SHARED(),\n }\n}\n\nconst P521 = {\n Npk: 133,\n Nsk: 66,\n algorithm: { name: 'ECDH', namedCurve: 'P-521' },\n order:\n 0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409n,\n bitmask: 0x01,\n pkcs8: /* @__PURE__ */ Uint8Array.of(0x30, 0x60, 0x02, 0x01, 0x00, 0x30, 0x10, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x23, 0x04, 0x49, 0x30, 0x47, 0x02, 0x01, 0x01, 0x04, 0x42), \n spki: /* @__PURE__ */ Uint8Array.of(0x30, 0x58, 0x30, 0x10, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x23, 0x03, 0x44, 0x00), \n Gx: 0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66n,\n Gy: 0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650n,\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nexport const KEM_DHKEM_P521_HKDF_SHA512 = function () \n {\n const id = 0x0012\n const name = 'DHKEM(P-521, HKDF-SHA512)'\n const kdf = KDF_HKDF_SHA512()\n \n kdf.name = name\n return {\n id,\n suite_id: concat(L_KEM, I2OSP(id, 2)),\n type: 'KEM',\n name,\n kdf,\n Nsecret: 64,\n Nenc: 133,\n Ndh: 66,\n ...P521,\n DeriveKeyPair: DeriveKeyPairNist,\n DeserializePrivateKey: DeserializePrivateKeyNist,\n ...DHKEM_SHARED(),\n }\n}\n\n \n \n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nexport const KEM_DHKEM_X25519_HKDF_SHA256 = function () \n \n {\n const id = 0x0020\n const name = 'DHKEM(X25519, HKDF-SHA256)'\n const kdf = KDF_HKDF_SHA256()\n \n kdf.name = name\n return {\n id,\n suite_id: concat(L_KEM, I2OSP(id, 2)),\n type: 'KEM',\n name,\n kdf,\n Nsecret: 32,\n Nenc: 32,\n Npk: 32,\n Nsk: 32,\n Ndh: 32,\n algorithm: { name: 'X25519' },\n pkcs8: Uint8Array.of(0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e, 0x04, 0x22, 0x04, 0x20), \n DeriveKeyPair: DeriveKeyPairX,\n async DeserializePrivateKey(key, extractable) {\n return await CurveKeyFromD(name, this.Nsk, this.pkcs8, this.algorithm, key, extractable)\n },\n ...DHKEM_SHARED(),\n }\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nexport const KEM_DHKEM_X448_HKDF_SHA512 = function () \n \n {\n const id = 0x0021\n const name = 'DHKEM(X448, HKDF-SHA512)'\n const kdf = KDF_HKDF_SHA512()\n \n kdf.name = name\n return {\n id,\n suite_id: concat(L_KEM, I2OSP(id, 2)),\n type: 'KEM',\n name,\n kdf,\n Nsecret: 64,\n Nenc: 56,\n Npk: 56,\n Nsk: 56,\n Ndh: 56,\n algorithm: { name: 'X448' },\n pkcs8: Uint8Array.of(0x30, 0x46, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6f, 0x04, 0x3a, 0x04, 0x38), \n DeriveKeyPair: DeriveKeyPairX,\n async DeserializePrivateKey(key, extractable) {\n return await CurveKeyFromD(name, this.Nsk, this.pkcs8, this.algorithm, key, extractable)\n },\n ...DHKEM_SHARED(),\n }\n}\n\n \n \n \n\n \n\n \n \n \n \n \n\nfunction DIRECT_KEM_SHARED() {\n return {\n async DeriveKeyPair( ikm, extractable) {\n const dk = await LabeledDerive(\n this.kdf,\n this.suite_id,\n ikm,\n L_DeriveKeyPair,\n new Uint8Array(),\n this.Nsk,\n )\n\n const privateKey = (await this.DeserializePrivateKey(dk, extractable)) \n \n const usages = ['encapsulateBits']\n const publicKey = await getPublicKey(this.name, privateKey, usages)\n\n return { privateKey, publicKey }\n },\n async GenerateKeyPair( extractable) {\n \n const usages = ['encapsulateBits', 'decapsulateBits']\n return (await subtle(\n (c) => c.generateKey(this.algorithm, extractable, usages),\n this.name,\n )) \n },\n async SerializePublicKey( key) {\n assertKeyAlgorithm(key, this.algorithm)\n assertCryptoKey(key)\n \n const format = 'raw-public'\n return new Uint8Array(await subtle((c) => c.exportKey(format, key), this.name))\n },\n async DeserializePublicKey( key) {\n \n const format = 'raw-public'\n \n const usages = ['encapsulateBits']\n return await subtle(\n (c) => c.importKey(format, key , this.algorithm, true, usages),\n this.name,\n )\n },\n async SerializePrivateKey( key) {\n assertKeyAlgorithm(key, this.algorithm)\n assertCryptoKey(key)\n \n const format = 'raw-seed'\n return new Uint8Array(await subtle((c) => c.exportKey(format, key), this.name))\n },\n async DeserializePrivateKey( key, extractable) {\n \n const format = 'raw-seed'\n \n const usages = ['decapsulateBits']\n return await subtle(\n (c) => c.importKey(format, key , this.algorithm, extractable, usages),\n this.name,\n )\n },\n async Encap( pkR) {\n assertKeyAlgorithm(pkR, this.algorithm)\n\n const { sharedKey, ciphertext } = (await subtle(\n \n (c) => c.encapsulateBits(this.algorithm, pkR),\n this.name,\n )) \n\n return { shared_secret: new Uint8Array(sharedKey), enc: new Uint8Array(ciphertext) }\n },\n async Decap( enc, skR, _pkR) {\n assertKeyAlgorithm(skR, this.algorithm)\n return new Uint8Array(\n await subtle(\n \n (c) => c.decapsulateBits(this.algorithm, skR, enc ),\n this.name,\n ),\n )\n },\n }\n}\n\nfunction createDirectKEM({ id, name, Nsecret, Nenc, Npk, Nsk } ) {\n const kdf = KDF_SHAKE256()\n \n kdf.name = name\n return {\n id,\n suite_id: concat(L_KEM, I2OSP(id, 2)),\n type: 'KEM',\n name,\n Nsecret,\n Nenc,\n Npk,\n Nsk,\n algorithm: { name },\n kdf,\n ...DIRECT_KEM_SHARED(),\n }\n}\n\n \n \n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nexport const KEM_ML_KEM_512 = function () {\n const id = 0x0040\n const name = 'ML-KEM-512'\n const Nsecret = 32\n const Nenc = 768\n const Npk = 800\n const Nsk = 64\n return createDirectKEM({ id, name, Nsecret, Nenc, Npk, Nsk })\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nexport const KEM_ML_KEM_768 = function () {\n const id = 0x0041\n const name = 'ML-KEM-768'\n const Nsecret = 32\n const Nenc = 1088\n const Npk = 1184\n const Nsk = 64\n return createDirectKEM({ id, name, Nsecret, Nenc, Npk, Nsk })\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nexport const KEM_ML_KEM_1024 = function () {\n const id = 0x0042\n const name = 'ML-KEM-1024'\n const Nsecret = 32\n const Nenc = 1568\n const Npk = 1568\n const Nsk = 64\n return createDirectKEM({ id, name, Nsecret, Nenc, Npk, Nsk })\n}\n\n \n \n \n \n\n \n\nfunction AEAD_SHARED(P_MAX ) {\n \n \n \n \n \n const cache = new WeakMap ()\n async function importKey( key ) {\n return await subtle(\n (c) =>\n c.importKey(this.keyFormat, key , this.algorithm, false, [\n 'encrypt',\n 'decrypt',\n ]),\n this.name,\n )\n }\n return {\n async Seal( key, nonce, aad, pt) {\n if (pt.byteLength > P_MAX) {\n throw new RangeError('\"pt\" exceeds P_MAX')\n }\n const cryptoKey = await getCachedCryptoKey(cache, key, (bytes) => importKey.call(this, bytes))\n return new Uint8Array(\n await subtle(\n (c) =>\n c.encrypt(\n {\n name: this.algorithm,\n iv: nonce ,\n additionalData: aad ,\n },\n cryptoKey,\n pt ,\n ),\n this.name,\n ),\n )\n },\n async Open( key, nonce, aad, ct) {\n const cryptoKey = await getCachedCryptoKey(cache, key, (bytes) => importKey.call(this, bytes))\n return new Uint8Array(\n await subtle(\n (c) =>\n c.decrypt(\n {\n name: this.algorithm,\n iv: nonce ,\n additionalData: aad ,\n },\n cryptoKey,\n ct ,\n ),\n this.name,\n ),\n )\n },\n }\n}\n\n \n \n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nexport const AEAD_AES_128_GCM = function () {\n return {\n id: 0x0001,\n type: 'AEAD',\n name: 'AES-128-GCM',\n Nk: 16,\n Nn: 12,\n Nt: 16,\n algorithm: 'AES-GCM',\n keyFormat: 'raw',\n ...AEAD_SHARED(AES_GCM_P_MAX),\n }\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nexport const AEAD_AES_256_GCM = function () {\n return {\n id: 0x0002,\n type: 'AEAD',\n name: 'AES-256-GCM',\n Nk: 32,\n Nn: 12,\n Nt: 16,\n algorithm: 'AES-GCM',\n keyFormat: 'raw',\n ...AEAD_SHARED(AES_GCM_P_MAX),\n }\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nexport const AEAD_ChaCha20Poly1305 = function AEAD_ChaCha20Poly1305() {\n return {\n id: 0x0003,\n type: 'AEAD',\n name: 'ChaCha20Poly1305',\n Nk: 32,\n Nn: 12,\n Nt: 16,\n algorithm: 'ChaCha20-Poly1305',\n \n keyFormat: 'raw-secret',\n ...AEAD_SHARED(CHACHA20_POLY1305_P_MAX),\n }\n}\n\n \n \n \n\n \nconst InvalidInvocation = (_ ) => {\n if (_ !== priv) {\n throw new Error('invalid invocation')\n }\n}\nconst priv = /* @__PURE__ */ Symbol()\nclass HybridKey {\n #algorithm \n #type \n #extractable \n #t \n #pq \n #seed \n #publicKey \n\n static #isValid(key ) {\n return key.#algorithm !== undefined\n }\n\n static validate(key , extractable ) {\n try {\n if (!HybridKey.#isValid(key )) {\n throw new TypeError('unexpected key constructor')\n }\n } catch {\n throw new TypeError('unexpected key constructor')\n }\n if (extractable && !(key ).extractable) {\n throw new TypeError('key must be extractable')\n }\n }\n\n constructor(\n _ ,\n algorithm ,\n type ,\n extractable ,\n pq ,\n t ,\n seed ,\n publicKey ,\n ) {\n InvalidInvocation(_)\n this.#algorithm = algorithm\n this.#type = type\n this.#extractable = extractable\n this.#pq = pq\n this.#t = t\n this.#seed = seed\n this.#publicKey = publicKey\n }\n\n get algorithm() {\n return { name: this.#algorithm.name }\n }\n\n get extractable() {\n return this.#extractable\n }\n\n get type() {\n return this.#type\n }\n\n getPublicKey(_ ) {\n InvalidInvocation(_)\n return this.#publicKey\n }\n\n getSeed(_ ) {\n InvalidInvocation(_)\n return slice(this.#seed )\n }\n\n getT(_ ) {\n InvalidInvocation(_)\n return this.#t\n }\n\n getPq(_ ) {\n InvalidInvocation(_)\n return this.#pq\n }\n}\n\nfunction split(N1 , N2 , x ) {\n if (x.byteLength !== N1 + N2) {\n throw new Error('x.byteLength !== N1 + N2')\n }\n\n const x1 = slice(x, 0, N1)\n const x2 = slice(x, -N2)\n\n return [x1, x2]\n}\n\nfunction RandomScalarNist(t , seed ) {\n let sk_bigint = 0n\n let start = 0\n let end = t.Nscalar \n sk_bigint = OS2IP(slice(seed, start, end))\n\n while (sk_bigint === 0n || sk_bigint >= t.order ) {\n start = end\n end = end + t.Nscalar \n if (end > seed.byteLength) {\n throw new DeriveKeyPairError('Rejection sampling failed')\n }\n sk_bigint = OS2IP(slice(seed, start, end))\n }\n return bigIntToUint8Array(sk_bigint, t.Nscalar )\n}\n\n \nasync function expandDecapsKeyG(kem , seed ) {\n const Nout = kem.pq.Nseed + kem.t.Nseed\n const bits = Nout << 3\n \n const algorithm = { name: 'cSHAKE256', length: bits, outputLength: bits }\n const seed_full = await subtle((c) => c.digest(algorithm, seed ), kem.name)\n\n const [seed_PQ, seed_T] = split(kem.pq.Nseed, kem.t.Nseed, new Uint8Array(seed_full))\n\n \n const format = 'raw-seed'\n \n const usages = ['decapsulateBits', 'encapsulateBits']\n const dk_PQ = await subtle(\n (c) => c.importKey(format, seed_PQ , kem.pq.algorithm, true, [usages[0]]),\n kem.name,\n )\n const ek_PQ = await getPublicKey(kem.name, dk_PQ, [usages[1]])\n\n const sk = kem.t.RandomScalar?.(seed_T) ?? seed_T\n const { privateKey: dk_T, publicKey: ek_T } = await kem.t.GetKeyPair(sk)\n\n return { ek_PQ, ek_T, dk_PQ, dk_T }\n}\n\n \nasync function C2PRICombiner(\n kem ,\n ss_PQ ,\n ss_T ,\n ct_T ,\n _ek_T ,\n label ,\n) {\n const ek_T = new Uint8Array(await subtle((c) => c.exportKey('raw', _ek_T), kem.name))\n const data = concat(ss_PQ, ss_T, ct_T, ek_T, label) \n return new Uint8Array(await subtle((c) => c.digest('SHA3-256', data), kem.name))\n}\n\n \nasync function prepareEncapsG(\n kem ,\n ek_PQ ,\n ek_T ,\n) {\n const res = (await subtle(\n \n (c) => c.encapsulateBits(kem.pq.algorithm, ek_PQ),\n kem.name,\n )) \n const ss_PQ = new Uint8Array(res.sharedKey)\n const ct_PQ = new Uint8Array(res.ciphertext)\n\n const { privateKey: sk_E, publicKey } = (await subtle(\n (c) => c.generateKey(kem.t.algorithm, true, ['deriveBits']),\n kem.name,\n )) \n const ct_T = new Uint8Array(await subtle((c) => c.exportKey('raw', publicKey), kem.name))\n\n const ss_T = new Uint8Array(\n await subtle(\n (c) => c.deriveBits({ name: kem.t.algorithm.name, public: ek_T }, sk_E, kem.t.Nss << 3),\n kem.name,\n ),\n )\n\n return [ss_PQ, ss_T, ct_PQ, ct_T]\n}\n\n \nasync function prepareDecapsG(\n kem ,\n dk_PQ ,\n dk_T ,\n ct_PQ ,\n ct_T ,\n) {\n const ss_PQ = new Uint8Array(\n await subtle(\n \n (c) => c.decapsulateBits(kem.pq.algorithm, dk_PQ, ct_PQ),\n kem.name,\n ),\n )\n\n const pub = await subtle(\n (c) => c.importKey('raw', ct_T , kem.t.algorithm, true, []),\n kem.name,\n )\n\n const ss_T = new Uint8Array(\n await subtle(\n (c) => c.deriveBits({ name: kem.t.algorithm.name, public: pub }, dk_T, kem.t.Nss << 3),\n kem.name,\n ),\n )\n\n return [ss_PQ, ss_T]\n}\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n \n\nfunction COMPOSITE_HYBRID_KEM_SHARED() {\n Object.freeze(HybridKey.prototype)\n return {\n async DeriveKeyPair( ikm , extractable) {\n const seed = await LabeledDerive(\n this.kdf,\n this.suite_id,\n ikm,\n L_DeriveKeyPair,\n new Uint8Array(),\n 32,\n )\n\n const { ek_PQ, ek_T, dk_PQ, dk_T } = await expandDecapsKeyG(this, seed)\n\n const publicKey = new HybridKey(priv, this.algorithm, 'public', true, ek_PQ, ek_T)\n const privateKey = new HybridKey(\n priv,\n this.algorithm,\n 'private',\n extractable,\n dk_PQ,\n dk_T,\n seed,\n publicKey,\n )\n\n return { privateKey, publicKey }\n },\n async GenerateKeyPair( extractable) {\n return await this.DeriveKeyPair(crypto.getRandomValues(new Uint8Array(32)), extractable)\n },\n async SerializePublicKey( key) {\n assertKeyAlgorithm(key, this.algorithm)\n HybridKey.validate(key, true)\n \n const format = 'raw-public'\n const ek_PQ = new Uint8Array(\n await subtle((c) => c.exportKey(format, key.getPq(priv)), this.name),\n )\n const ek_T = new Uint8Array(\n await subtle((c) => c.exportKey('raw', key.getT(priv)), this.name),\n )\n\n return concat(ek_PQ, ek_T)\n },\n async DeserializePublicKey( key) {\n \n const format = 'raw-public'\n \n const usages = ['encapsulateBits']\n const pubPq = key.subarray(0, this.pq.Npk) \n const pubT = key.subarray(this.pq.Npk) \n const [ek_PQ, ek_T] = await Promise.all([\n subtle((c) => c.importKey(format, pubPq, this.pq.algorithm, true, usages), this.name),\n subtle((c) => c.importKey('raw', pubT, this.t.algorithm, true, []), this.name),\n ])\n\n return new HybridKey(priv, this.algorithm, 'public', true, ek_PQ, ek_T)\n },\n async SerializePrivateKey( key) {\n assertKeyAlgorithm(key, this.algorithm)\n HybridKey.validate(key, true)\n\n return key.getSeed(priv)\n },\n async DeserializePrivateKey( key, extractable) {\n const seed = slice(key)\n const { ek_PQ, ek_T, dk_PQ, dk_T } = await expandDecapsKeyG(this, seed)\n const publicKey = new HybridKey(priv, this.algorithm, 'public', true, ek_PQ, ek_T)\n const privateKey = new HybridKey(\n priv,\n this.algorithm,\n 'private',\n extractable,\n dk_PQ,\n dk_T,\n seed,\n publicKey,\n )\n\n return privateKey\n },\n async Encap( pkR) {\n assertKeyAlgorithm(pkR, this.algorithm)\n HybridKey.validate(pkR)\n\n const ek_PQ = pkR.getPq(priv)\n const ek_T = pkR.getT(priv)\n const [ss_PQ, ss_T, ct_PQ, ct_T] = await prepareEncapsG(this, ek_PQ, ek_T)\n const ss_H = await C2PRICombiner(this, ss_PQ, ss_T, ct_T, ek_T, this.label)\n const ct_H = concat(ct_PQ, ct_T)\n\n return { shared_secret: ss_H, enc: ct_H }\n },\n async Decap( enc, skR, pkR) {\n assertKeyAlgorithm(skR, this.algorithm)\n HybridKey.validate(skR)\n\n if (pkR) {\n assertKeyAlgorithm(pkR, this.algorithm)\n HybridKey.validate(pkR)\n }\n\n const [ct_PQ, ct_T] = split(this.pq.Nct, this.t.Nct, enc)\n const ek = pkR ?? skR.getPublicKey(priv) \n const ek_T = ek.getT(priv)\n const dk_PQ = skR.getPq(priv)\n const dk_T = skR.getT(priv)\n const [ss_PQ, ss_T] = await prepareDecapsG(this, dk_PQ, dk_T, ct_PQ, ct_T)\n const ss_H = await C2PRICombiner(this, ss_PQ, ss_T, ct_T, ek_T, this.label)\n\n return ss_H\n },\n }\n}\n\nfunction createCompositeHybridKEM(parameters ) {\n const kdf = KDF_SHAKE256()\n \n kdf.name = parameters.name\n return {\n ...parameters,\n suite_id: concat(L_KEM, I2OSP(parameters.id, 2)),\n type: 'KEM',\n algorithm: { name: parameters.name },\n kdf,\n ...COMPOSITE_HYBRID_KEM_SHARED(),\n }\n}\n\n \n \n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nexport const KEM_MLKEM768_X25519 = function () {\n const id = 0x647a\n const name = 'MLKEM768-X25519'\n const Nsecret = 32\n const Nenc = 1120\n const Npk = 1216\n const Nsk = 32\n const kem = { id, name, Nsecret, Nenc, Npk, Nsk }\n \n if (SubtleCrypto.supports?.('generateKey', name) ?? false) {\n return createDirectKEM(kem)\n }\n\n const pkcs8 = Uint8Array.of(0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e, 0x04, 0x22, 0x04, 0x20) \n return createCompositeHybridKEM({\n ...kem,\n pq: { algorithm: { name: 'ML-KEM-768' }, Nseed: 64, Npk: 1184, Nct: 1088 },\n t: {\n algorithm: { name: 'X25519' },\n Nseed: 32,\n Npk: 32,\n Nss: 32,\n Nsk: 32,\n Nct: 32,\n async GetKeyPair(sk) {\n const privateKey = await CurveKeyFromD(name, this.Nsk, pkcs8, this.algorithm, sk, true)\n const publicKey = await getPublicKey(name, privateKey, [])\n\n return { privateKey, publicKey }\n },\n },\n label: Uint8Array.of(0x5c, 0x2e, 0x2f, 0x2f, 0x5e, 0x5c), \n })\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nexport const KEM_MLKEM768_P256 = function () {\n const id = 0x0050\n const name = 'MLKEM768-P256'\n const Nsecret = 32\n const Nenc = 1153\n const Npk = 1249\n const Nsk = 32\n const kem = { id, name, Nsecret, Nenc, Npk, Nsk }\n \n if (SubtleCrypto.supports?.('generateKey', name) ?? false) {\n return createDirectKEM(kem)\n }\n\n return createCompositeHybridKEM({\n ...kem,\n pq: { algorithm: { name: 'ML-KEM-768' }, Nseed: 64, Npk: 1184, Nct: 1088 },\n t: {\n ...P256,\n Nseed: 128,\n Nss: 32,\n Nct: 65,\n Nscalar: 32,\n order: 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n,\n RandomScalar(seed) {\n return RandomScalarNist(this, seed)\n },\n GetKeyPair(sk) {\n return GetKeyPairNist(P256, sk, true, name)\n },\n },\n label: Uint8Array.of(0x4d, 0x4c, 0x4b, 0x45, 0x4d, 0x37, 0x36, 0x38, 0x2d, 0x50, 0x32, 0x35, 0x36), \n })\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nexport const KEM_MLKEM1024_P384 = function () {\n const id = 0x0051\n const name = 'MLKEM1024-P384'\n const Nsecret = 32\n const Nenc = 1665\n const Npk = 1665\n const Nsk = 32\n const kem = { id, name, Nsecret, Nenc, Npk, Nsk }\n \n if (SubtleCrypto.supports?.('generateKey', name) ?? false) {\n return createDirectKEM(kem)\n }\n\n return createCompositeHybridKEM({\n ...kem,\n pq: { algorithm: { name: 'ML-KEM-1024' }, Nseed: 64, Npk: 1568, Nct: 1568 },\n t: {\n ...P384,\n Nseed: 48,\n Nss: 48,\n Nct: 97,\n Nscalar: 48,\n order:\n 0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973n,\n RandomScalar(seed) {\n return RandomScalarNist(this, seed)\n },\n GetKeyPair(sk) {\n return GetKeyPairNist(P384, sk, true, name)\n },\n },\n label: Uint8Array.of(0x4d, 0x4c, 0x4b, 0x45, 0x4d, 0x31, 0x30, 0x32, 0x34, 0x2d, 0x50, 0x33, 0x38, 0x34), \n })\n}\n", "/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */\nexport function aarray(item, title, inner = () => { }) {\n if (!Array.isArray(item))\n throw new TypeError(`\"${title}\" expected array, got type=${typeof item}`);\n for (let i = 0; i < item.length; i++)\n inner(item[i], `${title}[${i}]`);\n return item;\n}\n/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - Value to inspect.\n * @returns `true` when the value is a Uint8Array view, including Node's `Buffer`.\n * @example\n * Guards a value before treating it as raw key material.\n *\n * ```ts\n * isBytes(new Uint8Array());\n * ```\n */\nexport function isBytes(a) {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy /\n // cross-realm cases. The fallback still requires a real ArrayBuffer view\n // so plain JSON-deserialized `{ constructor: ... }`\n // spoofing is rejected, and `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n 'BYTES_PER_ELEMENT' in a &&\n a.BYTES_PER_ELEMENT === 1));\n}\n// Shared error-message prefix builder. Only called on throw paths, so assert\n// success paths never pay for the string concatenation.\nconst atitle = (title) => (title ? `\"${title}\" ` : '');\n/**\n * Asserts something is boolean.\n * @param value - Value to validate.\n * @returns The validated boolean.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validates a boolean option before branching on it.\n *\n * ```ts\n * abool(true);\n * ```\n */\nexport function abool(value, title = '') {\n if (typeof value !== 'boolean')\n throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);\n return value;\n}\n/**\n * Asserts something is a non-negative safe integer.\n * @param n - Value to validate.\n * @returns The validated number.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validates a non-negative length or counter.\n *\n * ```ts\n * anumber(1);\n * ```\n */\nexport function anumber(n, title = '') {\n if (typeof n !== 'number')\n throw new TypeError(atitle(title) + 'expected number, got ' + typeof n);\n if (!Number.isSafeInteger(n) || n < 0)\n throw new RangeError(atitle(title) + 'expected integer >= 0, got ' + n);\n return n;\n}\n/**\n * Asserts something is Uint8Array.\n * @param value - Value to validate.\n * @param length - Expected byte length.\n * @param title - Optional label used in error messages.\n * @returns The validated byte array.\n * On Node, `Buffer` is accepted too because it is a Uint8Array view.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument lengths. {@link RangeError}\n * @example\n * Validates a fixed-length nonce or key buffer.\n *\n * ```ts\n * abytes(new Uint8Array([1, 2]), 2);\n * ```\n */\nexport function abytes(value, length, title = '') {\n // Success path first: this runs at the start of every update() / digestInto(), and the\n // common `abytes(data)` form must not pay for length handling it does not use.\n if (isBytes(value) && (length === undefined || value.length === length))\n return value;\n // Error path: recompute freely to build the exact message.\n if (length !== undefined)\n anumber(length, 'length');\n const bytes = isBytes(value);\n const ofLen = length !== undefined ? ` of length ${length}` : '';\n const got = bytes ? `length=${value.length}` : `type=${typeof value}`;\n const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes)\n throw new TypeError(message);\n throw new RangeError(message);\n}\nconst aobject = (value, label) => {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n throw new TypeError(label === 'object'\n ? 'expected valid options object'\n : `\"${label}\" expected object, got type=${typeof value}`);\n};\n/**\n * Asserts a hash- or MAC-like instance has not been destroyed or finished.\n * @param instance - Stateful instance to validate.\n * @param checkFinished - Whether to reject finished instances.\n * When `false`, only `destroyed` is checked.\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Guards against calling `update()` or `digest()` on a finished hash.\n *\n * ```ts\n * aexists({ destroyed: false, finished: false });\n * ```\n */\nexport function aexists(instance, checkFinished = true) {\n // Runs on every update()/digestInto(); the flags are library-owned booleans, so only their\n // truthiness is checked - re-validating their type per call was pure hot-path overhead.\n if (instance.destroyed)\n throw new Error('hash was destroyed');\n if (checkFinished && instance.finished)\n throw new Error('digest() was already called');\n}\n/**\n * Asserts output is a sufficiently-sized byte array.\n * @param out - Output buffer to validate.\n * @param instance - Hash-like instance providing `outputLen`.\n * This is the relaxed `digestInto()`-style contract: output must be at least `outputLen`,\n * unlike one-shot cipher helpers elsewhere in the repo that often require exact lengths.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong output buffer lengths. {@link RangeError}\n * @example\n * Verifies that a caller-provided output buffer is large enough.\n *\n * ```ts\n * aoutput(new Uint8Array(16), { outputLen: 16 });\n * ```\n */\nexport function aoutput(out, instance) {\n abytes(out, undefined, 'output');\n // `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast\n // when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call.\n const min = instance.outputLen;\n if (!(out.length >= min)) {\n throw new RangeError('\"output\" expected length >= ' + min);\n }\n}\n/**\n * Asserts output is a sufficiently-sized, 4-byte-aligned byte array.\n * {@link aoutput} plus an {@link isAligned32} check, for `digestInto()` paths\n * that write through zero-allocation `u32` word views.\n * @param out - Output buffer to validate.\n * @param instance - Hash-like instance providing `outputLen`.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong output buffer lengths. {@link RangeError}\n * @throws On wrong output buffer alignment. {@link Error}\n * @example\n * Verifies that a caller-provided output buffer is large enough and aligned.\n *\n * ```ts\n * aoutput32(new Uint8Array(16), { outputLen: 16 });\n * ```\n */\nexport function aoutput32(out, instance) {\n aoutput(out, instance);\n if (!isAligned32(out))\n throw new Error('invalid output, must be aligned');\n}\n/**\n * Casts a typed-array view to Uint8Array.\n * @param arr - Typed-array view to reinterpret.\n * @returns Uint8Array view over the same bytes.\n * @example\n * Views 32-bit words as raw bytes without copying.\n *\n * ```ts\n * u8(new Uint32Array([1]));\n * ```\n */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Casts a typed-array view to Uint32Array.\n * @param arr - Typed-array view to reinterpret.\n * @returns Uint32Array view over the same bytes. Callers are expected to provide a\n * 4-byte-aligned offset; trailing `1..3` bytes are silently dropped.\n * @example\n * Views a byte buffer as 32-bit words for block processing.\n *\n * ```ts\n * u32(new Uint8Array(4));\n * ```\n */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/**\n * Zeroizes typed arrays in place.\n * Warning: JS provides no guarantees.\n * @param arrays - Arrays to wipe.\n * @example\n * Wipes a temporary key buffer after use.\n *\n * ```ts\n * const bytes = new Uint8Array([1]);\n * clean(bytes);\n * ```\n */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - Typed-array view to wrap.\n * @returns DataView over the same bytes.\n * @example\n * Creates an endian-aware view for length encoding.\n *\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Whether the current platform is little-endian.\n * Most are; some IBM systems are not.\n */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/**\n * Reverses byte order of one 32-bit word.\n * @param word - Unsigned 32-bit word to swap.\n * @returns The same word with bytes reversed.\n * @example\n * Swaps a big-endian word into little-endian byte order.\n *\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/**\n * Normalizes one 32-bit word to the little-endian representation expected by cipher cores.\n * @param n - Unsigned 32-bit word to normalize.\n * @returns Little-endian normalized word on big-endian hosts, else the input word unchanged.\n * @example\n * Normalizes a host-endian word before passing it into an ARX/AES core.\n *\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n) >>> 0;\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - Uint32Array whose words should be swapped.\n * @returns The same array after in-place byte swapping.\n * @example\n * Swaps every 32-bit word in a word-view buffer.\n *\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n/**\n * Normalizes a Uint32Array view to the little-endian representation expected by cipher cores.\n * @param u - Word view to normalize in place.\n * @returns Little-endian normalized word view.\n * @example\n * Normalizes a word-view buffer before block processing.\n *\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion:\n// {@link https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex | caniuse entry}\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @param bytes - Bytes to encode.\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Formats ciphertext bytes for logs or test vectors.\n *\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\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// Strict ASCII nibble parser: non-ASCII hex lookalikes are rejected as undefined.\n// ASCII codes: '0'..'9' = 48..57, 'A'..'F' = 65..70, 'a'..'f' = 97..102.\n// prettier-ignore\nfunction asciiToBase16(ch) {\n return ch >= 48 && ch <= 57 ? ch - 48 // '2' => 50-48\n : ch >= 65 && ch <= 70 ? ch - (65 - 10) // 'B' => 66-(65-10)\n : ch >= 97 && ch <= 102 ? ch - (97 - 10) // 'b' => 98-(97-10)\n : undefined;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - hexadecimal string to decode\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode lowercase hexadecimal into bytes.\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return Uint8Array.fromHex(hex);\n }\n catch (error) {\n if (error instanceof SyntaxError)\n throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new RangeError('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)); // parse first char, multiply it by 16\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); // parse second char\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9\n }\n return array;\n}\nconst _0n = /* @__PURE__ */ BigInt(0);\n// Used in ff1, via bytesToNumberBE\n/**\n * Converts a big-endian hex string into bigint.\n * @param hex - Hexadecimal string without `0x`.\n * @returns Parsed bigint value. The empty string is treated as `0n`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Parses a big-endian field element or counter from hex.\n *\n * ```ts\n * hexToNumber('ff');\n * ```\n */\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n // Numeric parser, not byte-hex decoder: odd-length forms like 'f' are valid,\n // and malformed syntax follows BigInt's native error behavior.\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n// Used in ff1\n// BE: Big Endian, LE: Little Endian\n/**\n * Converts big-endian bytes into bigint.\n * @param bytes - Big-endian bytes.\n * @returns Parsed bigint value. Empty input is treated as `0n`.\n * @throws On invalid byte input passed to the internal hex conversion. {@link TypeError}\n * @example\n * Reads a big-endian integer from serialized bytes.\n *\n * ```ts\n * bytesToNumberBE(new Uint8Array([1, 0]));\n * ```\n */\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\n/**\n * Validates that a value is a non-negative bigint or safe integer.\n * @param n - Value to validate.\n * @returns The same validated value.\n * @throws On wrong argument ranges or values. {@link RangeError}\n */\nfunction abignumber(n) {\n if (typeof n === 'bigint') {\n if (!(_0n <= n))\n throw new RangeError('positive bigint expected, got ' + n);\n }\n else\n anumber(n);\n return n;\n}\n// Used in ff1\n/**\n * Converts a number into big-endian bytes of fixed length.\n * @param n - Number to encode.\n * @param len - Output length in bytes. Must be greater than zero.\n * @returns Big-endian bytes padded to `len`.\n * Negative values, `len = 0`, and values that do not fit are rejected before\n * downstream hex parsing.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If a documented runtime validation or state check fails. {@link Error}\n * @example\n * Encodes a counter as fixed-width big-endian bytes.\n *\n * ```ts\n * numberToBytesBE(1, 2);\n * ```\n */\nexport function numberToBytesBE(n, len) {\n anumber(len);\n if (len === 0)\n throw new Error('zero output length is invalid');\n n = abignumber(n);\n const expectedLen = len * 2;\n const hex = n.toString(16);\n // Detect overflow before hex parsing so oversized values don't leak the shared odd-hex error.\n if (hex.length > expectedLen)\n throw new RangeError('number is too large');\n return hexToBytes(hex.padStart(expectedLen, '0'));\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * @param str - String to encode.\n * @returns UTF-8 bytes in a detached fresh Uint8Array copy.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encodes application text before encryption or MACing.\n *\n * ```ts\n * utf8ToBytes('abc'); // new Uint8Array([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new TypeError('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // {@link https://bugzil.la/1681809 | Firefox bug 1681809}\n}\n/**\n * Converts bytes to string using UTF8 encoding.\n * @param bytes - UTF-8 bytes.\n * @returns Decoded string. Input validation is delegated to `TextDecoder`, and malformed\n * UTF-8 is replacement-decoded instead of rejected.\n * @example\n * Decodes UTF-8 plaintext back into a string.\n *\n * ```ts\n * bytesToUtf8(new Uint8Array([97, 98, 99])); // 'abc'\n * ```\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Checks if two U8A use same underlying buffer and overlaps.\n * This is invalid and can corrupt data.\n * @param a - First byte view.\n * @param b - Second byte view.\n * @returns `true` when the views overlap in memory.\n * @example\n * Detects whether two slices alias the same backing buffer.\n *\n * ```ts\n * overlapBytes(new Uint8Array(4), new Uint8Array(4));\n * ```\n */\nexport function overlapBytes(a, b) {\n // Zero-length views cannot overwrite anything, even if their offset sits inside another range.\n if (!a.byteLength || !b.byteLength)\n return false;\n return (a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy\n a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end\n b.byteOffset < a.byteOffset + a.byteLength // b starts before a end\n );\n}\n/**\n * If input and output overlap and input starts before output, we will overwrite end of input before\n * we start processing it, so this is not supported by forward-processing ciphers.\n * @param input - Input bytes.\n * @param output - Output bytes.\n * @throws If the output view would overwrite unread input bytes. {@link Error}\n * @example\n * Rejects an in-place layout that would overwrite unread input bytes.\n *\n * ```ts\n * const buffer = new Uint8Array(8);\n * complexOverlapBytes(buffer.subarray(0, 4), buffer.subarray(2, 6));\n * ```\n */\nexport function complexOverlapBytes(input, output) {\n // This is very cursed. It works somehow, but I'm completely unsure,\n // reasoning about overlapping aligned windows is very hard.\n if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)\n throw new Error('complex overlap of input and output is not supported');\n}\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - Byte arrays to concatenate.\n * @returns Combined byte array.\n * @throws On wrong argument types inside the byte-array list. {@link TypeError}\n * @example\n * Builds a `nonce || ciphertext` style buffer.\n *\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays) {\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 * Merges user options into defaults.\n * @param defaults - Default option values.\n * @param opts - User-provided overrides.\n * @returns Combined options object.\n * `defaults` is a library-owned mutable object; user-provided `opts` only need to be\n * object-shaped, since \"plain object\" checks reject valid proxy/cross-realm containers.\n * The merge mutates `defaults` in place and returns the same object, so direct callers\n * should pass a fresh defaults object unless they intentionally want shared state updated.\n * @throws If options are missing or not an object. {@link Error}\n * @example\n * Applies user overrides to the default cipher options.\n *\n * ```ts\n * checkOpts({ rounds: 20 }, { rounds: 8 });\n * ```\n */\nexport function checkOpts(defaults, opts) {\n aobject(defaults, 'defaults');\n aobject(opts, 'opts');\n // Mutates defaults by design. __proto__ follows Object.assign semantics here and can only\n // affect this local option object; callers already control this low-level options surface.\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/**\n * Compares two byte arrays in kinda constant time once lengths already match.\n * @param a - First byte array.\n * @param b - Second byte array.\n * @returns `true` when the arrays contain the same bytes. Different lengths still return early.\n * @example\n * Compares an expected authentication tag with the received one.\n *\n * ```ts\n * equalBytes(new Uint8Array([1]), new Uint8Array([1]));\n * ```\n */\nexport function equalBytes(a, b) {\n a = abytes(a);\n b = abytes(b);\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * Wraps a keyed MAC constructor into a one-shot helper with `.create()`.\n * @param keyLen - Valid probe-key length used to read static metadata once.\n * The probe key is only used for `outputLen` / `blockLen`, so callers with several valid key sizes\n * can pass any representative size as long as those values stay fixed.\n * @param macCons - Keyed MAC constructor or factory.\n * @param fromMsg - Optional adapter that derives extra constructor args from the one-shot message.\n * @returns Callable MAC helper with `.create()`.\n */\nexport function wrapMacConstructor(keyLen, macCons, fromMsg) {\n const mac = macCons;\n const getArgs = (fromMsg || (() => []));\n const macC = (msg, key) => mac(key, ...getArgs(msg))\n .update(msg)\n .digest();\n const tmp = mac(new Uint8Array(keyLen), ...getArgs(new Uint8Array(0)));\n macC.outputLen = tmp.outputLen;\n macC.blockLen = tmp.blockLen;\n macC.create = (key, ...args) => mac(key, ...args);\n return macC;\n}\n/**\n * Wraps a cipher: validates args, ensures encrypt() can only be called once.\n * Used internally by the exported cipher constructors.\n * Output-buffer support is inferred from the wrapped `encrypt` / `decrypt`\n * arity (`fn.length === 2`), so wrapped output-capable methods must use a normal\n * second parameter, not a default/rest parameter. AAD support is explicit in\n * `params.withAAD`; optional AAD starts after the nonce slot when one is present.\n * @__NO_SIDE_EFFECTS__\n * @param params - Static cipher metadata. See {@link CipherParams}.\n * @param constructor - Cipher constructor.\n * @returns Wrapped constructor with validation.\n */\nexport const wrapCipher = (params, constructor) => {\n function wrappedCipher(key, ...args) {\n // Validate key\n abytes(key, undefined, 'key');\n // Validate nonce if nonceLength is present\n if (params.nonceLength !== undefined) {\n const nonce = args[0];\n abytes(nonce, params.varSizeNonce ? undefined : params.nonceLength, 'nonce');\n }\n // Keep tag length available for decrypt-size checks after constructor validation.\n const tagl = params.tagLength;\n const aadStart = params.nonceLength !== undefined ? 1 : 0;\n // No-AAD constructors otherwise silently ignore byte args meant as AAD.\n if (!params.withAAD) {\n for (let i = aadStart; i < args.length; i++)\n if (isBytes(args[i]))\n throw new Error('AAD not supported');\n }\n // Validate the first AAD slot early; rest-arg AAD constructors validate the tail themselves.\n if (params.withAAD && args[aadStart] !== undefined)\n abytes(args[aadStart], undefined, 'AAD');\n const cipher = constructor(key, ...args);\n const checkOutput = (fnLength, output) => {\n if (output !== undefined) {\n if (fnLength !== 2)\n throw new Error('cipher output not supported');\n abytes(output, undefined, 'output');\n }\n };\n // Create wrapped cipher with validation and single-use encryption\n let called = false;\n const wrCipher = {\n encrypt(data, output) {\n if (called)\n throw new Error('cannot encrypt() twice with same key + nonce');\n // Any encrypt attempt consumes the instance, even if validation rejects below.\n called = true;\n abytes(data, undefined, 'data');\n checkOutput(cipher.encrypt.length, output);\n return cipher.encrypt(data, output);\n },\n decrypt(data, output) {\n abytes(data, undefined, 'data');\n if (tagl && data.length < tagl)\n throw new Error('\"ciphertext\" expected length >= tagLength=' + tagl);\n checkOutput(cipher.decrypt.length, output);\n return cipher.decrypt(data, output);\n },\n };\n return wrCipher;\n }\n Object.assign(wrappedCipher, params);\n return wrappedCipher;\n};\n/**\n * By default, returns u8a of length.\n * When out is available, it checks it for validity and uses it.\n * @param expectedLength - Required output length.\n * @param out - Optional destination buffer.\n * @param onlyAligned - Whether `out` must be 4-byte aligned.\n * @returns Output buffer ready for writing.\n * @throws On wrong argument types. {@link TypeError}\n * @throws If the provided output buffer has the wrong size. {@link RangeError}\n * @throws If the provided output buffer has the wrong alignment. {@link Error}\n * @example\n * Reuses a caller-provided output buffer when lengths match.\n *\n * ```ts\n * getOutput(16, new Uint8Array(16));\n * ```\n */\nexport function getOutput(expectedLength, out, onlyAligned = true) {\n if (out === undefined)\n return new Uint8Array(expectedLength);\n // Keep Buffer/cross-realm Uint8Array support here instead of trusting a shape-compatible object.\n abytes(out, expectedLength, 'output');\n if (onlyAligned && !isAligned32(out))\n throw new Error('invalid output, must be aligned');\n return out;\n}\n/**\n * Encodes data and AAD lengths into a 16-byte buffer.\n * @param dataLength - Data length. Units are caller-defined: GCM passes bit\n * lengths, ChaCha20-Poly1305 passes byte lengths \u2014 the helper writes the raw values.\n * @param aadLength - AAD length, same unit convention as `dataLength`.\n * The serialized block is still `aadLength || dataLength`, matching GCM/Poly1305\n * conventions even though the helper parameter order is `(dataLength, aadLength)`.\n * @param isLE - Whether to encode lengths as little-endian.\n * @returns 16-byte length block.\n * @throws On wrong argument types passed to the endian validator. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Builds the length block appended by GCM and Poly1305.\n *\n * ```ts\n * u64Lengths(16, 8, true);\n * ```\n */\nexport function u64Lengths(dataLength, aadLength, isLE) {\n // Reject coercible non-number lengths like '10' and true before BigInt(...) accepts them.\n anumber(dataLength);\n anumber(aadLength);\n abool(isLE);\n const num = new Uint8Array(16);\n const view = createView(num);\n view.setBigUint64(0, BigInt(aadLength), isLE);\n view.setBigUint64(8, BigInt(dataLength), isLE);\n return num;\n}\n/**\n * Checks whether a byte array is aligned to a 4-byte offset.\n * @param bytes - Byte array to inspect.\n * @returns `true` when the view is 4-byte aligned.\n * @example\n * Checks whether a buffer can be safely viewed as Uint32Array.\n *\n * ```ts\n * isAligned32(new Uint8Array(4));\n * ```\n */\nexport function isAligned32(bytes) {\n return bytes.byteOffset % 4 === 0;\n}\n/**\n * Copies bytes into a new Uint8Array.\n * @param bytes - Bytes to copy.\n * @returns Copied byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Copies input into an aligned Uint8Array before block processing.\n *\n * ```ts\n * copyBytes(new Uint8Array([1, 2]));\n * ```\n */\nexport function copyBytes(bytes) {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes));\n}\n/**\n * Cryptographically secure PRNG backed by `crypto.getRandomValues`.\n * @param bytesLength - number of random bytes to generate\n * @returns Random bytes.\n * The platform `getRandomValues()` implementation still defines any\n * single-call length cap, and this helper rejects oversize requests\n * with a stable library `RangeError` instead of host-specific errors.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}\n * @example\n * Generate a fresh random key or nonce.\n * ```ts\n * const key = randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32) {\n // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.\n anumber(bytesLength, 'bytesLength');\n const cr = typeof globalThis === 'object' ? globalThis.crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n // Web Cryptography API Level 2 \u00A710.1.1:\n // if `byteLength > 65536`, throw `QuotaExceededError`.\n // Keep the guard explicit so callers can see the quota in code\n // instead of discovering it by reading the spec or host errors.\n // This wrapper surfaces the same quota as a stable library RangeError.\n if (bytesLength > 65536)\n throw new RangeError(`\"bytesLength\" expected <= 65536, got ${bytesLength}`);\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n/**\n * Uses CSPRNG for nonce, nonce injected in ciphertext.\n * For `encrypt`, a `nonceBytes`-length buffer is fetched from CSPRNG and\n * prepended to encrypted ciphertext. For `decrypt`, first `nonceBytes` of ciphertext\n * are treated as nonce. The wrapper always allocates a fresh `nonce || ciphertext`\n * buffer on encrypt and intentionally does not support caller-provided destination buffers.\n * Too-short decrypt inputs are split into short/empty nonce views and then delegated\n * to the wrapped cipher instead of being rejected here first.\n *\n * NOTE: Under the same key, using random nonces (e.g. `managedNonce`) with AES-GCM and ChaCha\n * should be limited to `2**23` (8M) messages to get a collision chance of\n * `2**-50`. Stretching to `2**32` (4B) messages would raise that chance to\n * `2**-33`, still negligible but creeping up.\n * @param fn - Cipher constructor that expects a nonce.\n * @param randomBytes_ - Random-byte source used for nonce generation.\n * @returns Cipher constructor that prepends the nonce to ciphertext.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On invalid nonce lengths observed at wrapper construction or use. {@link RangeError}\n * @example\n * Prepends a fresh random nonce to every ciphertext.\n *\n * ```ts\n * import { gcm } from '@noble/ciphers/aes.js';\n * import { managedNonce, randomBytes } from '@noble/ciphers/utils.js';\n * const wrapped = managedNonce(gcm);\n * const key = randomBytes(16);\n * const ciphertext = wrapped(key).encrypt(new Uint8Array([1, 2, 3]));\n * wrapped(key).decrypt(ciphertext);\n * ```\n */\nexport function managedNonce(fn, randomBytes_ = randomBytes) {\n if (typeof fn !== 'function')\n throw new TypeError('\"fn\" expected cipher constructor, got type=' + typeof fn);\n if (typeof randomBytes_ !== 'function')\n throw new TypeError('\"randomBytes_\" expected function, got type=' + typeof randomBytes_);\n const { nonceLength } = fn;\n anumber(nonceLength, 'fn.nonceLength');\n const addNonce = (nonce, ciphertext, plaintext) => {\n const out = concatBytes(nonce, ciphertext);\n // Wrapped ciphers may alias caller plaintext on encrypt(); never zero\n // caller-owned buffers here.\n if (!overlapBytes(plaintext, ciphertext))\n ciphertext.fill(0);\n return out;\n };\n // NOTE: we cannot support DST here, it would be mistake:\n // - we don't know how much dst length cipher requires\n // - nonce may unalign dst and break everything\n // - we create new u8a anyway (concatBytes)\n // - previously we passed all args to cipher, but that was mistake!\n const res = ((key, ...args) => ({\n encrypt(plaintext) {\n abytes(plaintext, undefined, 'data');\n const nonce = randomBytes_(nonceLength);\n const encrypted = fn(key, nonce, ...args).encrypt(plaintext);\n // @ts-ignore\n if (encrypted instanceof Promise)\n return encrypted.then((ct) => addNonce(nonce, ct, plaintext));\n return addNonce(nonce, encrypted, plaintext);\n },\n decrypt(ciphertext) {\n abytes(ciphertext, undefined, 'data');\n const nonce = ciphertext.subarray(0, nonceLength);\n const decrypted = ciphertext.subarray(nonceLength);\n return fn(key, nonce, ...args).decrypt(decrypted);\n },\n }));\n // Auto-nonce wrappers still preserve the wrapped payload geometry.\n if ('blockSize' in fn)\n res.blockSize = fn.blockSize;\n if ('tagLength' in fn)\n res.tagLength = fn.tagLength;\n if ('withAAD' in fn)\n res.withAAD = fn.withAAD;\n return res;\n}\n", "/**\n * Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.\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) | cnt(2) | s[2] | k(4) | s[3]\n chacha: s(4) | k(8) | cnt(1) | nonce(3)\n chacha20orig: s(4) | k(8) | cnt(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 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).\nCounter overflow is undefined; see {@link https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/ | the CFRG thread}.\nCurrent noble policy is strict non-wrap for the shared 32-bit counter path:\nexported ARX ciphers reject initial `0xffffffff` and stop before any implicit\nwrap back to zero.\nSee {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2 | the XChaCha appendix} for the extended-nonce construction.\n\n * @module\n */\nimport { abool, abytes, anumber, checkOpts, clean, complexOverlapBytes, copyBytes, getOutput, isAligned32, isLE, randomBytes, swap32IfBE, u32, } from \"./utils.js\";\n// Replaces `TextEncoder` for ASCII literals, which is enough for sigma constants.\n// Non-ASCII input would not match UTF-8 `TextEncoder` output.\nconst encodeStr = (str) => Uint8Array.from(str.split(''), (c) => c.charCodeAt(0));\n// Raw `createCipher(...)` exports consume these native-endian `u32(...)` views directly.\n// Public `wrapCipher(...)` APIs reject non-little-endian platforms before reaching this path.\n// RFC 8439 \u00A72.3 / RFC 7539 \u00A72.3 only define the 256-bit-key constants; this 16-byte sigma is\n// kept for legacy allowShortKeys Salsa/ChaCha variants.\nconst sigma16_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr('expand 16-byte k'))))();\n// RFC 8439 \u00A72.3 / RFC 7539 \u00A72.3 define words 0-3 as\n// `0x61707865 0x3320646e 0x79622d32 0x6b206574`, i.e. `expand 32-byte k`.\nconst sigma32_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr('expand 32-byte k'))))();\n/**\n * Rotates a 32-bit word left.\n * @param a - Input word.\n * @param b - Rotation count in bits.\n * @returns Rotated 32-bit word.\n * @example\n * Moves the top byte of `0x12345678` into the low byte position.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(a, b) {\n return (a << b) | (a >>> (32 - b));\n}\n// Salsa and Chacha block length is always 512-bit\nconst BLOCK_LEN = 64;\n// RFC 8439 \u00A72.2 / RFC 7539 \u00A72.2: the ChaCha state has 16 32-bit words.\nconst BLOCK_LEN32 = 16;\n// Counter policy for the shared public `counter` argument:\n// - RFC/IETF ChaCha20 uses a 32-bit counter.\n// - OpenSSL/Node `chacha20` instead treat the full 16-byte IV as a 128-bit\n// counter state and carry into the next word.\n// - Raw `chacha20orig`, `salsa20`, `xsalsa20`, and `xchacha20` use 64-bit counters in libsodium\n// and libtomcrypt, while some libs (for example libtomcrypt's RFC/IETF path) reject the max\n// boundary instead of carrying.\n// - AEAD wrappers diverge too: libsodium `xchacha20poly1305` uses the IETF payload counter from\n// block 1, while `secretstream_xchacha20poly1305` is a different protocol with rekey/reset.\n// Noble intentionally throws instead of silently picking one wrap model for users. In the default\n// path, even a 32-bit boundary would take 2^32 blocks * 64 bytes = 256 GiB, which is practically\n// unreachable for normal JS callers; advanced users who pass `counter` explicitly can implement\n// whatever wider carry / wrap policy they need on top.\nconst MAX_COUNTER = /* @__PURE__ */ (() => 2 ** 32 - 1)();\nconst U32_EMPTY = /* @__PURE__ */ Uint32Array.of();\nfunction runCipher(core, sigma, key, nonce, data, output, counter, rounds) {\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 = isLE && isAligned32(data) && isAligned32(output);\n const d32 = isAligned ? u32(data) : U32_EMPTY;\n const o32 = isAligned ? u32(output) : U32_EMPTY;\n // RFC 8439 \u00A72.4.1 / RFC 7539 \u00A72.4.1 allow XORing one keystream block at a time and\n // truncating the final partial block instead of materializing the whole keystream.\n if (!isLE) {\n for (let pos = 0; pos < len; counter++) {\n core(sigma, key, nonce, b32, counter, rounds);\n // RFC 8439 \u00A72.4 / RFC 7539 \u00A72.4 serialize keystream words in little-endian order.\n swap32IfBE(b32);\n if (counter >= MAX_COUNTER)\n throw new Error('arx: counter overflow');\n const take = Math.min(BLOCK_LEN, len - pos);\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 return;\n }\n for (let pos = 0; pos < len; counter++) {\n core(sigma, key, nonce, b32, counter, rounds);\n // See MAX_COUNTER policy note above: never silently wrap the shared public counter.\n if (counter >= MAX_COUNTER)\n 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)\n throw new Error('arx: invalid block position');\n for (let j = 0, posj; 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/**\n * Creates an ARX stream cipher from a 32-bit core permutation.\n * Used internally to build the exported Salsa and ChaCha stream ciphers.\n * @param core - Core function that fills one keystream block.\n * @param opts - Cipher layout and nonce-extension options. See {@link CipherOpts}.\n * @returns Stream cipher function over byte arrays.\n * @throws If the core callback, key size, counter, or output sizing is invalid. {@link Error}\n */\nexport function createCipher(core, opts) {\n const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts);\n if (typeof core !== 'function')\n throw new Error('core must be a function');\n anumber(counterLength);\n anumber(rounds);\n abool(counterRight);\n abool(allowShortKeys);\n return (key, nonce, data, output, counter = 0) => {\n abytes(key, undefined, 'key');\n abytes(nonce, undefined, 'nonce');\n abytes(data, undefined, 'data');\n const len = data.length;\n // Raw XorStream APIs return ciphertext/plaintext bytes directly, so caller-provided outputs\n // must match the logical result length exactly instead of returning an oversized workspace.\n const hasOutput = output !== undefined;\n output = getOutput(len, output, false);\n if (hasOutput)\n complexOverlapBytes(data, output);\n anumber(counter);\n // See MAX_COUNTER policy note above: reject advanced explicit-counter requests before any wrap.\n if (counter < 0 || counter >= MAX_COUNTER)\n throw new Error('arx: counter overflow');\n const toClean = [];\n // Key & sigma\n // key=16 -> sigma16, k=key|key\n // key=32 -> sigma32, k=key\n let l = key.length;\n let k;\n let sigma;\n if (l === 32) {\n // Copy caller keys too: big-endian normalization, extended-nonce subkey derivation, and\n // final clean(...) all mutate or wipe the temporary buffer in place.\n toClean.push((k = copyBytes(key)));\n sigma = sigma32_32;\n }\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 }\n else {\n abytes(key, 32, 'arx key');\n throw new Error('invalid key size');\n // throw new Error(`\"arx key\" expected Uint8Array of length 32, got length=${l}`);\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 // Copy before taking u32(...) views on misaligned inputs, and on big-endian so later\n // swap32IfBE(...) never mutates caller nonce bytes in place.\n if (!isLE || !isAligned32(nonce))\n toClean.push((nonce = copyBytes(nonce)));\n let k32 = u32(k);\n // hsalsa & hchacha: handle extended nonce\n if (extendNonceFn) {\n if (nonce.length !== 24)\n throw new Error('arx: extended nonce must be 24 bytes');\n const n16 = nonce.subarray(0, 16);\n if (isLE)\n extendNonceFn(sigma, k32, u32(n16), k32);\n else {\n const sigmaRaw = swap32IfBE(Uint32Array.from(sigma));\n extendNonceFn(sigmaRaw, k32, u32(n16), k32);\n clean(sigmaRaw);\n swap32IfBE(k32);\n }\n nonce = nonce.subarray(16);\n }\n else if (!isLE)\n swap32IfBE(k32);\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 // Normalize 64-bit-nonce layouts to the 12-byte core input: ChaCha/XChaCha prefix 4 zero\n // counter bytes, while Salsa/XSalsa append them after the nonce words.\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 = swap32IfBE(u32(nonce));\n // Ensure temporary key/nonce copies are wiped even if the remaining\n // runtime guard in runCipher(...) throws on counter overflow.\n try {\n runCipher(core, sigma, k32, n32, data, output, counter, rounds);\n return output;\n }\n finally {\n clean(...toClean);\n }\n };\n}\n/** Internal class which wraps chacha20 or chacha8 to create CSPRNG. */\nexport class _XorStreamPRG {\n blockLen;\n keyLen;\n nonceLen;\n state;\n buf;\n key;\n nonce;\n pos;\n ctr;\n cipher;\n destroyed = false;\n constructor(cipher, blockLen, keyLen, nonceLen, seed) {\n this.cipher = cipher;\n this.blockLen = blockLen;\n this.keyLen = keyLen;\n this.nonceLen = nonceLen;\n this.state = new Uint8Array(this.keyLen + this.nonceLen);\n this.reseed(seed);\n this.ctr = 0;\n this.pos = this.blockLen;\n this.buf = new Uint8Array(this.blockLen);\n // Keep a single key||nonce backing buffer so reseed/addEntropy/clean update the live cipher\n // inputs in place through these subarray views.\n this.key = this.state.subarray(0, this.keyLen);\n this.nonce = this.state.subarray(this.keyLen);\n }\n reseed(seed) {\n abytes(seed, undefined, 'seed');\n if (!seed || seed.length === 0)\n throw new Error('entropy required');\n // Mix variable-length entropy cyclically across the whole key||nonce state, then restart the\n // keystream so buffered leftovers from the previous state are never reused.\n for (let i = 0; i < seed.length; i++)\n this.state[i % this.state.length] ^= seed[i];\n this.ctr = 0;\n this.pos = this.blockLen;\n }\n addEntropy(seed) {\n if (this.destroyed)\n throw new Error('cannot use destroyed PRG');\n // Reject empty entropy before re-keying, otherwise a throwing call would still advance state.\n abytes(seed, undefined, 'seed');\n if (seed.length === 0)\n throw new Error('entropy required');\n // Re-key from the current stream first, then mix external entropy into the fresh key||nonce\n // state through reseed() so stale buffered bytes are discarded.\n this.state.set(this.randomBytes(this.state.length));\n this.reseed(seed);\n }\n randomBytes(len) {\n if (this.destroyed)\n throw new Error('cannot use destroyed PRG');\n anumber(len);\n if (len === 0)\n return new Uint8Array(0);\n const avail = this.pos < this.blockLen ? this.blockLen - this.pos : 0;\n const blocks = Math.ceil(Math.max(0, len - avail) / this.blockLen);\n // Preflight overflow so failed reads don't partially consume keystream\n // and leave the PRG repeating blocks.\n if (blocks > 0 && this.ctr > MAX_COUNTER - blocks)\n throw new Error('arx: counter overflow');\n const out = new Uint8Array(len);\n let outPos = 0;\n // `out` starts zero-filled, and `buf.fill(0)` below does the same for leftovers: XOR-stream\n // ciphers then emit raw keystream bytes directly into those buffers.\n // Serve buffered leftovers first so split reads stay identical to one larger read.\n if (this.pos < this.blockLen) {\n const take = Math.min(len, this.blockLen - this.pos);\n out.set(this.buf.subarray(this.pos, this.pos + take), 0);\n this.pos += take;\n outPos += take;\n if (outPos === len)\n return out; // fast path\n }\n // Full blocks directly to out\n const full = Math.floor((len - outPos) / this.blockLen);\n if (full > 0) {\n const blockBytes = full * this.blockLen;\n const b = out.subarray(outPos, outPos + blockBytes);\n this.cipher(this.key, this.nonce, b, b, this.ctr);\n this.ctr += full;\n outPos += blockBytes;\n }\n // Save leftovers\n const left = len - outPos;\n if (left > 0) {\n this.buf.fill(0);\n // NOTE: cipher will handle overflow\n this.cipher(this.key, this.nonce, this.buf, this.buf, this.ctr++);\n out.set(this.buf.subarray(0, left), outPos);\n this.pos = left;\n }\n return out;\n }\n // Clone seeds the new instance from this stream, so the source PRG advances too.\n clone() {\n if (this.destroyed)\n throw new Error('cannot use destroyed PRG');\n return new _XorStreamPRG(this.cipher, this.blockLen, this.keyLen, this.nonceLen, this.randomBytes(this.state.length));\n }\n // Zeroes the current state, leftover buffer, and marks the instance destroyed.\n // The instance fails closed: any later randomBytes()/addEntropy()/clone() throws instead\n // of silently continuing from zero key||nonce state (which would yield predictable output).\n clean() {\n this.pos = 0;\n this.ctr = 0;\n this.buf.fill(0);\n this.state.fill(0);\n this.destroyed = true;\n }\n}\n/**\n * Creates a PRG constructor from a stream cipher.\n * @param cipher - Stream cipher used to fill output blocks.\n * @param blockLen - Keystream block length in bytes.\n * @param keyLen - Internal key length in bytes.\n * @param nonceLen - Internal nonce length in bytes.\n * @returns PRG factory for seeded concrete `_XorStreamPRG` instances.\n * @example\n * Builds a PRG from XChaCha20 and reads bytes from a randomly seeded instance.\n * ```ts\n * import { xchacha20 } from '@noble/ciphers/chacha.js';\n * import { createPRG } from '@noble/ciphers/_arx.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const seed = randomBytes(32);\n * const init = createPRG(xchacha20, 64, 32, 24);\n * const prg = init(seed);\n * prg.randomBytes(8);\n * ```\n */\nexport const createPRG = (cipher, blockLen, keyLen, nonceLen) => {\n return ((seed = randomBytes(32)) => new _XorStreamPRG(cipher, blockLen, keyLen, nonceLen, seed));\n};\n", "/**\n * Poly1305 ({@link https://cr.yp.to/mac/poly1305-20050329.pdf | PDF},\n * {@link https://en.wikipedia.org/wiki/Poly1305 | wiki})\n * is a fast and parallel secret-key message-authentication code suitable for\n * a wide variety of applications. It was standardized in\n * {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and is now used in TLS 1.3.\n *\n * Polynomial MACs are not perfect for every situation:\n * they lack Random Key Robustness: the MAC can be forged, and can't be used in PAKE schemes.\n * See {@link https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/ | the invisible salamanders attack writeup}.\n * To combat invisible salamanders, `hash(key)` can be included in ciphertext,\n * however, this would violate ciphertext indistinguishability:\n * an attacker would know which key was used - so `HKDF(key, i)`\n * could be used instead.\n *\n * Check out the {@link https://cr.yp.to/mac.html | original website}.\n * Based on public-domain {@link https://github.com/floodyberry/poly1305-donna | poly1305-donna}.\n * @module\n */\n// prettier-ignore\nimport { abytes, aexists, aoutput, clean, copyBytes, wrapMacConstructor } from \"./utils.js\";\n// A simple-loop reference version (`poly1305_small`) lives in\n// `test/misc/micro-ciphers.ts`, provided for auditability.\n// Little-endian 2-byte load used by the Poly1305 limb decomposition.\nfunction u8to16(a, i) {\n return (a[i++] & 0xff) | ((a[i++] & 0xff) << 8);\n}\n/**\n * Incremental Poly1305 MAC state.\n * Prefer `poly1305()` for one-shot use.\n * @param key - 32-byte Poly1305 one-time key.\n * @example\n * Feeds one chunk into an incremental Poly1305 state with a fresh one-time key.\n *\n * ```ts\n * import { Poly1305 } from '@noble/ciphers/_poly1305.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const mac = new Poly1305(key);\n * mac.update(new Uint8Array([1, 2, 3]));\n * mac.digest();\n * ```\n */\nexport class Poly1305 {\n blockLen = 16;\n outputLen = 16;\n buffer = new Uint8Array(16);\n r = new Uint16Array(10); // Allocating 1 array with .subarray() here is slower than 3\n h = new Uint16Array(10);\n pad = new Uint16Array(8);\n pos = 0;\n finished = false;\n destroyed = false;\n // Can be speed-up using BigUint64Array, at the cost of complexity\n constructor(key) {\n key = copyBytes(abytes(key, 32, 'key'));\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 // RFC 8439 \u00A72.5.1 / RFC 7539 \u00A72.5.1 clamp r before multiplication.\n // These masks unpack that clamped value into 13-bit limbs, while pad\n // keeps the raw s half for finalize().\n // {@link https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47 | poly1305-donna reference}\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++)\n this.pad[i] = u8to16(key, 16 + 2 * i);\n }\n process(data, offset, isLast = false) {\n // RFC 8439 \u00A72.5 / \u00A72.5.1 and RFC 7539 \u00A72.5 / \u00A72.5.1 add an extra high\n // bit to every full 16-byte block. The final partial block gets its\n // explicit `1` byte during digestInto(), so `hibit` stays zero there.\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 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 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 let c = 0;\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 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 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 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 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 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 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 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 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 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 c = ((c << 2) + c) | 0;\n c = (c + d0) | 0;\n d0 = c & 0x1fff;\n c = c >>> 13;\n d1 += c;\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 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 // RFC 8439 \u00A72.5 / RFC 7539 \u00A72.5 reduce modulo 2^130-5 before repacking\n // to 16-bit words and adding the raw s half.\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 let mask = (c ^ 1) - 1;\n for (let i = 0; i < 10; i++)\n g[i] &= mask;\n mask = ~mask;\n for (let i = 0; i < 10; i++)\n 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 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 clean(g);\n }\n update(data) {\n aexists(this);\n abytes(data);\n data = copyBytes(data);\n const { buffer, blockLen } = this;\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\n if (take === blockLen) {\n for (; blockLen <= len - pos; pos += blockLen)\n 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 // `aexists(this)` guards update/digest paths, so destroy must mark the instance unusable too.\n this.destroyed = true;\n clean(this.h, this.r, this.buffer, this.pad);\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const { buffer, h } = this;\n let { pos } = this;\n if (pos) {\n // RFC 8439 \u00A72.5 / RFC 7539 \u00A72.5: the final short block appends a\n // single `0x01` byte and zero-fills the remaining bytes before the\n // last multiplication step.\n buffer[pos++] = 1;\n for (; pos < 16; pos++)\n 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 }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n // Copy out before destroy() zeroes the internal buffer.\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n}\n/**\n * Poly1305 MAC from RFC 8439.\n * @param msg - Message bytes to authenticate.\n * @param key - 32-byte Poly1305 one-time key.\n * @returns 16-byte authentication tag.\n * @example\n * Authenticates one message with a one-shot Poly1305 call and a fresh key.\n *\n * ```ts\n * import { poly1305 } from '@noble/ciphers/_poly1305.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * poly1305(new Uint8Array(), key);\n * ```\n */\nexport const poly1305 = /* @__PURE__ */ wrapMacConstructor(32, (key) => new Poly1305(key));\n", "/**\n * ChaCha stream cipher, released\n * in 2008. Developed after Salsa20, ChaCha aims to increase diffusion per round.\n * It was standardized in\n * {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and\n * is now used in TLS 1.3.\n *\n * {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | XChaCha20}\n * extended-nonce variant is also provided. Similar to XSalsa, it's safe to use with\n * randomly-generated nonces.\n *\n * Check out\n * {@link http://cr.yp.to/chacha/chacha-20080128.pdf | PDF},\n * {@link https://en.wikipedia.org/wiki/Salsa20 | wiki}, and\n * {@link https://cr.yp.to/chacha.html | website}.\n *\n * @module\n */\nimport { createCipher, createPRG, rotl } from \"./_arx.js\";\nimport { poly1305 } from \"./_poly1305.js\";\nimport { abytes, clean, equalBytes, getOutput, isLE, swap32IfBE, u64Lengths, wrapCipher, } from \"./utils.js\";\n/**\n * ChaCha core function. Uses an unrolled loop (chachaCore, hchacha) - 4x\n * faster than a simple loop, but larger & harder to read. A simple-loop\n * reference version lives in `test/misc/micro-ciphers.ts`;\n * `test/arx.test.ts` keeps the two aligned.\n * The specific implementation is selected in `createCipher` below.\n */\n/** RFC 8439 \u00A72.3 block core for `state = constants | key | counter | nonce`. */\n// prettier-ignore\nfunction chachaCore(s, k, n, out, cnt, rounds = 20) {\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 Nonce Nonce Nonce\n // Save state to temporary variables\n let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;\n for (let r = 0; r < rounds; r += 2) {\n x00 = (x00 + x04) | 0;\n x12 = rotl(x12 ^ x00, 16);\n x08 = (x08 + x12) | 0;\n x04 = rotl(x04 ^ x08, 12);\n x00 = (x00 + x04) | 0;\n x12 = rotl(x12 ^ x00, 8);\n x08 = (x08 + x12) | 0;\n x04 = rotl(x04 ^ x08, 7);\n x01 = (x01 + x05) | 0;\n x13 = rotl(x13 ^ x01, 16);\n x09 = (x09 + x13) | 0;\n x05 = rotl(x05 ^ x09, 12);\n x01 = (x01 + x05) | 0;\n x13 = rotl(x13 ^ x01, 8);\n x09 = (x09 + x13) | 0;\n x05 = rotl(x05 ^ x09, 7);\n x02 = (x02 + x06) | 0;\n x14 = rotl(x14 ^ x02, 16);\n x10 = (x10 + x14) | 0;\n x06 = rotl(x06 ^ x10, 12);\n x02 = (x02 + x06) | 0;\n x14 = rotl(x14 ^ x02, 8);\n x10 = (x10 + x14) | 0;\n x06 = rotl(x06 ^ x10, 7);\n x03 = (x03 + x07) | 0;\n x15 = rotl(x15 ^ x03, 16);\n x11 = (x11 + x15) | 0;\n x07 = rotl(x07 ^ x11, 12);\n x03 = (x03 + x07) | 0;\n x15 = rotl(x15 ^ x03, 8);\n x11 = (x11 + x15) | 0;\n x07 = rotl(x07 ^ x11, 7);\n x00 = (x00 + x05) | 0;\n x15 = rotl(x15 ^ x00, 16);\n x10 = (x10 + x15) | 0;\n x05 = rotl(x05 ^ x10, 12);\n x00 = (x00 + x05) | 0;\n x15 = rotl(x15 ^ x00, 8);\n x10 = (x10 + x15) | 0;\n x05 = rotl(x05 ^ x10, 7);\n x01 = (x01 + x06) | 0;\n x12 = rotl(x12 ^ x01, 16);\n x11 = (x11 + x12) | 0;\n x06 = rotl(x06 ^ x11, 12);\n x01 = (x01 + x06) | 0;\n x12 = rotl(x12 ^ x01, 8);\n x11 = (x11 + x12) | 0;\n x06 = rotl(x06 ^ x11, 7);\n x02 = (x02 + x07) | 0;\n x13 = rotl(x13 ^ x02, 16);\n x08 = (x08 + x13) | 0;\n x07 = rotl(x07 ^ x08, 12);\n x02 = (x02 + x07) | 0;\n x13 = rotl(x13 ^ x02, 8);\n x08 = (x08 + x13) | 0;\n x07 = rotl(x07 ^ x08, 7);\n x03 = (x03 + x04) | 0;\n x14 = rotl(x14 ^ x03, 16);\n x09 = (x09 + x14) | 0;\n x04 = rotl(x04 ^ x09, 12);\n x03 = (x03 + x04) | 0;\n x14 = rotl(x14 ^ x03, 8);\n x09 = (x09 + x14) | 0;\n x04 = rotl(x04 ^ x09, 7);\n }\n // RFC 8439 \u00A72.3 / \u00A72.3.1: add the original state words back in state order.\n let oi = 0;\n out[oi++] = (y00 + x00) | 0;\n out[oi++] = (y01 + x01) | 0;\n out[oi++] = (y02 + x02) | 0;\n out[oi++] = (y03 + x03) | 0;\n out[oi++] = (y04 + x04) | 0;\n out[oi++] = (y05 + x05) | 0;\n out[oi++] = (y06 + x06) | 0;\n out[oi++] = (y07 + x07) | 0;\n out[oi++] = (y08 + x08) | 0;\n out[oi++] = (y09 + x09) | 0;\n out[oi++] = (y10 + x10) | 0;\n out[oi++] = (y11 + x11) | 0;\n out[oi++] = (y12 + x12) | 0;\n out[oi++] = (y13 + x13) | 0;\n out[oi++] = (y14 + x14) | 0;\n out[oi++] = (y15 + x15) | 0;\n}\n/**\n * hchacha hashes key and nonce into key' and nonce' for xchacha20.\n * Algorithmically identical to `hchacha_small` from `test/misc/micro-ciphers.ts`,\n * but this exported path normalizes word order on big-endian hosts.\n * Reuses `chachaCore` and subtracts its feed-forward, keeping the hot per-block\n * path untouched.\n * @param s - Sigma constants as 32-bit words.\n * @param k - Key words.\n * @param i - Nonce-prefix words.\n * @param out - Output buffer for the derived subkey.\n * @example\n * Derives the XChaCha subkey from sigma, key, and nonce-prefix words.\n *\n * ```ts\n * const sigma = new Uint32Array(4);\n * const key = new Uint32Array(8);\n * const nonce = new Uint32Array(4);\n * const out = new Uint32Array(8);\n * hchacha(sigma, key, nonce, out);\n * ```\n */\n// prettier-ignore\nexport function hchacha(s, k, i, out) {\n // Runs the shared chachaCore permutation, then subtracts the RFC 8439 feed-forward\n // it applies, recovering the raw permutation words hchacha needs.\n // LE hosts read the caller arrays in place (no copies); BE hosts get\n // byte-swapped scratch copies, wiped before returning.\n const s2 = isLE ? s : swap32IfBE(s.slice(0, 4));\n const k2 = isLE ? k : swap32IfBE(k.slice(0, 8));\n const i2 = isLE ? i : swap32IfBE(i.slice(0, 4));\n const t = new Uint32Array(16);\n chachaCore(s2, k2, i2.subarray(1), t, i2[0]);\n let oi = 0;\n out[oi++] = (t[0] - s2[0]) | 0;\n out[oi++] = (t[1] - s2[1]) | 0;\n out[oi++] = (t[2] - s2[2]) | 0;\n out[oi++] = (t[3] - s2[3]) | 0;\n out[oi++] = (t[12] - i2[0]) | 0;\n out[oi++] = (t[13] - i2[1]) | 0;\n out[oi++] = (t[14] - i2[2]) | 0;\n out[oi++] = (t[15] - i2[3]) | 0;\n swap32IfBE(out);\n if (!isLE)\n clean(s2, k2, i2);\n clean(t);\n}\n/**\n * Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter.\n * The nonce/counter layout still reserves 8 counter bytes internally, but the shared public\n * `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts`\n * near `MAX_COUNTER` for the full counter-policy rationale.\n * @param key - 16-byte or 32-byte key.\n * @param nonce - 8-byte nonce.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Initial block counter.\n * @returns Encrypted or decrypted bytes.\n * @example\n * Encrypts bytes with the original 8-byte-nonce ChaCha variant and a fresh key/nonce.\n *\n * ```ts\n * import { chacha20orig } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(8);\n * chacha20orig(key, nonce, new Uint8Array(4));\n * ```\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 smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance.\n * @param key - 32-byte key.\n * @param nonce - 12-byte nonce.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Initial block counter.\n * @returns Encrypted or decrypted bytes.\n * @example\n * Encrypts bytes with the RFC 8439 ChaCha20 stream cipher and a fresh key/nonce.\n *\n * ```ts\n * import { chacha20 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(12);\n * chacha20(key, nonce, new Uint8Array(4));\n * ```\n */\nexport const chacha20 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n allowShortKeys: false,\n});\n/**\n * XChaCha eXtended-nonce ChaCha. With 24-byte nonce, it's safe to make it random (CSPRNG).\n * See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}.\n * The nonce/counter layout still reserves 8 counter bytes internally, but the shared public\n * `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts`\n * near `MAX_COUNTER` for the full counter-policy rationale.\n * @param key - 32-byte key.\n * @param nonce - 24-byte extended nonce.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Initial block counter.\n * @returns Encrypted or decrypted bytes.\n * @example\n * Encrypts bytes with XChaCha20 using a fresh key and random 24-byte nonce.\n *\n * ```ts\n * import { xchacha20 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(24);\n * xchacha20(key, nonce, new Uint8Array(4));\n * ```\n */\nexport const xchacha20 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 8,\n extendNonceFn: hchacha,\n allowShortKeys: false,\n});\n/**\n * Reduced 8-round chacha, described in original paper.\n * @param key - 32-byte key.\n * @param nonce - 12-byte nonce.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Initial block counter.\n * @returns Encrypted or decrypted bytes.\n * @example\n * Uses the reduced 8-round variant for non-critical workloads with a fresh key/nonce.\n *\n * ```ts\n * import { chacha8 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(12);\n * chacha8(key, nonce, new Uint8Array(4));\n * ```\n */\nexport const chacha8 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n rounds: 8,\n});\n/**\n * Reduced 12-round chacha, described in original paper.\n * @param key - 32-byte key.\n * @param nonce - 12-byte nonce.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Initial block counter.\n * @returns Encrypted or decrypted bytes.\n * @example\n * Uses the reduced 12-round variant for non-critical workloads with a fresh key/nonce.\n *\n * ```ts\n * import { chacha12 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(12);\n * chacha12(key, nonce, new Uint8Array(4));\n * ```\n */\nexport const chacha12 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n rounds: 12,\n});\n// Test-only hook: exposes the unrolled production core so tests can compare it\n// with the simple/reference core from `test/misc/micro-ciphers.ts`.\nexport const __TESTS = /* @__PURE__ */ Object.freeze({ chachaCore });\n// RFC 8439 \u00A72.8.1 pad16(x): shared zero block for AAD/ciphertext padding.\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\n// RFC 8439 \u00A72.8 / \u00A72.8.1: aligned inputs add nothing, otherwise append 16-(len%16) zero bytes.\nconst updatePadded = (h, msg) => {\n h.update(msg);\n const leftover = msg.length % 16;\n if (leftover)\n h.update(ZEROS16.subarray(leftover));\n};\n// RFC 8439 \u00A72.6.1 poly1305_key_gen returns `block[0..31]`, so AEAD key\n// generation only needs 32 zero bytes.\nconst ZEROS32 = /* @__PURE__ */ new Uint8Array(32);\nfunction computeTag(fn, key, nonce, ciphertext, AAD) {\n if (AAD !== undefined)\n abytes(AAD, undefined, 'AAD');\n // RFC 8439 \u00A72.6 / \u00A72.8: derive the Poly1305 one-time key from counter 0,\n // then MAC AAD || pad16(AAD) || ciphertext || pad16(ciphertext) || len(AAD) || len(ciphertext).\n const authKey = fn(key, nonce, ZEROS32);\n const lengths = u64Lengths(ciphertext.length, AAD ? AAD.length : 0, true);\n // Methods below can be replaced with\n // `return poly1305_computeTag_small(authKey, lengths, ciphertext, AAD)`\n // from `test/misc/micro-ciphers.ts`.\n const h = poly1305.create(authKey);\n if (AAD)\n updatePadded(h, AAD);\n updatePadded(h, ciphertext);\n h.update(lengths);\n const res = h.digest();\n clean(authKey, lengths);\n return res;\n}\n/**\n * AEAD algorithm from RFC 8439.\n * Salsa20 and chacha (RFC 8439) use poly1305 differently.\n * We could have composed them, 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 = (xorStream) => (key, nonce, AAD) => {\n // This borrows caller key/nonce/AAD buffers by reference; mutating them after construction\n // changes future encrypt/decrypt results.\n const tagLength = 16;\n return {\n encrypt(plaintext, output) {\n const plength = plaintext.length;\n output = getOutput(plength + tagLength, output, false);\n output.set(plaintext);\n const oPlain = output.subarray(0, -tagLength);\n // RFC 8439 \u00A72.8: payload encryption starts at counter 1 because counter 0 produced the OTK.\n xorStream(key, nonce, oPlain, oPlain, 1);\n const tag = computeTag(xorStream, key, nonce, oPlain, AAD);\n output.set(tag, plength); // append tag\n clean(tag);\n return output;\n },\n decrypt(ciphertext, output) {\n output = getOutput(ciphertext.length - tagLength, output, false);\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = computeTag(xorStream, key, nonce, data, AAD);\n // RFC 8439 \u00A72.8 / \u00A74: authenticate ciphertext before decrypting it, and compare tags with\n // the constant-time equalBytes() helper rather than decrypting speculative plaintext first.\n if (!equalBytes(passedTag, tag)) {\n clean(tag);\n throw new Error('invalid tag');\n }\n output.set(ciphertext.subarray(0, -tagLength));\n // Actual decryption\n xorStream(key, nonce, output, output, 1); // start stream with i=1\n clean(tag);\n return output;\n },\n };\n};\n/**\n * ChaCha20-Poly1305 from RFC 8439.\n *\n * Unsafe to use random nonces under the same key, due to collision chance.\n * Prefer XChaCha instead.\n * @param key - 32-byte key.\n * @param nonce - 12-byte nonce.\n * @param AAD - Additional authenticated data.\n * @returns AEAD cipher instance.\n * @example\n * Encrypts and authenticates plaintext with a fresh key and nonce.\n *\n * ```ts\n * import { chacha20poly1305 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(12);\n * const aad = new TextEncoder().encode('session metadata');\n * const cipher = chacha20poly1305(key, nonce, aad);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const chacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 12, tagLength: 16, withAAD: true }, \n/* @__PURE__ */ _poly1305_aead(chacha20));\n/**\n * XChaCha20-Poly1305 extended-nonce chacha.\n *\n * Can be safely used with random nonces (CSPRNG).\n * See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}.\n * @param key - 32-byte key.\n * @param nonce - 24-byte nonce.\n * @param AAD - Additional authenticated data.\n * @returns AEAD cipher instance.\n * @example\n * Encrypts and authenticates plaintext with a fresh key and random 24-byte nonce.\n *\n * ```ts\n * import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(24);\n * const aad = new TextEncoder().encode('session metadata');\n * const cipher = xchacha20poly1305(key, nonce, aad);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const xchacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16, withAAD: true }, \n/* @__PURE__ */ _poly1305_aead(xchacha20));\n/**\n * Chacha20 CSPRNG (cryptographically secure pseudorandom number generator).\n * It's best to limit usage to non-production, non-critical cases: for example, test-only.\n * Compatible with libtomcrypt. It does not have a specification, so unclear how secure it is.\n * @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted,\n * only 32 random bytes are mixed into the 40-byte state.\n * @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.\n * @example\n * Seeds the test-only ChaCha20 DRBG from fresh entropy.\n *\n * ```ts\n * import { rngChacha20 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const seed = randomBytes(32);\n * const prg = rngChacha20(seed);\n * prg.randomBytes(8);\n * ```\n */\nexport const rngChacha20 = /* @__PURE__ */ createPRG(chacha20orig, 64, 32, 8);\n/**\n * Chacha20/8 CSPRNG (cryptographically secure pseudorandom number generator).\n * It's best to limit usage to non-production, non-critical cases: for example, test-only.\n * Faster than `rngChacha20`.\n * @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted,\n * only 32 random bytes are mixed into the 44-byte state.\n * @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.\n * @example\n * Seeds the faster test-only ChaCha8 DRBG from fresh entropy.\n *\n * ```ts\n * import { rngChacha8 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const seed = randomBytes(32);\n * const prg = rngChacha8(seed);\n * prg.randomBytes(8);\n * ```\n */\nexport const rngChacha8 = /* @__PURE__ */ createPRG(chacha8, 64, 32, 12);\n", "/**\n * GHash from AES-GCM and its little-endian \"mirror image\" Polyval from AES-SIV.\n *\n * Implemented in terms of GHash with conversion function for keys\n * GCM GHASH from\n * {@link https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf | NIST SP800-38d},\n * SIV from\n * {@link https://www.rfc-editor.org/rfc/rfc8452 | RFC 8452}.\n *\n * GHASH modulo: x^128 + x^7 + x^2 + x + 1\n * POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1\n *\n * @module\n */\nimport { abytes, aexists, aoutput32, clean, copyBytes, createView, isLE, swap32IfBE, swap8IfBE, u32, wrapMacConstructor, } from \"./utils.js\";\nconst BLOCK_SIZE = 16;\n// TODO: rewrite\n// temporary padding buffer\n// ZEROS32 aliases these bytes, so clean(ZEROS32) also resets this shared tail-padding scratch.\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\nconst ZEROS32 = /* @__PURE__ */ u32(ZEROS16);\n// GHASH reduces modulo x^128 + x^7 + x^2 + x + 1, so the low-degree terms\n// x^7 + x^2 + x + 1 become bits `11100001` = 0xe1 in R = 0xe1 || 0^120.\nconst POLY = 0xe1;\n// v = 2*v % POLY\n// NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x\n// Montgomery ladder can multiply any field element with this doubling step;\n// addition stays simple xor.\nconst mul2 = (s0, s1, s2, s3) => {\n const hiBit = s3 & 1;\n return {\n s3: (s2 << 31) | (s3 >>> 1),\n s2: (s1 << 31) | (s2 >>> 1),\n s1: (s0 << 31) | (s1 >>> 1),\n // NIST SP 800-38D \u00A76.3 applies `V >> 1` and XORs R on carry. In this\n // 4x32-bit split, R = 0xe1 || 0^120 lives in the top byte of s0.\n s0: (s0 >>> 1) ^ ((POLY << 24) & -(hiBit & 1)), // reduce % poly\n };\n};\n// Per-word part of RFC 8452 `ByteReverse`; callers also reverse the 32-bit word order.\nconst swapLE = (n) => (((n >>> 0) & 0xff) << 24) |\n (((n >>> 8) & 0xff) << 16) |\n (((n >>> 16) & 0xff) << 8) |\n ((n >>> 24) & 0xff) |\n 0;\n// POLYVAL first applies RFC 8452's per-word byte reversal, then re-normalizes\n// host-endian u32 loads to the little-endian word value `_updateBlock()` expects.\nconst swap8IfLE = (n) => swap8IfBE(swapLE(n));\n/**\n * `mulX_GHASH(ByteReverse(H))` from RFC 8452 Appendix A.\n * @param k mutated in place\n */\nexport function _toGHASHKey(k) {\n // The input is the original POLYVAL key H; reverse() materializes\n // RFC 8452's `ByteReverse(H)` before the GHASH mulX step.\n k.reverse();\n const hiBit = k[15] & 1;\n // k >>= 1\n let carry = 0;\n for (let i = 0; i < k.length; i++) {\n const t = k[i];\n k[i] = (t >>> 1) | carry;\n carry = (t & 1) << 7;\n }\n k[0] ^= -hiBit & 0xe1; // if (hiBit) n ^= 0xe1000000000000000000000000000000;\n return k;\n}\n// Precompute-window heuristic only: larger inputs trade memory for fewer table lookups.\n// Any caller-provided length hint still collapses to one of the supported windows {2, 4, 8}.\nconst estimateWindow = (bytes) => {\n if (bytes > 64 * 1024)\n return 8;\n if (bytes > 1024)\n return 4;\n return 2;\n};\n/**\n * Incremental GHASH state for AES-GCM.\n * @param key - 16-byte GHASH key.\n * @param expectedLength - Expected message length for table sizing.\n * Chunking is segment-based, not hash-streaming: every `update()` call is zero-padded\n * to the next 16-byte boundary before it is absorbed. This matches the internal AES/GCM\n * use where AAD, payload, and length block are separate padded segments.\n * @example\n * Feeds one ciphertext block into an incremental GHASH state with a fresh hash key.\n *\n * ```ts\n * import { GHASH } from '@noble/ciphers/_polyval.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * const mac = new GHASH(key);\n * mac.update(new Uint8Array(16));\n * mac.digest();\n * ```\n */\nexport class GHASH {\n blockLen = BLOCK_SIZE;\n outputLen = BLOCK_SIZE;\n s0 = 0;\n s1 = 0;\n s2 = 0;\n s3 = 0;\n finished = false;\n destroyed = false;\n t;\n W;\n windowSize;\n // We select bits per window adaptively based on expectedLength\n constructor(key, expectedLength) {\n abytes(key, 16, 'key');\n key = copyBytes(key);\n const kView = createView(key);\n let k0 = kView.getUint32(0, false);\n let k1 = kView.getUint32(4, false);\n let k2 = kView.getUint32(8, false);\n let k3 = kView.getUint32(12, false);\n // generate table of doubled keys (half of montgomery ladder)\n const doubles = [];\n for (let i = 0; i < 128; i++) {\n doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) });\n ({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2(k0, k1, k2, k3));\n }\n const W = estimateWindow(expectedLength || 1024);\n if (![1, 2, 4, 8].includes(W))\n throw new Error('ghash: invalid window size, expected 2, 4 or 8');\n this.W = W;\n const bits = 128; // always 128 bits;\n const windows = bits / W;\n const windowSize = (this.windowSize = 2 ** W);\n const items = [];\n // Create precompute table for window of W bits\n for (let w = 0; w < windows; w++) {\n // truth table: 00, 01, 10, 11\n for (let byte = 0; byte < windowSize; byte++) {\n // prettier-ignore\n let s0 = 0, s1 = 0, s2 = 0, s3 = 0;\n for (let j = 0; j < W; j++) {\n const bit = (byte >>> (W - j - 1)) & 1;\n if (!bit)\n continue;\n const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j];\n ((s0 ^= d0), (s1 ^= d1), (s2 ^= d2), (s3 ^= d3));\n }\n items.push({ s0, s1, s2, s3 });\n }\n }\n this.t = items;\n }\n _updateBlock(s0, s1, s2, s3) {\n ((s0 ^= this.s0), (s1 ^= this.s1), (s2 ^= this.s2), (s3 ^= this.s3));\n const { W, t, windowSize } = this;\n // prettier-ignore\n let o0 = 0, o1 = 0, o2 = 0, o3 = 0;\n const mask = (1 << W) - 1; // 2**W will kill performance.\n let w = 0;\n // NIST SP 800-38D \u00A76.3 interprets blocks as little-endian polynomials,\n // so the lookup walk consumes each word byte-by-byte from\n // least-significant to most-significant bits.\n for (const num of [s0, s1, s2, s3]) {\n for (let bytePos = 0; bytePos < 4; bytePos++) {\n const byte = (num >>> (8 * bytePos)) & 0xff;\n for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) {\n const bit = (byte >>> (W * bitPos)) & mask;\n const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit];\n ((o0 ^= e0), (o1 ^= e1), (o2 ^= e2), (o3 ^= e3));\n w += 1;\n }\n }\n }\n this.s0 = o0;\n this.s1 = o1;\n this.s2 = o2;\n this.s3 = o3;\n }\n update(data) {\n aexists(this);\n abytes(data);\n data = copyBytes(data);\n const b32 = u32(data);\n const blocks = Math.floor(data.length / BLOCK_SIZE);\n const left = data.length % BLOCK_SIZE;\n for (let i = 0; i < blocks; i++) {\n this._updateBlock(swap8IfBE(b32[i * 4 + 0]), swap8IfBE(b32[i * 4 + 1]), swap8IfBE(b32[i * 4 + 2]), swap8IfBE(b32[i * 4 + 3]));\n }\n if (left) {\n ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));\n // Tail blocks go through the shared ZEROS32 scratch, so they need the same host-endian\n // normalization as full blocks; otherwise segmented GHASH/POLYVAL updates diverge on BE.\n this._updateBlock(swap8IfBE(ZEROS32[0]), swap8IfBE(ZEROS32[1]), swap8IfBE(ZEROS32[2]), swap8IfBE(ZEROS32[3]));\n clean(ZEROS32); // clean tmp buffer\n }\n return this;\n }\n destroy() {\n // `aexists(this)` guards update/digest paths, so destroy must mark the instance unusable too.\n this.destroyed = true;\n const { t } = this;\n // Wipe the key-derived precompute table; scalar accumulator words remain,\n // but the destroyed guard blocks further use.\n // clean precompute table\n for (const elm of t) {\n ((elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0));\n }\n }\n digestInto(out) {\n aexists(this);\n // `digestInto(out)` is the no-allocation fast path, so callers must pass a\n // 32-bit-aligned buffer before we reinterpret it with `u32(out)`.\n aoutput32(out, this);\n this.finished = true;\n // NIST SP 800-38D \u00A76.4 returns the final 128-bit block Y_m.\n // `digestInto()` follows the relaxed `aoutput()` contract, so only\n // out[0..15] may be touched.\n const { s0, s1, s2, s3 } = this;\n const o32 = u32(out);\n o32[0] = s0;\n o32[1] = s1;\n o32[2] = s2;\n o32[3] = s3;\n // Only the tag words need host-endian normalization; oversized output tails are caller-owned.\n if (!isLE)\n swap32IfBE(o32.subarray(0, BLOCK_SIZE / 4));\n }\n digest() {\n const res = new Uint8Array(BLOCK_SIZE);\n this.digestInto(res);\n // `res` is independent of internal state, so it stays valid after destroy() wipes the table.\n this.destroy();\n return res;\n }\n}\n/**\n * Incremental POLYVAL state for AES-SIV.\n * @param key - 16-byte POLYVAL key.\n * @param expectedLength - Expected message length for table sizing.\n * Inherits GHASH's segment-padded `update()` behavior: each call is padded\n * independently to a 16-byte boundary before absorption.\n * @example\n * Feeds one block into an incremental POLYVAL state with a fresh hash key.\n *\n * ```ts\n * import { Polyval } from '@noble/ciphers/_polyval.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * const mac = new Polyval(key);\n * mac.update(new Uint8Array(16));\n * mac.digest();\n * ```\n */\nexport class Polyval extends GHASH {\n constructor(key, expectedLength) {\n abytes(key);\n // RFC 8452 Appendix A converts the POLYVAL key with\n // `mulX_GHASH(ByteReverse(H))`; copy first because `_toGHASHKey(...)`\n // mutates in place.\n const ghKey = _toGHASHKey(copyBytes(key));\n super(ghKey, expectedLength);\n clean(ghKey);\n }\n update(data) {\n aexists(this);\n abytes(data);\n data = copyBytes(data);\n const b32 = u32(data);\n const left = data.length % BLOCK_SIZE;\n const blocks = Math.floor(data.length / BLOCK_SIZE);\n for (let i = 0; i < blocks; i++) {\n // RFC 8452 Appendix A feeds `ByteReverse(X_i)` into GHASH, so POLYVAL\n // reverses the 32-bit word order in addition to the per-word byte swap.\n this._updateBlock(swap8IfLE(b32[i * 4 + 3]), swap8IfLE(b32[i * 4 + 2]), swap8IfLE(b32[i * 4 + 1]), swap8IfLE(b32[i * 4 + 0]));\n }\n if (left) {\n ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));\n this._updateBlock(swap8IfLE(ZEROS32[3]), swap8IfLE(ZEROS32[2]), swap8IfLE(ZEROS32[1]), swap8IfLE(ZEROS32[0]));\n clean(ZEROS32);\n }\n return this;\n }\n digestInto(out) {\n aexists(this);\n // `digestInto(out)` is the no-allocation fast path, so callers must pass a\n // 32-bit-aligned buffer before we reinterpret the output prefix with `u32(view)`.\n aoutput32(out, this);\n this.finished = true;\n // RFC 8452 Appendix A maps POLYVAL output back through `ByteReverse(...)`.\n // `digestInto()` follows the relaxed `aoutput()` contract, so only out[0..15] may be touched.\n const view = out.subarray(0, this.outputLen);\n const { s0, s1, s2, s3 } = this;\n const o32 = u32(view);\n o32[0] = s0;\n o32[1] = s1;\n o32[2] = s2;\n o32[3] = s3;\n swap32IfBE(o32);\n view.reverse();\n }\n}\n/**\n * GHash MAC for AES-GCM.\n * @param msg - Message bytes to authenticate.\n * @param key - 16-byte GHASH key.\n * @returns 16-byte authentication tag.\n * @example\n * Authenticates a short message with GHASH and a fresh hash key.\n *\n * ```ts\n * import { ghash } from '@noble/ciphers/_polyval.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * ghash(new Uint8Array(), key);\n * ```\n */\nexport const ghash = \n/* @__PURE__ */ wrapMacConstructor(16, (key, expectedLength) => new GHASH(key, expectedLength), (msg) => [msg.length]);\n/**\n * POLYVAL MAC for AES-SIV.\n * @param msg - Message bytes to authenticate.\n * @param key - 16-byte POLYVAL key.\n * @returns 16-byte authentication tag.\n * @example\n * Authenticates a short message with POLYVAL and a fresh hash key.\n *\n * ```ts\n * import { polyval } from '@noble/ciphers/_polyval.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * polyval(new Uint8Array(), key);\n * ```\n */\nexport const polyval = \n/* @__PURE__ */ wrapMacConstructor(16, (key, expectedLength) => new Polyval(key, expectedLength), (msg) => [msg.length]);\n", "/**\n * {@link https://en.wikipedia.org/wiki/Advanced_Encryption_Standard | AES}\n * a.k.a. Advanced Encryption Standard\n * is a variant of Rijndael block cipher, standardized by NIST in 2001.\n * We provide the fastest available pure JS implementation.\n *\n * `cipher = encrypt(block, key)`\n *\n * Data is split into 128-bit blocks.\n * Encrypted in 10/12/14 rounds (128/192/256 bits). In every round:\n * 1. **S-box**, table substitution\n * 2. **Shift rows**, cyclic shift left of all rows of data array\n * 3. **Mix columns**, multiplying every column by fixed polynomial\n * 4. **Add round key**, round_key xor i-th column of array\n *\n * Check out\n * {@link https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf | FIPS-197},\n * {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf | NIST 800-38G},\n * and {@link https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf | original proposal}.\n * @module\n */\nimport { ghash, polyval } from \"./_polyval.js\";\n// prettier-ignore\nimport { abytes, aexists, anumber, aoutput32, byteSwap, clean, complexOverlapBytes, concatBytes, copyBytes, createView, equalBytes, getOutput, isAligned32, isLE, overlapBytes, swap32IfBE, swap8IfBE, u32, u64Lengths, u8, wrapCipher, wrapMacConstructor } from \"./utils.js\";\nconst BLOCK_SIZE = 16;\n// AES operates on 16-byte blocks, i.e. 4 32-bit words.\nconst BLOCK_SIZE32 = 4;\n// Shared zero block (`0^128`) used by GCM's `H = CIPH_K(0^128)` / J0 scratch\n// and by CMAC / SIV helpers; callers take `.slice()` before mutating it.\nconst EMPTY_BLOCK = /* @__PURE__ */ new Uint8Array(BLOCK_SIZE);\n// RFC 5297 \u00A72.1 / \u00A72.4: S2V uses `<one> = 0^127 || 1` for the `n = 0` special case.\nconst ONE_BLOCK = /* @__PURE__ */ Uint8Array.from([\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,\n]);\nconst POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8\n// Validates plain AES key sizes only; AES-SIV's doubled-key contract is checked elsewhere.\nfunction validateKeyLength(key) {\n if (![16, 24, 32].includes(key.length))\n throw new Error('\"aes key\" expected Uint8Array of length 16/24/32, got length=' + key.length);\n}\n// TODO: remove multiplication, binary ops only\n// Doubles one GF(2^8) field element; callers are expected to stay in byte range.\n// FIPS 197 upd1 \u00A74.3 equation (4.5): XTIMES(b) left-shifts by one and, when\n// b7=1, reduces by m(x); using POLY=0x11b here yields the same byte result\n// as XORing with {1b} after the shift.\nfunction mul2(n) {\n return (n << 1) ^ (POLY & -(n >> 7));\n}\n// Shift-and-add multiplication in GF(2^8); callers are expected to pass byte values.\n// FIPS 197 upd1 \u00A74.3 equation (4.7): general products are XORs of repeated\n// XTIMES() multiples, e.g. {57}\u2022{13} = {57}\u2295{ae}\u2295{07}.\nfunction mul(a, b) {\n let res = 0;\n for (; b > 0; b >>= 1) {\n // Usual shift-and-add step in GF(2^8), not a scalar-multiplication ladder.\n res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time).\n a = mul2(a); // a = 2*a\n }\n return res;\n}\n/**\n * Increments a counter block with wrap around.\n * AES call sites here currently use the big-endian branch, but the helper supports both layouts.\n * NIST SP 800-38A Appendix B.1 and SP 800-38D \u00A76.2 increment the\n * least-significant/rightmost bits.\n * `isLE=false` matches that standard counter-block layout, while `isLE=true`\n * is a generic extension for non-AES callers.\n * The implementation keeps a 32-bit bitwise carry path, so `carry` is capped at `0xffffff00`;\n * larger values throw instead of silently overflowing before the next-byte propagation step.\n */\n// Keep the helper explicitly typed so `--isolatedDeclarations` can expose it\n// through the test-only `__TESTS` export without inference errors.\nconst incBytes = (data, isLE, carry = 1) => {\n // Carry is an increment count, not a signed delta; negatives would wrap through `| 0`.\n // Keep `carry + byte <= 0xffffffff` so the `| 0` / `>>> 8` path below\n // never truncates a real carry bit.\n if (!Number.isSafeInteger(carry) || carry < 0 || carry > 0xffffff00)\n throw new Error('incBytes: wrong carry ' + carry);\n abytes(data);\n for (let i = 0; i < data.length; i++) {\n const pos = !isLE ? data.length - 1 - i : i;\n carry = (carry + (data[pos] & 0xff)) | 0;\n data[pos] = carry & 0xff;\n carry >>>= 8;\n }\n};\n// AES S-box is generated using finite field inversion,\n// an affine transform, and xor of a constant 0x63.\nconst sbox = /* @__PURE__ */ (() => {\n const t = new Uint8Array(256);\n // Repeated multiplication by {03} walks all 255 nonzero field elements\n // once, so t[255 - i] is the multiplicative inverse of t[i] for the\n // affine step.\n for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x))\n t[i] = x;\n const box = new Uint8Array(256);\n // FIPS 197 upd1 \u00A75.1.1: SBOX({00}) = {63} because the inverse step leaves\n // {00} at {00}, then the affine transform xors in c = {63}.\n box[0] = 0x63;\n for (let i = 0; i < 255; i++) {\n let x = t[255 - i];\n x |= x << 8;\n box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff;\n }\n clean(t);\n return box;\n})();\n// FIPS 197 upd1 \u00A75.3.2: INVSBOX() is derived from SBOX() by swapping input\n// and output roles (Table 6).\n// `indexOf` is only used once at module init, so the quadratic setup cost stays off hot paths.\nconst invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j));\n// FIPS 197 upd1 \u00A75.2: ROTWORD([a0,a1,a2,a3]) = [a1,a2,a3,a0]; with this LE\n// word packing that is a right rotate by 8 bits.\nconst rotr32_8 = (n) => (n << 24) | (n >>> 8);\n// LE T-table helper: rotates one precomputed word by one byte so T1/T2/T3\n// reuse T0's substitution/mix result in the other byte lanes.\nconst rotl32_8 = (n) => (n << 8) | (n >>> 24);\n// T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes:\n// - LE instead of BE\n// - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23;\n// so index is u16, instead of u8. This speeds up things, unexpectedly\nfunction genTtable(sbox, fn) {\n if (sbox.length !== 256)\n throw new Error('wrong sbox length');\n const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j]));\n const T1 = T0.map(rotl32_8);\n const T2 = T1.map(rotl32_8);\n const T3 = T2.map(rotl32_8);\n // Pre-xor adjacent lanes so apply0123/applySbox can fetch two substituted\n // byte lanes per lookup in the LE round layout.\n const T01 = new Uint32Array(256 * 256);\n const T23 = new Uint32Array(256 * 256);\n const sbox2 = new Uint16Array(256 * 256);\n for (let i = 0; i < 256; i++) {\n for (let j = 0; j < 256; j++) {\n const idx = i * 256 + j;\n T01[idx] = T0[i] ^ T1[j];\n T23[idx] = T2[i] ^ T3[j];\n sbox2[idx] = (sbox[i] << 8) | sbox[j];\n }\n }\n return { sbox, sbox2, T0, T1, T2, T3, T01, T23 };\n}\n// Forward round precompute: the packed word stores the MIXCOLUMNS row\n// [{02},{01},{01},{03}] in LE byte-lane order, and the returned `sbox2`\n// is also reused by key expansion and the final round.\nconst tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2));\n// Inverse round precompute: the packed word stores the INVMIXCOLUMNS row\n// [{0e},{09},{0d},{0b}] in LE byte-lane order, and the tables are reused\n// by decrypt() and expandKeyDecLE().\nconst tableDecoding = /* @__PURE__ */ genTtable(invSbox, (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14));\n// FIPS 197 upd1 \u00A75.2 Table 5: left-most bytes of Rcon[j] = x^(j-1), generated by repeated XTIMES().\nconst xPowers = /* @__PURE__ */ (() => {\n const p = new Uint8Array(16);\n for (let i = 0, x = 1; i < 16; i++, x = mul2(x))\n p[i] = x;\n return p;\n})();\n/** Forward AES key expansion used across ECB/CBC/CTR/GCM/CMAC/KW-style paths. */\nfunction expandKeyLE(key) {\n abytes(key);\n const len = key.length;\n validateKeyLength(key);\n const { sbox2 } = tableEncoding;\n const toClean = [];\n // Copy on BE or misaligned inputs so the LE word normalization below never\n // mutates caller key bytes in place.\n if (!isLE || !isAligned32(key))\n toClean.push((key = copyBytes(key)));\n const k32 = swap32IfBE(u32(key));\n const Nk = k32.length;\n // `applySbox` normally reads one byte lane from each argument; repeating\n // `n` across all four lanes turns it into SUBWORD(n).\n const subByte = (n) => applySbox(sbox2, n, n, n, n);\n // AES key sizes are 16/24/32 bytes, so len + 28 yields the 44/52/60\n // schedule words from FIPS 197 \u00A75.2 / Table 3.\n const xk = new Uint32Array(len + 28); // expanded key\n xk.set(k32);\n // 4.3.1 Key expansion\n for (let i = Nk; i < xk.length; i++) {\n let t = xk[i - 1];\n if (i % Nk === 0)\n t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];\n else if (Nk > 6 && i % Nk === 4)\n t = subByte(t);\n xk[i] = xk[i - Nk] ^ t;\n }\n clean(...toClean);\n return xk;\n}\nfunction expandKeyDecLE(key) {\n const encKey = expandKeyLE(key);\n const xk = encKey.slice();\n const Nk = encKey.length;\n const { sbox2 } = tableEncoding;\n const { T0, T1, T2, T3 } = tableDecoding;\n // Local decrypt() walks round keys forward from xk[0], so reverse the\n // encryption round-key blocks first before applying the equivalent-inverse\n // middle-round transform.\n for (let i = 0; i < Nk; i += 4) {\n for (let j = 0; j < 4; j++)\n xk[i + j] = encKey[Nk - i - 4 + j];\n }\n clean(encKey);\n // Apply InvMixColumn to the reversed round keys using the same LE sbox2\n // packing as the forward path.\n // apply InvMixColumn except first & last round\n for (let i = 4; i < Nk - 4; i++) {\n const x = xk[i];\n const w = applySbox(sbox2, x, x, x, x);\n xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24];\n }\n return xk;\n}\n// Apply tables\nfunction apply0123(T01, T23, s0, s1, s2, s3) {\n // `T01` takes the low byte lane from `s0` plus the next lane from `s1`;\n // `T23` does the same for `s2`/`s3`.\n // Equivalent to `T0[s0&0xff] ^ T1[(s1>>>8)&0xff] ^ T2[(s2>>>16)&0xff] ^\n // T3[s3>>>24]`, but with two merged-table fetches.\n return (T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^\n T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]);\n}\nfunction applySbox(sbox2, s0, s1, s2, s3) {\n // `sbox2` packs two substituted byte lanes at a time in the same LE\n // layout used by the round code.\n // Equivalent to `SBOX(byte0(s0)) | SBOX(byte1(s1))<<8 |\n // SBOX(byte2(s2))<<16 | SBOX(byte3(s3))<<24`.\n return (sbox2[(s0 & 0xff) | (s1 & 0xff00)] |\n (sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16));\n}\nfunction encrypt(xk, s0, s1, s2, s3) {\n const { sbox2, T01, T23 } = tableEncoding;\n let k = 0;\n ((s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]));\n // `xk` has Nr+1 round-key blocks, so after the initial AddRoundKey and the\n // final S-box-only round there are Nr-1 full table/MixColumns rounds left.\n const rounds = xk.length / 4 - 2;\n for (let i = 0; i < rounds; i++) {\n const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);\n const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);\n const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);\n const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);\n ((s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3));\n }\n // last round (without mixcolumns, so using SBOX2 table)\n const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);\n const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);\n const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);\n const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2);\n return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\n// Can't be merged with encrypt: arg positions for apply0123 / applySbox are different\nfunction decrypt(xk, s0, s1, s2, s3) {\n const { sbox2, T01, T23 } = tableDecoding;\n let k = 0;\n ((s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]));\n // With `expandKeyDecLE()` the round keys are already reversed and middle\n // rounds are InvMixColumns-adjusted, so this loop follows the equivalent\n // inverse cipher order directly.\n const rounds = xk.length / 4 - 2;\n for (let i = 0; i < rounds; i++) {\n const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1);\n const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2);\n const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3);\n const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0);\n ((s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3));\n }\n // Final equivalent-inverse round omits InvMixColumns, so use inverse\n // S-box lanes in InvShiftRows order.\n const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1);\n const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2);\n const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3);\n const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0);\n return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\nfunction ctrCounter(xk, nonce, src, dst) {\n abytes(nonce, BLOCK_SIZE, 'nonce');\n abytes(src);\n const srcLen = src.length;\n dst = getOutput(srcLen, dst);\n complexOverlapBytes(src, dst);\n // Internal helper: mutate `nonce` in place as the live counter block so\n // each encrypted block uses the next CTR value.\n const ctr = nonce;\n const c32 = u32(ctr);\n const src32 = u32(src);\n const dst32 = u32(dst);\n // process blocks\n for (let i = 0; i + 4 <= src32.length; i += 4) {\n const { s0, s1, s2, s3 } = encrypt(xk, swap8IfBE(c32[0]), swap8IfBE(c32[1]), swap8IfBE(c32[2]), swap8IfBE(c32[3]));\n dst32[i + 0] = src32[i + 0] ^ swap8IfBE(s0);\n dst32[i + 1] = src32[i + 1] ^ swap8IfBE(s1);\n dst32[i + 2] = src32[i + 2] ^ swap8IfBE(s2);\n dst32[i + 3] = src32[i + 3] ^ swap8IfBE(s3);\n // Full 128 bit big-endian counter with wrap around. Same fixed-shape\n // 16-byte carry walk as incBytes(ctr, false, 1), inlined to skip its\n // per-call argument validation on the per-block hot path.\n for (let j = BLOCK_SIZE - 1, carry = 1; j >= 0; j--) {\n carry = (carry + ctr[j]) | 0;\n ctr[j] = carry & 0xff;\n carry >>>= 8;\n }\n }\n // NIST SP 800-38A CTR mode uses the leading `u` bits of the next output\n // block for the final short block.\n // It's possible to handle > u32 fast, but is it worth it?\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n const { s0, s1, s2, s3 } = encrypt(xk, swap8IfBE(c32[0]), swap8IfBE(c32[1]), swap8IfBE(c32[2]), swap8IfBE(c32[3]));\n const b32 = new Uint32Array([s0, s1, s2, s3]);\n swap32IfBE(b32);\n const buf = u8(b32);\n for (let i = start, pos = 0; i < srcLen; i++, pos++)\n dst[i] = src[i] ^ buf[pos];\n clean(b32);\n }\n // Unsafe mutable-counter API only advances whole blocks. Callers that want to\n // resume after consuming part of this block must re-run from the same counter\n // with left-padding and strip the already-consumed prefix themselves.\n return dst;\n}\n// AES CTR with overflowing 32 bit counter\n// It's possible to do 32le significantly simpler (and probably faster) by using u32.\n// But, we need both, and perf bottleneck is in ghash anyway.\n// Unsafe 32-bit CTR helper: mutates `nonce` in place, expects aligned `src`/`dst`,\n// and uses `isLE` to choose which 32-bit counter word is incremented.\nfunction ctr32(xk, isLE, nonce, src, dst) {\n abytes(nonce, BLOCK_SIZE, 'nonce');\n abytes(src);\n dst = getOutput(src.length, dst);\n const ctr = nonce; // write new value to nonce, so it can be re-used\n const c32 = u32(ctr);\n const view = createView(ctr);\n const src32 = u32(src);\n const dst32 = u32(dst);\n // NIST SP 800-38D GCTR increments the rightmost 32 bits of J0, while\n // RFC 8452 AES-GCM-SIV increments the first 32 bits as a little-endian u32.\n const ctrPos = isLE ? 0 : 12;\n const srcLen = src.length;\n let ctrNum = view.getUint32(ctrPos, isLE); // read current counter value\n // process blocks\n for (let i = 0; i + 4 <= src32.length; i += 4) {\n const { s0, s1, s2, s3 } = encrypt(xk, swap8IfBE(c32[0]), swap8IfBE(c32[1]), swap8IfBE(c32[2]), swap8IfBE(c32[3]));\n dst32[i + 0] = src32[i + 0] ^ swap8IfBE(s0);\n dst32[i + 1] = src32[i + 1] ^ swap8IfBE(s1);\n dst32[i + 2] = src32[i + 2] ^ swap8IfBE(s2);\n dst32[i + 3] = src32[i + 3] ^ swap8IfBE(s3);\n ctrNum = (ctrNum + 1) >>> 0; // u32 wrap\n view.setUint32(ctrPos, ctrNum, isLE);\n }\n // leftovers (less than a block)\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n const { s0, s1, s2, s3 } = encrypt(xk, swap8IfBE(c32[0]), swap8IfBE(c32[1]), swap8IfBE(c32[2]), swap8IfBE(c32[3]));\n const b32 = new Uint32Array([s0, s1, s2, s3]);\n swap32IfBE(b32);\n const buf = u8(b32);\n for (let i = start, pos = 0; i < srcLen; i++, pos++)\n dst[i] = src[i] ^ buf[pos];\n clean(b32);\n }\n // Same unsafe contract as ctrCounter(): only full blocks advance the stored\n // mutable counter state; partial-block continuation is caller-managed.\n return dst;\n}\n/**\n * **CTR** (Counter Mode): turns a block cipher into a stream cipher using a\n * full 16-byte counter block.\n * Efficient and parallelizable. Requires a unique nonce per encryption. Unauthenticated: needs MAC.\n * @param key - AES key bytes.\n * @param nonce - 16-byte counter block, incremented as a full AES block.\n * @returns Cipher instance with `encrypt()` and `decrypt()`.\n * @example\n * Encrypts a short payload with a fresh AES key and counter block.\n *\n * ```ts\n * import { ctr } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * const nonce = randomBytes(16);\n * const cipher = ctr(key, nonce);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const ctr = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aesctr(key, nonce) {\n function processCtr(buf, dst) {\n abytes(buf);\n if (dst !== undefined) {\n abytes(dst);\n // Optional output buffers must stay 4-byte aligned because\n // ctrCounter() reinterprets them as Uint32Array words.\n if (!isAligned32(dst))\n throw new Error('unaligned destination');\n }\n const xk = expandKeyLE(key);\n // Public CTR keeps caller nonce bytes immutable even though ctrCounter()\n // advances the live 16-byte counter block in place.\n const n = copyBytes(nonce); // align + avoid changing\n const toClean = [xk, n];\n if (!isAligned32(buf))\n toClean.push((buf = copyBytes(buf)));\n const out = ctrCounter(xk, n, buf, dst);\n clean(...toClean);\n return out;\n }\n return {\n encrypt: (plaintext, dst) => processCtr(plaintext, dst),\n decrypt: (ciphertext, dst) => processCtr(ciphertext, dst),\n };\n});\nfunction validateBlockDecrypt(data, dst) {\n abytes(data);\n // ECB/CBC decryption always consumes whole ciphertext blocks; PKCS#7/CMS\n // padding, when enabled, is removed only after decrypting the final block.\n if (data.length % BLOCK_SIZE !== 0) {\n throw new Error('ciphertext must be multiple of ' + BLOCK_SIZE);\n }\n // Validate caller-provided output before key expansion; allocation happens after it.\n if (dst !== undefined) {\n getOutput(data.length, dst);\n complexOverlapBytes(data, dst);\n }\n}\n// ECB/CBC core modes operate on whole blocks; `pkcs5` enables the library's\n// PKCS#7/CMS-compatible final-block padding convenience before encryption.\nfunction validateBlockEncrypt(plaintext, pkcs5, dst) {\n abytes(plaintext);\n let outLen = plaintext.length;\n const remaining = outLen % BLOCK_SIZE;\n if (!pkcs5 && remaining !== 0)\n throw new Error('plaintext must be multiple of ' + BLOCK_SIZE);\n if (pkcs5) {\n let left = BLOCK_SIZE - remaining;\n // RFC 5652 pads even already-aligned inputs, so a full extra block is\n // appended when the plaintext length is already a multiple of 16 bytes.\n if (!left)\n left = BLOCK_SIZE; // if no bytes left, create empty padding block\n outLen = outLen + left;\n }\n // Validate caller-provided output before key expansion; allocation happens after it.\n if (dst !== undefined) {\n getOutput(outLen, dst);\n complexOverlapBytes(plaintext, dst);\n }\n return outLen;\n}\nfunction prepareBlockEncrypt(plaintext, outLen, dst) {\n if (dst === undefined)\n dst = new Uint8Array(outLen);\n // Copy on BE or misaligned inputs so u32()/swap32IfBE() normalization never\n // mutates caller plaintext bytes in place before ECB/CBC processing.\n if (!isLE || !isAligned32(plaintext))\n plaintext = copyBytes(plaintext);\n const o = u32(dst);\n // Keep the full byte owner so callers can wipe a conditional copy without rebuilding a view.\n return { b: plaintext, o, out: dst };\n}\n// `pkcs5` is the historical option name; for AES's 16-byte block this is the\n// generic PKCS#7/CMS-style block-padding rule on decrypt.\nfunction validatePKCS(data, pkcs5) {\n if (!pkcs5)\n return data;\n const len = data.length;\n // RFC 5652 pads even empty / already-aligned inputs, so a valid padded\n // ECB/CBC ciphertext is never empty when PKCS#7/CMS unpadding is enabled.\n // AES-CBC/ECB ciphertext should be full blocks before unpadding\n if (len === 0)\n throw new Error('pkcs7: empty ciphertext not allowed');\n const lastByte = data[len - 1];\n let valid = 1;\n valid &= ((lastByte - 1) >>> 31) ^ 1; // pad >= 1\n valid &= ((16 - lastByte) >>> 31) ^ 1; // pad <= 16\n // Check exactly 16 tail bytes in constant-shape loop\n // For i < pad: byte must equal pad\n // For i >= pad: ignore byte\n for (let i = 0; i < 16; i++) {\n // const b = data[len - 1 - i];\n const shouldCheck = (i - lastByte) >>> 31; // 1 if i < pad else 0\n const eq = (data[len - 1 - i] ^ lastByte) === 0 ? 1 : 0; // 1 if equal\n valid &= eq | (shouldCheck ^ 1); // pass if equal OR not checked\n }\n // if (invalidLen) throw new Error('aes/pkcs7: ciphertext length must be multiple of 16');\n // Padding rejection is observable as a decrypt failure; authenticate CBC/ECB\n // ciphertexts before decrypting or use `disablePadding` in a higher-level protocol.\n if (!valid)\n throw new Error('aes: bad decrypt');\n return data.subarray(0, len - lastByte);\n}\n// ECB/CBC callers only pass the final short block here, so `left.length` is\n// 0..15 and the helper always emits exactly one padded 16-byte block.\nfunction padPCKS(left) {\n const tmp = new Uint8Array(16);\n const tmp32 = u32(tmp);\n tmp.set(left);\n const paddingByte = BLOCK_SIZE - left.length;\n // RFC 5652 \u00A76.3 fills the whole suffix with the padding length byte:\n // e.g. `aa 0f..0f` for a 1-byte tail, or `10..10` for a full extra block.\n for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++)\n tmp[i] = paddingByte;\n return tmp32;\n}\n/**\n * **ECB** (Electronic Codebook): Deterministic encryption; identical plaintext blocks yield\n * identical ciphertexts. Not secure due to pattern leakage.\n * See {@link https://words.filippo.io/the-ecb-penguin/ | the AES Penguin}.\n * @param key - AES key bytes.\n * @param opts - Padding options. See {@link BlockOpts}.\n * @returns Cipher instance with `encrypt()` and `decrypt()`.\n * @example\n * Shows the basic ECB encrypt call shape with a fresh key; avoid ECB in new designs.\n *\n * ```ts\n * import { ecb } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * const cipher = ecb(key);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const ecb = /* @__PURE__ */ wrapCipher({ blockSize: 16 }, function aesecb(key, opts = {}) {\n const pkcs5 = !opts.disablePadding;\n return {\n encrypt(plaintext, dst) {\n const outLen = validateBlockEncrypt(plaintext, pkcs5, dst);\n const xk = expandKeyLE(key);\n const { b: input, o, out: _out } = prepareBlockEncrypt(plaintext, outLen, dst);\n const b = u32(input);\n swap32IfBE(b);\n let i = 0;\n for (; i + 4 <= b.length;) {\n const { s0, s1, s2, s3 } = encrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);\n ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3));\n }\n if (pkcs5) {\n const tmp32 = padPCKS(plaintext.subarray(i * 4));\n swap32IfBE(tmp32);\n const { s0, s1, s2, s3 } = encrypt(xk, tmp32[0], tmp32[1], tmp32[2], tmp32[3]);\n ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3));\n // The padding scratch contains the final plaintext tail; wipe it as soon as consumed.\n clean(tmp32);\n }\n swap32IfBE(o);\n clean(xk);\n if (input !== plaintext)\n clean(input);\n return _out;\n },\n decrypt(ciphertext, dst) {\n // Validate inputs before expanding the key, so a validation throw\n // never leaves an unwiped expanded key behind.\n validateBlockDecrypt(ciphertext, dst);\n const xk = expandKeyDecLE(key);\n if (dst === undefined)\n dst = new Uint8Array(ciphertext.length);\n const toClean = [xk];\n // Copy on BE or misaligned ciphertext so u32()/swap32IfBE()\n // normalization never mutates caller bytes in place before decrypt().\n if (!isLE || !isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const b = u32(ciphertext);\n const o = u32(dst);\n swap32IfBE(b);\n for (let i = 0; i + 4 <= b.length;) {\n const { s0, s1, s2, s3 } = decrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);\n ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3));\n }\n swap32IfBE(o);\n clean(...toClean);\n return validatePKCS(dst, pkcs5);\n },\n };\n});\n/**\n * **CBC** (Cipher Block Chaining): Each plaintext block is XORed with the\n * previous block of ciphertext before encryption.\n * Hard to use: requires proper padding and an unpredictable IV. Unauthenticated: needs MAC.\n * Bad padding is reported as decrypt failure, which can be a padding oracle if exposed.\n * @param key - AES key bytes.\n * @param iv - 16-byte unpredictable initialization vector.\n * @param opts - Padding options. See {@link BlockOpts}.\n * @returns Cipher instance with `encrypt()` and `decrypt()`.\n * @example\n * Encrypts a padded message with a fresh key and 16-byte IV.\n *\n * ```ts\n * import { cbc } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * const iv = randomBytes(16);\n * const cipher = cbc(key, iv);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const cbc = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aescbc(key, iv, opts = {}) {\n const pkcs5 = !opts.disablePadding;\n return {\n encrypt(plaintext, dst) {\n // Validate inputs before expanding the key, so a validation throw\n // never leaves an unwiped expanded key behind.\n const outLen = validateBlockEncrypt(plaintext, pkcs5, dst);\n const xk = expandKeyLE(key);\n const { b: input, o, out: _out } = prepareBlockEncrypt(plaintext, outLen, dst);\n const b = u32(input);\n swap32IfBE(b);\n let _iv = iv;\n const toClean = [xk];\n // Copy on BE or misaligned inputs so IV normalization and the mutable\n // local chaining state never write back into caller IV bytes.\n if (!isLE || !isAligned32(_iv))\n toClean.push((_iv = copyBytes(_iv)));\n const n32 = u32(_iv);\n swap32IfBE(n32);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n let i = 0;\n for (; i + 4 <= b.length;) {\n ((s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]));\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3));\n }\n if (pkcs5) {\n const tmp32 = padPCKS(plaintext.subarray(i * 4));\n swap32IfBE(tmp32);\n ((s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]));\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3));\n // The padding scratch contains the final plaintext tail; wipe it as soon as consumed.\n clean(tmp32);\n }\n swap32IfBE(o);\n clean(...toClean);\n if (input !== plaintext)\n clean(input);\n return _out;\n },\n decrypt(ciphertext, dst) {\n // Validate inputs before expanding the key, so a validation throw\n // never leaves an unwiped expanded key behind.\n validateBlockDecrypt(ciphertext, dst);\n const xk = expandKeyDecLE(key);\n if (dst === undefined)\n dst = new Uint8Array(ciphertext.length);\n let _iv = iv;\n const toClean = [xk];\n // Copy on BE or misaligned inputs so IV normalization and the mutable\n // local chaining state never write back into caller IV bytes.\n if (!isLE || !isAligned32(_iv))\n toClean.push((_iv = copyBytes(_iv)));\n const n32 = u32(_iv);\n swap32IfBE(n32);\n // Copy on BE or misaligned ciphertext so u32()/swap32IfBE()\n // normalization never mutates caller bytes in place before decrypt().\n if (!isLE || !isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const b = u32(ciphertext);\n const o = u32(dst);\n swap32IfBE(b);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n for (let i = 0; i + 4 <= b.length;) {\n // prettier-ignore\n const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3;\n ((s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]));\n const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt(xk, s0, s1, s2, s3);\n ((o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3));\n }\n swap32IfBE(o);\n clean(...toClean);\n return validatePKCS(dst, pkcs5);\n },\n };\n});\n/**\n * CFB (CFB-128): Cipher Feedback Mode with 128-bit segments. The input for the\n * block cipher is the previous cipher output.\n * Unauthenticated: needs MAC.\n * @param key - AES key bytes.\n * @param iv - 16-byte unpredictable initialization vector.\n * @returns Cipher instance with `encrypt()` and `decrypt()`.\n * @example\n * Encrypts a short message with feedback mode and a fresh key/IV pair.\n *\n * ```ts\n * import { cfb } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * const iv = randomBytes(16);\n * const cipher = cfb(key, iv);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const cfb = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aescfb(key, iv) {\n function processCfb(src, isEncrypt, dst) {\n abytes(src);\n const srcLen = src.length;\n dst = getOutput(srcLen, dst);\n // CFB feeds back previous ciphertext, so overlapping src/dst could\n // overwrite bytes that are still needed as the next feedback block.\n if (overlapBytes(src, dst))\n throw new Error('overlapping src and dst not supported');\n const xk = expandKeyLE(key);\n let _iv = iv;\n const toClean = [xk];\n // Copy on BE or misaligned inputs so u32()/swap32IfBE() normalization\n // never mutates caller IV/src bytes in place before CFB processing.\n if (!isLE || !isAligned32(_iv))\n toClean.push((_iv = copyBytes(_iv)));\n if (!isLE || !isAligned32(src))\n toClean.push((src = copyBytes(src)));\n const src32 = u32(src);\n const dst32 = u32(dst);\n // NIST SP 800-38A \u00A76.3 feeds back the previous ciphertext segment in\n // both directions: encrypt reuses freshly written dst words, decrypt\n // reuses the source ciphertext words.\n const next32 = isEncrypt ? dst32 : src32;\n const n32 = u32(_iv);\n swap32IfBE(src32);\n swap32IfBE(n32);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n for (let i = 0; i + 4 <= src32.length;) {\n const { s0: e0, s1: e1, s2: e2, s3: e3 } = encrypt(xk, s0, s1, s2, s3);\n dst32[i + 0] = src32[i + 0] ^ e0;\n dst32[i + 1] = src32[i + 1] ^ e1;\n dst32[i + 2] = src32[i + 2] ^ e2;\n dst32[i + 3] = src32[i + 3] ^ e3;\n ((s0 = next32[i++]), (s1 = next32[i++]), (s2 = next32[i++]), (s3 = next32[i++]));\n }\n // leftovers (less than block)\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n // The byte tail loop reads `src` directly; restore any BE-swapped tail words first.\n if (!isLE)\n swap32IfBE(src32.subarray(start / 4));\n // Byte-oriented API: for a final short tail, reuse the next CFB-128\n // output block and XOR only the needed prefix. RFC 3826 \u00A73.1.3 /\n // \u00A73.1.4 describes the same no-padding rule at bit granularity for a\n // final r<=128 segment.\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n const tmp = new Uint32Array([s0, s1, s2, s3]);\n swap32IfBE(tmp);\n const buf = u8(tmp);\n for (let i = start, pos = 0; i < srcLen; i++, pos++)\n dst[i] = src[i] ^ buf[pos];\n clean(buf);\n }\n if (!isLE)\n swap32IfBE(dst32.subarray(0, start / 4));\n clean(...toClean);\n return dst;\n }\n return {\n encrypt: (plaintext, dst) => processCfb(plaintext, true, dst),\n decrypt: (ciphertext, dst) => processCfb(ciphertext, false, dst),\n };\n});\n// TODO: merge with chacha, however gcm has bitLen while chacha has byteLen\n// `data` is the payload covered by the polynomial MAC: ciphertext for GCM,\n// plaintext for GCM-SIV. Keep AAD/data/length as separate updates because\n// GHASH/POLYVAL pad each call to block boundaries, so the chunks must match the\n// spec-defined segments instead of arbitrary concatenation boundaries.\nfunction computeTag(fn, isLE, key, data, AAD) {\n const aadLength = AAD ? AAD.length : 0;\n const h = fn.create(key, data.length + aadLength);\n if (AAD)\n h.update(AAD);\n // u64Lengths() takes (dataBits, aadBits) but still serializes the final\n // block as len(AAD) || len(data), matching both GCM and GCM-SIV.\n const num = u64Lengths(8 * data.length, 8 * aadLength, isLE);\n h.update(data);\n h.update(num);\n const res = h.digest();\n clean(num);\n return res;\n}\n/**\n * **GCM** (Galois/Counter Mode): Combines CTR mode with polynomial MAC. Efficient and widely used.\n * Not perfect:\n * a) conservative key wear-out is `2**32` (4B) msgs.\n * b) key wear-out under random nonces is even smaller: `2**23` (8M) messages for `2**-50` chance.\n * c) MAC can be forged: see Poly1305 documentation.\n * @param key - AES key bytes.\n * @param nonce - Nonce bytes (12 recommended, minimum 8; other lengths use GHASH J0 derivation).\n * @param AAD - Additional authenticated data.\n * @returns AEAD cipher instance with a fixed 16-byte tag.\n * @example\n * Encrypts and authenticates plaintext with a fresh key and 12-byte nonce.\n *\n * ```ts\n * import { gcm } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * const nonce = randomBytes(12);\n * const aad = new TextEncoder().encode('session metadata');\n * const cipher = gcm(key, nonce, aad);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const gcm = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16, withAAD: true, varSizeNonce: true }, function aesgcm(key, nonce, AAD) {\n // SP 800-38D lets implementations narrow supported IV lengths.\n // This wrapper intentionally requires at least 8 bytes; OpenSSL accepts shorter IVs too.\n // 12-byte nonces take the fast path; other allowed lengths use GHASH to derive J0.\n if (nonce.length < 8)\n throw new Error('aes/gcm: invalid nonce length');\n const tagLength = 16;\n function _computeTag(authKey, tagMask, data) {\n const tag = computeTag(ghash, false, authKey, data, AAD);\n for (let i = 0; i < tagMask.length; i++)\n tag[i] ^= tagMask[i];\n return tag;\n }\n function deriveKeys() {\n const xk = expandKeyLE(key);\n const authKey = EMPTY_BLOCK.slice();\n const counter = EMPTY_BLOCK.slice();\n ctr32(xk, false, counter, counter, authKey);\n // NIST 800-38d, page 15: different behavior for 96-bit and non-96-bit nonces\n if (nonce.length === 12) {\n counter.set(nonce);\n }\n else {\n const nonceLen = EMPTY_BLOCK.slice();\n const view = createView(nonceLen);\n view.setBigUint64(8, BigInt(nonce.length * 8), false);\n // GHASH.update() pads each call to 16 bytes, so\n // update(nonce).update(nonceLen) realizes\n // IV || 0^s || 0^64 || [len(IV)]_64 for non-96-bit nonces.\n // ghash(nonce || u64be(0) || u64be(nonceLen*8))\n const g = ghash.create(authKey).update(nonce).update(nonceLen);\n g.digestInto(counter); // digestInto doesn't trigger '.destroy'\n g.destroy();\n }\n // GCTR_K(J0, 0^128) = E_K(J0); reusing ctr32() here extracts that tag\n // mask and leaves `counter` advanced to inc32(J0) for payload GCTR.\n const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK);\n return { xk, authKey, counter, tagMask };\n }\n return {\n encrypt(plaintext) {\n const { xk, authKey, counter, tagMask } = deriveKeys();\n const out = new Uint8Array(plaintext.length + tagLength);\n const toClean = [xk, authKey, counter, tagMask];\n if (!isAligned32(plaintext))\n toClean.push((plaintext = copyBytes(plaintext)));\n ctr32(xk, false, counter, plaintext, out.subarray(0, plaintext.length));\n const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength));\n toClean.push(tag);\n out.set(tag, plaintext.length);\n clean(...toClean);\n return out;\n },\n decrypt(ciphertext) {\n const { xk, authKey, counter, tagMask } = deriveKeys();\n const toClean = [xk, authKey, tagMask, counter];\n if (!isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = _computeTag(authKey, tagMask, data);\n toClean.push(tag);\n // NIST SP 800-38D \u00A77.2 permits equivalent step orderings; verify the\n // tag before CTR so unauthenticated plaintext is never materialized.\n if (!equalBytes(tag, passedTag)) {\n clean(...toClean);\n throw new Error('aes-gcm: invalid tag');\n }\n const out = ctr32(xk, false, counter, data);\n clean(...toClean);\n return out;\n },\n };\n});\nconst limit = (name, min, max) => (value) => {\n // Current AES-SIV/GCM-SIV callers pass protocol limits from RFC 8452 / RFC 5297,\n // not arbitrary library-preference bounds.\n // Callers feed Uint8Array.length values here, so safe-integer rejection\n // does not exclude any representable input even when an RFC bound is larger.\n if (!Number.isSafeInteger(value) || min > value || value > max) {\n const minmax = '[' + min + '..' + max + ']';\n throw new Error('' + name + ': expected value in range ' + minmax + ', got ' + value);\n }\n};\n/**\n * **SIV** (Synthetic IV): GCM with nonce-misuse resistance.\n * Repeating nonces reveal only the fact plaintexts are identical.\n * Also suffers from GCM issues: key wear-out limits & MAC forging.\n * See {@link https://www.rfc-editor.org/rfc/rfc8452 | RFC 8452}.\n * RFC 8452 defines 16-byte and 32-byte AES keys for this mode.\n * This implementation also accepts 24-byte AES-192 keys as a local\n * extension; see the inline comment next to `validateKeyLength(key)` below\n * for the exact scope note.\n * @param key - AES key bytes.\n * @param nonce - 12-byte nonce.\n * @param AAD - Additional authenticated data.\n * @returns AEAD cipher instance.\n * @example\n * Encrypts and authenticates plaintext with a fresh key and nonce, while tolerating reuse.\n *\n * ```ts\n * import { gcmsiv } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * const nonce = randomBytes(12);\n * const aad = new TextEncoder().encode('session metadata');\n * const cipher = gcmsiv(key, nonce, aad);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const gcmsiv = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16, withAAD: true, varSizeNonce: true }, function aessiv(key, nonce, AAD) {\n const tagLength = 16;\n // From RFC 8452: Section 6\n const AAD_LIMIT = limit('AAD', 0, 2 ** 36);\n const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 36);\n const NONCE_LIMIT = limit('nonce', 12, 12);\n const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 36 + 16);\n abytes(key);\n // RFC 8452 only standardizes 16-byte and 32-byte key-generating keys.\n // The accepted 24-byte path is a local AES-192 extension outside the RFC-defined AEADs.\n validateKeyLength(key);\n NONCE_LIMIT(nonce.length);\n if (AAD !== undefined)\n AAD_LIMIT(AAD.length);\n function deriveKeys() {\n const xk = expandKeyLE(key);\n const encKey = new Uint8Array(key.length);\n const authKey = new Uint8Array(16);\n const toClean = [xk, encKey];\n let _nonce = nonce;\n // Copy on BE or misaligned nonce so u32()/swap32IfBE() normalization\n // never mutates caller nonce bytes before RFC 8452 key derivation.\n if (!isLE || !isAligned32(_nonce))\n toClean.push((_nonce = copyBytes(_nonce)));\n const n32 = u32(_nonce);\n swap32IfBE(n32);\n // prettier-ignore\n let s0 = 0, s1 = n32[0], s2 = n32[1], s3 = n32[2];\n let counter = 0;\n for (const derivedKey of [authKey, encKey].map(u32)) {\n const d32 = u32(derivedKey);\n for (let i = 0; i < d32.length; i += 2) {\n // aes(u32le(0) || nonce)[:8] || aes(u32le(1) || nonce)[:8] ...\n const { s0: o0, s1: o1 } = encrypt(xk, s0, s1, s2, s3);\n d32[i + 0] = o0;\n d32[i + 1] = o1;\n s0 = ++counter; // increment counter inside state\n }\n swap32IfBE(d32);\n }\n const res = { authKey, encKey: expandKeyLE(encKey) };\n // Cleanup\n clean(...toClean);\n return res;\n }\n function _computeTag(encKey, authKey, data) {\n const tag = computeTag(polyval, true, authKey, data, AAD);\n // Compute the expected tag by XORing S_s and the nonce, clearing the\n // most significant bit of the last byte and encrypting with the\n // message-encryption key.\n for (let i = 0; i < 12; i++)\n tag[i] ^= nonce[i];\n tag[15] &= 0x7f; // Clear the highest bit\n // encrypt tag as block\n const t32 = u32(tag);\n swap32IfBE(t32);\n // prettier-ignore\n let s0 = t32[0], s1 = t32[1], s2 = t32[2], s3 = t32[3];\n ({ s0, s1, s2, s3 } = encrypt(encKey, s0, s1, s2, s3));\n ((t32[0] = s0), (t32[1] = s1), (t32[2] = s2), (t32[3] = s3));\n swap32IfBE(t32);\n return tag;\n }\n // actual decrypt/encrypt of message.\n function processSiv(encKey, tag, input) {\n let block = copyBytes(tag);\n // RFC 8452 \u00A74 / \u00A75 use the tag with the highest bit of the last byte\n // forced to one as the initial AES-CTR counter block.\n block[15] |= 0x80; // Force highest bit\n const res = ctr32(encKey, true, block, input);\n // Cleanup\n clean(block);\n return res;\n }\n return {\n encrypt(plaintext) {\n PLAIN_LIMIT(plaintext.length);\n const { encKey, authKey } = deriveKeys();\n const tag = _computeTag(encKey, authKey, plaintext);\n const toClean = [encKey, authKey, tag];\n if (!isAligned32(plaintext))\n toClean.push((plaintext = copyBytes(plaintext)));\n const out = new Uint8Array(plaintext.length + tagLength);\n out.set(tag, plaintext.length);\n out.set(processSiv(encKey, tag, plaintext));\n // Cleanup\n clean(...toClean);\n return out;\n },\n decrypt(ciphertext) {\n CIPHER_LIMIT(ciphertext.length);\n const tag = ciphertext.subarray(-tagLength);\n const { encKey, authKey } = deriveKeys();\n const toClean = [encKey, authKey];\n if (!isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const plaintext = processSiv(encKey, tag, ciphertext.subarray(0, -tagLength));\n const expectedTag = _computeTag(encKey, authKey, plaintext);\n toClean.push(expectedTag);\n // RFC 8452 \u00A75: plaintext is unauthenticated here and MUST NOT be\n // returned until the expected-tag check completes successfully.\n if (!equalBytes(tag, expectedTag)) {\n clean(plaintext, ...toClean);\n throw new Error('invalid polyval tag');\n }\n // Cleanup\n clean(...toClean);\n return plaintext;\n },\n };\n});\nfunction isBytes32(a) {\n // Plain `instanceof Uint32Array` is too strict for cross-realm expanded-key views.\n // This is only a best-effort unsafe-export guard, not a provenance proof for `expandKeyLE`.\n return (a instanceof Uint32Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint32Array'));\n}\n// Unsafe single-block helpers: mutate `block` in place and require its 16-byte\n// Uint8Array view to be 4-byte aligned because `u32(block)` reinterprets it.\nfunction encryptBlock(xk, block) {\n abytes(block, 16, 'block');\n if (!isBytes32(xk))\n throw new Error('_encryptBlock accepts result of expandKeyLE');\n const b32 = u32(block);\n swap32IfBE(b32);\n let { s0, s1, s2, s3 } = encrypt(xk, b32[0], b32[1], b32[2], b32[3]);\n ((b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3));\n swap32IfBE(b32);\n return block;\n}\nfunction decryptBlock(xk, block) {\n abytes(block, 16, 'block');\n if (!isBytes32(xk))\n throw new Error('_decryptBlock accepts result of expandKeyLE');\n const b32 = u32(block);\n swap32IfBE(b32);\n let { s0, s1, s2, s3 } = decrypt(xk, b32[0], b32[1], b32[2], b32[3]);\n ((b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3));\n swap32IfBE(b32);\n return block;\n}\n/**\n * AES-W (base for AESKW/AESKWP).\n * Specs:\n * {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf | SP800-38F},\n * {@link https://www.rfc-editor.org/rfc/rfc3394 | RFC 3394},\n * {@link https://www.rfc-editor.org/rfc/rfc5649 | RFC 5649}.\n * Shared core mutates `out` in place; callers are responsible for prepending\n * the right IV/AIV and checking the recovered value after decrypt.\n */\nconst AESW = {\n /*\n High-level pseudocode:\n ```\n A: u64 = IV\n out = []\n for (let i=0, ctr = 0; i<6; i++) {\n for (const chunk of chunks(plaintext, 8)) {\n A ^= swapEndianess(ctr++)\n [A, res] = chunks(encrypt(A || chunk), 8);\n out ||= res\n }\n }\n out = A || out\n ```\n Decrypt is the same, but reversed.\n */\n encrypt(kek, out) {\n // Current implementation keeps RFC 3394/5649 `t` in a u32-shaped counter,\n // so the shared core caps plaintext below 4 GiB even though the specs allow more.\n if (out.length >= 2 ** 32)\n throw new Error('plaintext should be less than 4gb');\n const xk = expandKeyLE(kek);\n // 16-byte `S = A || P[1]` is the RFC 5649 KWP special case for n=1;\n // KW callers never reach it because KW requires at least two plaintext semiblocks.\n if (out.length === 16)\n encryptBlock(xk, out);\n else {\n const o32 = u32(out);\n swap32IfBE(o32);\n // prettier-ignore\n let a0 = o32[0], a1 = o32[1]; // A\n for (let j = 0, ctr = 1; j < 6; j++) {\n for (let pos = 2; pos < o32.length; pos += 2, ctr++) {\n const { s0, s1, s2, s3 } = encrypt(xk, a0, a1, o32[pos], o32[pos + 1]);\n // A = MSB(64, B) ^ t where t = (n*j)+i. Under the 32-bit length cap\n // above, `t` fits in the low half of `[t]_64`, so xor only the low\n // 32 bits of A after converting `ctr` to network order.\n ((a0 = s0), (a1 = s1 ^ byteSwap(ctr)), (o32[pos] = s2), (o32[pos + 1] = s3));\n }\n }\n ((o32[0] = a0), (o32[1] = a1)); // out = A || out\n swap32IfBE(o32);\n }\n xk.fill(0);\n },\n decrypt(kek, out) {\n // Same implementation cap on the recovered plaintext length after\n // removing the 8-byte A/IV prefix.\n if (out.length - 8 >= 2 ** 32)\n throw new Error('ciphertext should be less than 4gb');\n const xk = expandKeyDecLE(kek);\n const chunks = out.length / 8 - 1; // first chunk is IV\n // `n = 2` semiblocks is the RFC 5649 KWP special case; KW ciphertexts\n // always have at least three semiblocks and therefore use the W^-1 loop.\n if (chunks === 1)\n decryptBlock(xk, out);\n else {\n const o32 = u32(out);\n swap32IfBE(o32);\n // prettier-ignore\n let a0 = o32[0], a1 = o32[1]; // A\n for (let j = 0, ctr = chunks * 6; j < 6; j++) {\n for (let pos = chunks * 2; pos >= 1; pos -= 2, ctr--) {\n a1 ^= byteSwap(ctr);\n const { s0, s1, s2, s3 } = decrypt(xk, a0, a1, o32[pos], o32[pos + 1]);\n ((a0 = s0), (a1 = s1), (o32[pos] = s2), (o32[pos + 1] = s3));\n }\n }\n ((o32[0] = a0), (o32[1] = a1));\n swap32IfBE(o32);\n }\n xk.fill(0);\n },\n};\n// RFC 3394 \u00A72.2.3.1 / NIST SP 800-38F Algorithm 3 / Algorithm 4: KW prepends\n// the default 64-bit ICV1 and unwrap must verify the same value.\nconst AESKW_IV = /* @__PURE__ */ new Uint8Array(8).fill(0xa6); // A6A6A6A6A6A6A6A6\n/**\n * AES-KW (key-wrap). Injects static IV into plaintext, adds counter, encrypts 6 times.\n * Reduces block size from 16 to 8 bytes.\n * Plaintext must be a non-empty multiple of 8 bytes with minimum 16 bytes.\n * 8-byte inputs use aeskwp.\n * Wrapped ciphertext must be a multiple of 8 bytes with minimum 24 bytes.\n * For padded version, use aeskwp.\n * See {@link https://www.rfc-editor.org/rfc/rfc3394/ | RFC 3394} and\n * {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf | NIST SP 800-38F}.\n * @param kek - AES key-encryption key.\n * @returns Key-wrap cipher instance.\n * As with other `wrapCipher(...)` wrappers, `encrypt()` is single-use per\n * instance.\n * @example\n * Wraps a 128-bit content-encryption key with a fresh key-encryption key.\n *\n * ```ts\n * import { aeskw } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const kek = randomBytes(16);\n * const cek = randomBytes(16);\n * const wrap = aeskw(kek);\n * wrap.encrypt(cek);\n * ```\n */\nexport const aeskw = /* @__PURE__ */ wrapCipher({ blockSize: 8 }, (kek) => ({\n encrypt(plaintext) {\n if (!plaintext.length || plaintext.length % 8 !== 0)\n throw new Error('invalid plaintext length');\n // RFC 3394 / NIST SP 800-38F define KW only for >=2 plaintext\n // semiblocks; the 1-semiblock case belongs to RFC 5649 KWP.\n if (plaintext.length === 8)\n throw new Error('8-byte keys not allowed, use AESKWP');\n const out = concatBytes(AESKW_IV, plaintext);\n AESW.encrypt(kek, out);\n return out;\n },\n decrypt(ciphertext) {\n // ciphertext must be at least 24 bytes and a multiple of 8 bytes\n // 24 because should have at least two block (1 iv + 2).\n // Replace with 16 to enable '8-byte keys'\n if (ciphertext.length % 8 !== 0 || ciphertext.length < 3 * 8)\n throw new Error('invalid ciphertext length');\n // AESW.decrypt() mutates its buffer in place, so keep caller ciphertext\n // immutable across the unwrap, ICV1 check, and IV scrubbing below.\n const out = copyBytes(ciphertext);\n AESW.decrypt(kek, out);\n if (!equalBytes(out.subarray(0, 8), AESKW_IV))\n throw new Error('integrity check failed');\n out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway\n return out.subarray(8);\n },\n}));\n/*\nWe don't support 8-byte keys. The rabbit hole:\n\n- Wycheproof says: \"NIST SP 800-38F does not define the wrapping of 8 byte keys.\n RFC 3394 Section 2 on the other hand specifies that 8 byte keys are wrapped\n by directly encrypting one block with AES.\"\n - {@link https://github.com/C2SP/wycheproof/blob/master/doc/key_wrap.md | Wycheproof key-wrap note}\n - \"RFC 3394 specifies in Section 2, that the input for the key wrap\n algorithm must be at least two blocks and otherwise the constant\n field and key are simply encrypted with ECB as a single block\"\n- What RFC 3394 actually says (in Section 2):\n - \"Before being wrapped, the key data is parsed into n blocks of 64 bits.\n The only restriction the key wrap algorithm places on n is that n be\n at least two\"\n - \"For key data with length less than or equal to 64 bits, the constant\n field used in this specification and the key data form a single\n 128-bit codebook input making this key wrap unnecessary.\"\n- Which means \"assert(n >= 2)\" and \"use something else for 8 byte keys\"\n- NIST SP800-38F actually prohibits 8-byte in \"5.3.1 Mandatory Limits\".\n It states that plaintext for KW should be \"2 to 2^54 -1 semiblocks\".\n- So, where does \"directly encrypt single block with AES\" come from?\n - Not RFC 3394. Pseudocode of key wrap in 2.2 explicitly uses\n loop of 6 for any code path\n - There is a weird W3C spec:\n {@link https://www.w3.org/TR/2002/REC-xmlenc-core-20021210/Overview.html#kw-aes128 | XML Encryption AES key-wrap section}\n - This spec is outdated, as admitted by Wycheproof authors\n - There is RFC 5649 for padded key wrap, which is padding construction on\n top of AESKW. In '4.1.2' it says: \"If the padded plaintext contains exactly\n eight octets, then prepend the AIV as defined in Section 3 above to P[1] and\n encrypt the resulting 128-bit block using AES in ECB mode [Modes] with key\n K (the KEK). In this case, the output is two 64-bit blocks C[0] and C[1]:\"\n - Browser subtle crypto is actually crashes on wrapping keys less than 16 bytes:\n `Error: error:1C8000E6:Provider routines::invalid input length]\n { opensslErrorStack: [ 'error:030000BD:digital envelope routines::update error' ]`\n\nIn the end, seems like a bug in Wycheproof.\nThe 8-byte check can be easily disabled inside of AES_W.\n*/\n// RFC 5649 \u00A73 / NIST SP 800-38F Algorithm 5 / Algorithm 6: KWP uses ICV2 as\n// the high 32 bits of the AIV; the low 32 bits carry the MLI in network order.\nconst AESKWP_IV = 0xa65959a6; // single u32le value\n/**\n * AES-KW, but with padding and allows random keys.\n * Uses the RFC 5649 alternative initial value; the second u32 stores the\n * 32-bit MLI in network order.\n * Wrapped ciphertext must be at least 16 bytes; malformed lengths are\n * rejected during AIV/padding checks.\n * See {@link https://www.rfc-editor.org/rfc/rfc5649 | RFC 5649}.\n * @param kek - AES key-encryption key.\n * @returns Padded key-wrap cipher instance.\n * @example\n * Wraps a short key blob using the padded variant and a fresh key-encryption key.\n *\n * ```ts\n * import { aeskwp } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const kek = randomBytes(16);\n * const wrap = aeskwp(kek);\n * wrap.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const aeskwp = /* @__PURE__ */ wrapCipher({ blockSize: 8 }, (kek) => ({\n encrypt(plaintext) {\n if (!plaintext.length)\n throw new Error('invalid plaintext length');\n const padded = Math.ceil(plaintext.length / 8) * 8;\n const out = new Uint8Array(8 + padded);\n out.set(plaintext, 8);\n const out32 = u32(out);\n out32[0] = swap8IfBE(AESKWP_IV);\n // RFC 5649 \u00A73: the low 32 bits of the AIV carry the octet-length MLI in\n // network order, even though this buffer is addressed through LE u32s.\n out32[1] = swap8IfBE(byteSwap(plaintext.length));\n AESW.encrypt(kek, out);\n return out;\n },\n decrypt(ciphertext) {\n // 16 because should have at least one block\n if (ciphertext.length < 16)\n throw new Error('invalid ciphertext length');\n // AESW.decrypt() mutates its buffer in place, so keep caller ciphertext\n // immutable across the unwrap, AIV checks, and IV scrubbing below.\n const out = copyBytes(ciphertext);\n const o32 = u32(out);\n AESW.decrypt(kek, out);\n const len = byteSwap(swap8IfBE(o32[1])) >>> 0;\n const padded = Math.ceil(len / 8) * 8;\n if (swap8IfBE(o32[0]) !== AESKWP_IV || out.length - 8 !== padded)\n throw new Error('integrity check failed');\n // RFC 5649 \u00A73 / NIST SP 800-38F Algorithm 6: recovered padding length\n // must be in [0,7], and every recovered pad octet must be zero.\n for (let i = len; i < padded; i++)\n if (out[8 + i] !== 0)\n throw new Error('integrity check failed');\n out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway\n return out.subarray(8, 8 + len);\n },\n}));\nclass _AesCtrDRBG {\n blockLen;\n key;\n nonce;\n state;\n reseedCnt;\n destroyed = false;\n constructor(keyLen, seed, personalization) {\n this.blockLen = ctr.blockSize;\n const keyLenBytes = keyLen / 8;\n const nonceLen = 16;\n // Store the full seedlen state as key || V so CTR_DRBG_Update-style steps\n // can rewrite the entire internal state in place.\n this.state = new Uint8Array(keyLenBytes + nonceLen);\n this.key = this.state.subarray(0, keyLenBytes);\n this.nonce = this.state.subarray(keyLenBytes, keyLenBytes + nonceLen);\n this.reseedCnt = 1;\n // Keep the stored counter one step ahead of SP 800-90A's formal V so\n // ctr(key, nonce) uses the next counter block directly.\n incBytes(this.nonce, false, 1);\n this.addEntropy(seed, personalization);\n }\n update(data) {\n // cannot re-use state here, because we will wipe current key\n ctr(this.key, this.nonce).encrypt(new Uint8Array(this.state.length), this.state);\n if (data) {\n abytes(data);\n // CTR_DRBG without a derivation function pads shorter additional_input\n // with zeros to seedlen, so XOR only the provided prefix here.\n for (let i = 0; i < data.length; i++)\n this.state[i] ^= data[i];\n }\n // Keep storing V+1 so the next ctr(key, nonce) call starts from the\n // spec's post-update counter state.\n incBytes(this.nonce, false, 1);\n }\n // Optional `info` is additional input XORed into the reseed block and is\n // limited to the internal state width.\n addEntropy(seed, info) {\n if (this.destroyed)\n throw new Error('cannot use destroyed DRBG');\n abytes(seed, this.state.length, 'seed');\n // Copy caller entropy before XORing in personalization/additional input,\n // then wipe the mixed seed material after CTR_DRBG_Update consumes it.\n const _seed = seed.slice();\n if (info) {\n abytes(info);\n if (info.length > _seed.length)\n throw new Error('info length is too big');\n for (let i = 0; i < info.length; i++)\n _seed[i] ^= info[i];\n }\n this.update(_seed);\n _seed.fill(0);\n this.reseedCnt = 1;\n }\n // Optional `info` is additional input for the pre/post-update steps; bytes\n // SP 800-90A Rev. 1 CTR_DRBG without a derivation function limits\n // additional_input to seedlen, which is exactly this internal state width.\n randomBytes(len, info) {\n if (this.destroyed)\n throw new Error('cannot use destroyed DRBG');\n anumber(len);\n // SP 800-90A Table 3 caps AES CTR_DRBG requests at 2^16 bits = 65536 bytes.\n if (len > 2 ** 16)\n throw new Error('requested output is too big');\n // The spec allows generate while reseed_counter == reseed_interval and increments afterwards.\n if (this.reseedCnt > 2 ** 48)\n throw new Error('entropy exhausted');\n if (info) {\n abytes(info);\n if (info.length > this.state.length)\n throw new Error('info length is too big');\n this.update(info);\n }\n const res = new Uint8Array(len);\n ctr(this.key, this.nonce).encrypt(res, res);\n incBytes(this.nonce, false, Math.ceil(len / this.blockLen));\n this.update(info);\n this.reseedCnt++;\n return res;\n }\n // Zeroes the current state and marks the instance destroyed. Fails closed:\n // any later randomBytes()/addEntropy() throws instead of continuing from the\n // zeroed state (which would make subsequent output the predictable zero-key stream).\n clean() {\n // `key` and `nonce` alias this backing buffer, so one fill wipes the full\n // secret state in place.\n this.state.fill(0);\n this.reseedCnt = 0;\n this.destroyed = true;\n }\n}\n// Internal helper for the exported 128-bit and 256-bit aliases; other key\n// lengths are not validated here.\nconst createAesDrbg = (keyLen) => {\n return (seed, personalization = undefined) => new _AesCtrDRBG(keyLen, seed, personalization);\n};\n/**\n * AES-CTR DRBG 128-bit - CSPRNG (cryptographically secure pseudorandom number generator).\n * It's best to limit usage to non-production, non-critical cases: for example, test-only.\n * @param seed - Initial 32-byte entropy input.\n * @param personalization - Optional personalization string.\n * @returns Seeded DRBG instance. The concrete methods also accept optional additional-input bytes.\n * @example\n * Seeds the test-only AES-CTR DRBG from fresh entropy and reads bytes from it.\n *\n * ```ts\n * import { rngAesCtrDrbg128 } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const seed = randomBytes(32);\n * const prg = rngAesCtrDrbg128(seed);\n * prg.randomBytes(8);\n * ```\n */\nexport const rngAesCtrDrbg128 = /* @__PURE__ */ createAesDrbg(128);\n/**\n * AES-CTR DRBG 256-bit - CSPRNG (cryptographically secure pseudorandom number generator).\n * It's best to limit usage to non-production, non-critical cases: for example, test-only.\n * @param seed - Initial 48-byte entropy input.\n * @param personalization - Optional personalization string.\n * @returns Seeded DRBG instance. The concrete methods also accept optional additional-input bytes.\n * @example\n * Seeds the test-only AES-CTR DRBG from fresh entropy and reads bytes from it.\n *\n * ```ts\n * import { rngAesCtrDrbg256 } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const seed = randomBytes(48);\n * const prg = rngAesCtrDrbg256(seed);\n * prg.randomBytes(8);\n * ```\n */\nexport const rngAesCtrDrbg256 = /* @__PURE__ */ createAesDrbg(256);\n//#region CMAC\n/**\n * Left-shift by one bit and conditionally XOR with 0x87:\n * ```\n * if MSB(L) is equal to 0\n * then K1 := L << 1;\n * else K1 := (L << 1) XOR const_Rb;\n * ```\n *\n * Specs:\n * {@link https://www.rfc-editor.org/rfc/rfc4493.html#section-2.3 | RFC 4493 Section 2.3},\n * {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.3 | RFC 5297 Section 2.3}\n *\n * @returns modified `block` (for chaining)\n */\nfunction dbl(block) {\n let carry = 0;\n // Left shift by 1 bit\n for (let i = BLOCK_SIZE - 1; i >= 0; i--) {\n const newCarry = (block[i] & 0x80) >>> 7;\n block[i] = (block[i] << 1) | carry;\n carry = newCarry;\n }\n // XOR with 0x87 if there was a carry from the most significant bit.\n // RFC 4493 \u00A72.3 / RFC 5297 \u00A72.1: 0x87 is const_Rb for doubling in the\n // CMAC/S2V finite field with primitive polynomial x^128 + x^7 + x^2 + x + 1.\n // Branchless: `carry` derives from secret CMAC subkey material.\n block[BLOCK_SIZE - 1] ^= 0x87 & -carry;\n return block;\n}\n/**\n * `a XOR b`, running in-place on `a`.\n * @param a left operand and output\n * @param b right operand\n * @returns `a` (for chaining)\n */\nfunction xorBlock(a, b) {\n if (a.length !== b.length)\n throw new Error('xorBlock: blocks must have same length');\n for (let i = 0; i < a.length; i++) {\n a[i] = a[i] ^ b[i];\n }\n return a;\n}\n/**\n * xorend as defined in\n * {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.1 | RFC 5297 Section 2.1}.\n *\n * ```\n * leftmost(A, len(A)-len(B)) || (rightmost(A, len(B)) xor B)\n * ```\n *\n * Mutates `a` in place so the left prefix stays untouched and only the\n * rightmost `len(B)` bytes are xored with `b`.\n */\nfunction xorend(a, b) {\n if (b.length > a.length) {\n throw new Error('xorend: expected len(B) <= len(A)');\n }\n // keep leftmost part of `a` unchanged\n // and xor only the rightmost part:\n const offset = a.length - b.length;\n for (let i = 0; i < b.length; i++) {\n a[offset + i] = a[offset + i] ^ b[i];\n }\n return a;\n}\n/**\n * Internal CMAC class.\n */\nclass _CMAC {\n blockLen = BLOCK_SIZE;\n outputLen = BLOCK_SIZE;\n // CMAC can only decide between `K1` and `K2` once the true final block is known,\n // so updates process older blocks eagerly but keep one pending block buffered.\n buffer;\n pos;\n finished;\n destroyed;\n k1;\n k2;\n x;\n x32;\n xk;\n constructor(key) {\n abytes(key);\n validateKeyLength(key);\n this.xk = expandKeyLE(key);\n this.buffer = new Uint8Array(BLOCK_SIZE);\n this.pos = 0;\n this.finished = false;\n this.destroyed = false;\n this.x = new Uint8Array(BLOCK_SIZE);\n // Cached word view over `x`: process() runs once per 16 input bytes, so\n // it must not re-create views or re-validate per block like encryptBlock().\n this.x32 = u32(this.x);\n // L = AES_encrypt(K, const_Zero)\n const L = new Uint8Array(BLOCK_SIZE);\n encryptBlock(this.xk, L);\n // Generate subkeys K1 and K2 from the main key according to\n // {@link https://www.rfc-editor.org/rfc/rfc4493.html#section-2.3 | RFC 4493 Section 2.3}\n // K1\n this.k1 = dbl(L);\n this.k2 = dbl(new Uint8Array(this.k1));\n }\n // Consumes 16 bytes of `data` starting at `pos`; `pos` avoids a per-block\n // subarray view allocation in update().\n process(data, pos) {\n // RFC 4493 \u00A72.4 step 6 loop body: Y := X XOR M_i; X := AES-128(K, Y).\n const { x, x32, xk } = this;\n for (let i = 0; i < BLOCK_SIZE; i++)\n x[i] ^= data[pos + i];\n swap32IfBE(x32);\n const { s0, s1, s2, s3 } = encrypt(xk, x32[0], x32[1], x32[2], x32[3]);\n ((x32[0] = s0), (x32[1] = s1), (x32[2] = s2), (x32[3] = s3));\n swap32IfBE(x32);\n }\n update(data) {\n aexists(this);\n abytes(data);\n let pos = 0;\n if (this.pos) {\n const take = Math.min(BLOCK_SIZE - this.pos, data.length);\n this.buffer.set(data.subarray(0, take), this.pos);\n this.pos += take;\n pos = take;\n if (this.pos === BLOCK_SIZE && pos < data.length) {\n this.process(this.buffer, 0);\n this.pos = 0;\n }\n }\n // Keep one complete block buffered: an exact 16-byte tail may still be\n // M_n, and digestInto() must decide there whether RFC 4493 uses K1 or K2.\n while (pos + BLOCK_SIZE < data.length) {\n this.process(data, pos);\n pos += BLOCK_SIZE;\n }\n if (pos < data.length) {\n this.buffer.set(data.subarray(pos), 0);\n this.pos = data.length - pos;\n }\n return this;\n }\n // See {@link https://www.rfc-editor.org/rfc/rfc4493.html#section-2.4 | RFC 4493 Section 2.4}.\n digestInto(out) {\n aexists(this);\n // `digestInto(out)` is the no-allocation fast path, so AES block re-use below\n // requires a 32-bit-aligned caller buffer instead of hidden temp copies.\n aoutput32(out, this);\n this.finished = true;\n // `digestInto()` accepts out.length >= outputLen, so only the first block stores the tag.\n const view = out.subarray(0, this.outputLen);\n let last = new Uint8Array(BLOCK_SIZE);\n if (this.pos === BLOCK_SIZE) {\n // M_last := M_n XOR K1;\n last.set(this.buffer);\n xorBlock(last, this.k1);\n }\n else {\n // M_last := padding(M_n) XOR K2;\n //\n // [...] padding(x) is the concatenation of x and a single '1',\n // followed by the minimum number of '0's, so that the total length is\n // equal to 128 bits.\n last.set(this.buffer.subarray(0, this.pos));\n last[this.pos] = 0x80; // single '1' bit\n xorBlock(last, this.k2);\n }\n view.set(this.x); // X := AES_CBC(K, M_1..M_{n-1})\n xorBlock(view, last); // Y := X XOR M_last\n encryptBlock(this.xk, view); // T := AES-128(K, Y)\n clean(last);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n // Copy out before destroy() wipes the internal digest buffer in place.\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n destroy() {\n const { buffer, destroyed, x, xk, k1, k2 } = this;\n if (destroyed)\n return;\n this.destroyed = true;\n // Wipe the buffered tail, chaining value, expanded AES key, and both CMAC subkeys.\n clean(buffer, x, xk, k1, k2);\n }\n}\n/**\n * AES-CMAC (Cipher-based Message Authentication Code).\n * Specs: {@link https://www.rfc-editor.org/rfc/rfc4493.html | RFC 4493}.\n * @param msg - Message bytes to authenticate.\n * @param key - AES key bytes.\n * @returns 16-byte authentication tag. `cmac.create(...)` follows the same incremental MAC shape as\n * the other keyed helpers in this repo, including `blockLen`,\n * `outputLen`, `digestInto()` and `destroy()`.\n * @example\n * Authenticates a message with AES-CMAC and a fresh key.\n *\n * ```ts\n * import { cmac } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * cmac(new Uint8Array(), key);\n * ```\n */\n// The 16-byte probe key is only used to read static metadata; runtime CMAC\n// still accepts AES-128/192/256 keys.\nexport const cmac = /* @__PURE__ */ wrapMacConstructor(16, (key) => new _CMAC(key));\n/**\n * S2V (Synthetic Initialization Vector) function as described in\n * {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.4 | RFC 5297 Section 2.4}.\n *\n * ```\n * S2V(K, S1, ..., Sn) {\n * if n = 0 then\n * return V = AES-CMAC(K, <one>)\n * fi\n * D = AES-CMAC(K, <zero>)\n * for i = 1 to n-1 do\n * D = dbl(D) xor AES-CMAC(K, Si)\n * done\n * if len(Sn) >= 128 then\n * T = Sn xorend D\n * else\n * T = dbl(D) xor pad(Sn)\n * fi\n * return V = AES-CMAC(K, T)\n * }\n * ```\n *\n * S2V takes a key and a vector of strings S1, S2, ..., Sn and returns a 128-bit string.\n * The S2V function is used to generate a synthetic IV for AES-SIV.\n *\n * @param key - AES key (128, 192, or 256 bits)\n * @param strings - Array of byte arrays to process\n * @returns 128-bit synthetic IV\n */\nfunction s2v(key, strings) {\n validateKeyLength(key);\n const len = strings.length;\n if (len > 127) {\n // RFC 5297 \u00A77 only proves S2V secure for at most 127 components; SIV\n // spends one of those on the plaintext, leaving at most 126 AAD inputs.\n throw new Error('s2v: expected <= 127 inputs');\n }\n if (len === 0)\n return cmac(ONE_BLOCK, key);\n // D = AES-CMAC(K, <zero>)\n let d = cmac(EMPTY_BLOCK, key);\n // for i = 1 to n-1 do\n // D = dbl(D) xor AES-CMAC(K, Si)\n for (let i = 0; i < len - 1; i++) {\n dbl(d);\n const cmacResult = cmac(strings[i], key);\n xorBlock(d, cmacResult);\n clean(cmacResult);\n }\n const s_n = strings[len - 1];\n // Earlier components are validated through cmac(...); validate the final one explicitly because\n // the Uint8Array.from()/set() paths below would otherwise coerce array-like inputs silently.\n abytes(s_n);\n let t;\n // if len(Sn) >= 128 then\n if (s_n.byteLength >= BLOCK_SIZE) {\n // T = Sn xorend D\n t = xorend(Uint8Array.from(s_n), d);\n }\n else {\n // pad(Sn):\n const paddedSn = new Uint8Array(BLOCK_SIZE);\n paddedSn.set(s_n);\n paddedSn[s_n.length] = 0x80; // padding: 0x80 followed by zeros\n // T = dbl(D) xor pad(Sn)\n t = xorBlock(dbl(d), paddedSn);\n clean(paddedSn);\n }\n // V = AES-CMAC(K, T)\n const result = cmac(t, key);\n clean(d, t);\n return result;\n}\n/**\n * Use `gcmsiv` or `aessiv`.\n * @returns Never; always throws with the migration hint.\n * @throws If called; `siv()` is a removed v1 alias. {@link Error}\n * @example\n * `siv()` was removed in v2; use `gcmsiv()` for nonce-based SIV instead.\n *\n * ```ts\n * import { gcmsiv } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * const nonce = randomBytes(12);\n * const cipher = gcmsiv(key, nonce);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const siv = () => {\n throw new Error('\"siv\" from v1 is now \"gcmsiv\"');\n};\n/**\n * **SIV**: Synthetic Initialization Vector (SIV) Authenticated Encryption\n * Nonce is derived from the plaintext and AAD using the S2V function.\n * Supports at most 126 AAD components. RFC 5297 nonce-based use is expressed by\n * passing the nonce as the final AAD component before the plaintext.\n * See {@link https://datatracker.ietf.org/doc/html/rfc5297.html | RFC 5297}.\n * @param key - 32-byte, 48-byte, or 64-byte key.\n * @param AAD - Additional authenticated data chunks (up to 126).\n * @returns AEAD cipher instance.\n * @example\n * Authenticates and encrypts plaintext with a fresh key without requiring unique nonces.\n *\n * ```ts\n * import { aessiv } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const cipher = aessiv(key);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const aessiv = /* @__PURE__ */ wrapCipher({ blockSize: 16, tagLength: 16, withAAD: true }, function aessiv(key, ...AAD) {\n // From RFC 5297: Section 6.1, 6.2, 6.3:\n const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 132);\n const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 132 + 16);\n if (AAD.length > 126) {\n // RFC 5297 \u00A72.6 / \u00A72.7 / \u00A77: SIV passes the plaintext as the last S2V\n // component, so callers only get 126 associated-data components.\n throw new Error('\"AAD\" expected <= 126 items');\n }\n AAD.forEach((aad) => abytes(aad));\n abytes(key);\n if (![32, 48, 64].includes(key.length))\n throw new Error('\"aes key\" expected Uint8Array of length 32/48/64, got length=' + key.length);\n // The key is split into equal halves, K1 = leftmost(K, len(K)/2) and\n // K2 = rightmost(K, len(K)/2). K1 is used for S2V and K2 is used for CTR.\n // This borrows caller key/AAD buffers by reference; mutating them after\n // construction changes future encrypt/decrypt results.\n const k1 = key.subarray(0, key.length / 2);\n const k2 = key.subarray(key.length / 2);\n return {\n // {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.6 | RFC 5297 Section 2.6}\n encrypt(plaintext) {\n PLAIN_LIMIT(plaintext.length);\n const v = s2v(k1, [...AAD, plaintext]);\n // clear out the 31st and 63rd (rightmost) bit:\n const q = Uint8Array.from(v);\n q[8] &= 0x7f;\n q[12] &= 0x7f;\n // encrypt:\n const c = ctr(k2, q).encrypt(plaintext);\n return concatBytes(v, c);\n },\n // {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.7 | RFC 5297 Section 2.7}\n decrypt(ciphertext) {\n CIPHER_LIMIT(ciphertext.length);\n const v = ciphertext.subarray(0, BLOCK_SIZE);\n const c = ciphertext.subarray(BLOCK_SIZE);\n // clear out the 31st and 63rd (rightmost) bit:\n const q = Uint8Array.from(v);\n q[8] &= 0x7f;\n q[12] &= 0x7f;\n // decrypt:\n const p = ctr(k2, q).decrypt(c);\n // verify tag:\n const t = s2v(k1, [...AAD, p]);\n if (equalBytes(t, v)) {\n return p;\n }\n else {\n clean(p);\n throw new Error('invalid siv tag');\n }\n },\n };\n});\n//#endregion\n/**\n * Unsafe low-level internal methods. May change at any time.\n * Callers are expected to use reviewed expanded-key outputs, pass mutable and\n * aligned 16-byte blocks where required, and treat several helpers as in-place\n * mutations of their input buffers or counters.\n */\nexport const unsafe = /* @__PURE__ */ Object.freeze({\n expandKeyLE,\n expandKeyDecLE,\n encrypt,\n decrypt,\n encryptBlock,\n decryptBlock,\n ctrCounter,\n ctr32,\n dbl,\n xorBlock,\n xorend,\n s2v,\n});\nexport const __TESTS = /* @__PURE__ */ Object.freeze({\n incBytes: incBytes,\n});\n", "const U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();\nconst _32n = /* @__PURE__ */ BigInt(32);\n// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high\n// }` to match little-endian word order rather than the property names.\nfunction fromBig(n, le = false) {\n if (le)\n 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// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array\n// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.\nfunction split(lst, le = false) {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS\n// bitwise results back to uint32 first, and little-endian callers must swap.\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// Split a JS number into u32 halves without a BigInt allocation. Exact only for integers\n// `0 <= n < 2**53`; callers use it on byte / bit counters, which JS length math caps far below\n// that (an ArrayBuffer cannot exceed 2**53 - 1 bytes).\nconst fromNumH = (n) => (n / 2 ** 32) | 0;\nconst fromNumL = (n) => n >>> 0;\n// Drop-in replacement for `view.setBigUint64(byteOffset, BigInt(n), isLE)` without the per-call\n// BigInt allocation. Same `n < 2**53` precondition as `fromNumH`/`fromNumL`.\nfunction setU64FromNum(view, byteOffset, n, isLE) {\n const h = fromNumH(n);\n const l = fromNumL(n);\n view.setUint32(byteOffset, isLE ? l : h, isLE);\n view.setUint32(byteOffset + 4, isLE ? h : l, isLE);\n}\n// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`.\nconst shrSH = (h, _l, s) => h >>> s;\n// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`.\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half.\nconst rotr32H = (_h, l) => l;\n// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half.\nconst rotr32L = (h, _l) => h;\n// 64-bit left rotates (rotl*) are not defined here: sha3.ts, their only consumer, keeps\n// local copies so V8 inlines them into keccakP.\n// Add two split 64-bit words and return the split `{ h, l }` sum.\n// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out\n// of the low sum and instead use division.\nfunction add(Ah, Al, Bh, Bl) {\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\n// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`.\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\n// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`.\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`.\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\n// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`.\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`.\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\n// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`.\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, fromNumH, fromNumL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, setU64FromNum, shrSH, shrSL, split, toBig };\n", "/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - value to test\n * @returns `true` when the value is a Uint8Array-compatible view.\n * @example\n * Check whether a value is a Uint8Array-compatible view.\n * ```ts\n * isBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function isBytes(a) {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.\n // The fallback still requires a real ArrayBuffer view, so plain\n // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and\n // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n 'BYTES_PER_ELEMENT' in a &&\n a.BYTES_PER_ELEMENT === 1));\n}\n// Shared error-message prefix builder. Only called on throw paths, so assert\n// success paths never pay for the string concatenation.\nconst atitle = (title) => (title ? `\"${title}\" ` : '');\n/**\n * Asserts something is a non-negative integer.\n * @param n - number to validate\n * @param title - label included in thrown errors\n * @returns The validated number.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a non-negative integer option.\n * ```ts\n * anumber(32, 'length');\n * ```\n */\nexport function anumber(n, title = '') {\n if (typeof n !== 'number')\n throw new TypeError(atitle(title) + 'expected number, got ' + typeof n);\n if (!Number.isSafeInteger(n) || n < 0)\n throw new RangeError(atitle(title) + 'expected integer >= 0, got ' + n);\n return n;\n}\n/**\n * Asserts something is a boolean.\n * @param value - value to validate\n * @param title - label included in thrown errors\n * @returns The validated boolean.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a boolean option.\n * ```ts\n * abool(true, 'enableXOF');\n * ```\n */\nexport function abool(value, title = '') {\n if (typeof value !== 'boolean')\n throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);\n return value;\n}\n/**\n * Asserts something is Uint8Array.\n * @param value - value to validate\n * @param length - optional exact length constraint\n * @param title - label included in thrown errors\n * @returns The validated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate that a value is a byte array.\n * ```ts\n * abytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function abytes(value, length, title = '') {\n // Success path first: this runs at the start of every update() / digestInto(), and the\n // common `abytes(data)` form must not pay for length handling it does not use.\n if (isBytes(value) && (length === undefined || value.length === length))\n return value;\n // Error path: recompute freely to build the exact message.\n if (length !== undefined)\n anumber(length, 'length');\n const bytes = isBytes(value);\n const ofLen = length !== undefined ? ` of length ${length}` : '';\n const got = bytes ? `length=${value.length}` : `type=${typeof value}`;\n const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes)\n throw new TypeError(message);\n throw new RangeError(message);\n}\n/**\n * Copies bytes into a fresh Uint8Array.\n * Buffer-style slices can alias the same backing store, so callers that need ownership should copy.\n * @param bytes - source bytes to clone\n * @returns Freshly allocated copy of `bytes`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Clone a byte array before mutating it.\n * ```ts\n * const copy = copyBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function copyBytes(bytes) {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes));\n}\n/**\n * Asserts something is a wrapped hash constructor.\n * @param h - hash constructor to validate\n * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}\n * @throws On invalid hash metadata ranges or values. {@link RangeError}\n * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}\n * @example\n * Validate a callable hash wrapper.\n * ```ts\n * import { ahash } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * ahash(sha256);\n * ```\n */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new TypeError('expected hash wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass\n // validation and can produce empty outputs instead of failing fast.\n if (h.outputLen < 1 || h.blockLen < 1)\n throw new Error('hash blockLen / outputLen must be >= 1');\n}\nconst aobject = (value, label) => {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n throw new TypeError((label === 'object' ? '' : `\"${label}\" `) + 'expected object, got type=' + typeof value);\n};\nconst aopts = (value, label) => {\n aobject(value, label);\n const proto = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null)\n throw new TypeError(`\"${label}\" expected plain object`);\n // Object.assign() treats an own \"__proto__\" source key as a write to the target's legacy\n // prototype setter. Reject it before merging so inherited option values cannot be injected.\n if (Object.hasOwn(value, '__proto__'))\n throw new TypeError(`\"${label}.__proto__\" is not allowed`);\n};\n/**\n * Asserts a hash instance has not been destroyed or finished.\n * @param instance - hash instance to validate\n * @param checkFinished - whether to reject finalized instances\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Validate that a hash instance is still usable.\n * ```ts\n * import { aexists } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aexists(hash);\n * ```\n */\nexport function aexists(instance, checkFinished = true) {\n // Runs on every update()/digestInto(); the flags are library-owned booleans, so only their\n // truthiness is checked - re-validating their type per call was pure hot-path overhead.\n if (instance.destroyed)\n throw new Error('hash was destroyed');\n if (checkFinished && instance.finished)\n throw new Error('digest() was already called');\n}\n/**\n * Asserts output is a sufficiently-sized byte array.\n * @param out - destination buffer\n * @param instance - hash instance providing output length\n * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a caller-provided digest buffer.\n * ```ts\n * import { aoutput } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aoutput(new Uint8Array(hash.outputLen), hash);\n * ```\n */\nexport function aoutput(out, instance) {\n abytes(out, undefined, 'output');\n // `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast\n // when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call.\n const min = instance.outputLen;\n if (!(out.length >= min)) {\n throw new RangeError('\"output\" expected length >= ' + min);\n }\n}\n/**\n * Casts a typed array view to Uint8Array.\n * @param arr - source typed array\n * @returns Uint8Array view over the same buffer.\n * @example\n * Reinterpret a typed array as bytes.\n * ```ts\n * u8(new Uint32Array([1, 2]));\n * ```\n */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Casts a typed array view to Uint32Array.\n * `arr.byteOffset` must already be 4-byte aligned or the platform\n * Uint32Array constructor will throw.\n * @param arr - source typed array\n * @returns Uint32Array view over the same buffer.\n * @example\n * Reinterpret a byte array as 32-bit words.\n * ```ts\n * u32(new Uint8Array(8));\n * ```\n */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/**\n * Zeroizes typed arrays in place. Warning: JS provides no guarantees.\n * @param arrays - arrays to overwrite with zeros\n * @example\n * Zeroize sensitive buffers in place.\n * ```ts\n * clean(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - source typed array\n * @returns DataView over the same buffer region.\n * @example\n * Create a DataView over an existing buffer.\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Rotate-right operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the right.\n * ```ts\n * rotr(0x12345678, 8);\n * ```\n */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/**\n * Rotate-left operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the left.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Whether the current platform is little-endian. */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/**\n * Byte-swap operation for uint32 values.\n * @param word - source word\n * @returns Word with reversed byte order.\n * @example\n * Reverse the byte order of a 32-bit word.\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/**\n * Conditionally byte-swaps one 32-bit word on big-endian platforms.\n * @param n - source word\n * @returns Original or byte-swapped word depending on platform endianness.\n * @example\n * Normalize a 32-bit word for host endianness.\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n) >>> 0;\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - array to mutate\n * @returns The same array after mutation; callers pass live state arrays here.\n * @example\n * Reverse the byte order of every word in place.\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n/**\n * Conditionally byte-swaps a Uint32Array on big-endian platforms.\n * @param u - array to normalize for host endianness\n * @returns Original or byte-swapped array depending on platform endianness.\n * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.\n * @example\n * Normalize a word array for host endianness.\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string.\n * Uses the built-in function when available and assumes it matches the tested\n * fallback semantics.\n * @param bytes - bytes to encode\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Convert bytes to lowercase hexadecimal.\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\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// Strict ASCII nibble parser: non-ASCII hex lookalikes are rejected as undefined.\n// ASCII codes: '0'..'9' = 48..57, 'A'..'F' = 65..70, 'a'..'f' = 97..102.\n// prettier-ignore\nfunction asciiToBase16(ch) {\n return ch >= 48 && ch <= 57 ? ch - 48 // '2' => 50-48\n : ch >= 65 && ch <= 70 ? ch - (65 - 10) // 'B' => 66-(65-10)\n : ch >= 97 && ch <= 102 ? ch - (97 - 10) // 'b' => 98-(97-10)\n : undefined;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - hexadecimal string to decode\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode lowercase hexadecimal into bytes.\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return Uint8Array.fromHex(hex);\n }\n catch (error) {\n if (error instanceof SyntaxError)\n throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new RangeError('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)); // parse first char, multiply it by 16\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); // parse second char\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9\n }\n return array;\n}\n/**\n * Yields to the host task scheduler so timers, I/O, and rendering can make progress.\n * Uses the Web Scheduling API when available or `setTimeout` as a cross-platform fallback.\n * Host-task yields are much slower than microtasks (roughly 1ms with the timer fallback), so\n * async loops should use `asyncTick >= 10` to amortize scheduling overhead to about 10% while\n * still allowing other event-loop work to proceed.\n * @param onReject - optional cleanup invoked only if the host yield fails\n * @example\n * Yield to the next scheduler tick.\n * ```ts\n * await nextTick();\n * ```\n */\nexport function nextTick(onReject) {\n const host = globalThis;\n if (typeof host.scheduler?.yield === 'function') {\n const promise = host.scheduler.yield();\n // Keep the original scheduler rejection; this handler exists only for cleanup.\n if (onReject)\n promise.catch(onReject);\n return promise;\n }\n return new Promise((resolve) => host.setTimeout(resolve, 0));\n}\n/**\n * Returns control to the host event loop every `tick` milliseconds to avoid blocking long loops.\n * @param iters - number of loop iterations to run\n * @param tick - maximum time slice in milliseconds\n * @param cb - callback executed on each iteration\n * @param onReject - optional cleanup invoked only if a host yield fails\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Run a loop that periodically yields back to the event loop.\n * ```ts\n * await asyncLoop(2, 0, () => {});\n * ```\n */\nexport async function asyncLoop(iters, tick, cb, onReject) {\n anumber(iters, 'iters');\n anumber(tick, 'tick');\n if (typeof cb !== 'function')\n throw new TypeError('callback must be a function');\n // Callback is synchronous by contract; asyncLoop only yields between sync work windows.\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)\n continue;\n await nextTick(onReject);\n // Track only synchronous work time; scheduler delay after yielding is outside our budget.\n ts = Date.now();\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * Non-ASCII details are delegated to the platform `TextEncoder`.\n * @param str - string to encode\n * @returns UTF-8 encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode a string as UTF-8 bytes.\n * ```ts\n * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new TypeError('string expected');\n const encoded = new TextEncoder().encode(str);\n try {\n // Copy into the current realm for Firefox extension contexts. Callers that own the returned\n // buffer can then wipe it independently of TextEncoder's temporary result.\n return new Uint8Array(encoded); // https://bugzil.la/1681809\n }\n finally {\n clean(encoded);\n }\n}\n/**\n * Helper for KDFs: consumes Uint8Array or string.\n * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.\n * @param data - user-provided KDF input\n * @param errorTitle - label included in thrown errors\n * @returns Byte representation of the input.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Normalize KDF input to bytes.\n * ```ts\n * kdfInputToBytes('password');\n * ```\n */\nexport function kdfInputToBytes(data, errorTitle = '') {\n if (typeof data === 'string')\n return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - arrays to concatenate\n * @returns Concatenated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Concatenate multiple byte arrays.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays) {\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 * Validates declared required and optional field types on a plain object.\n * This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct\n * one-line guards such as `abytes()`, `abool()`, or `anumber()` instead.\n * @param object - object to validate\n * @param fields - map of required field names to expected types\n * @param optFields - map of optional field names to expected types\n * @param title - label included in thrown errors\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate required and optional option fields.\n * ```ts\n * validateObject({ N: 1024, dkLen: 32 }, { N: 'number' }, { dkLen: 'number' });\n * ```\n */\nexport const validateObject = (object, fields = {}, optFields = {}, title = 'object') => {\n aobject(object, title);\n aobject(fields, 'fields');\n aobject(optFields, 'optFields');\n function checkField(fieldName, expectedType, isOpt) {\n const label = title === 'object' ? `param \"${String(fieldName)}\"` : `\"${title}.${String(fieldName)}\"`;\n // Config fields must be explicit own properties. Optional inherited values are rejected too\n // because callers keep reading the same options object after validation.\n const val = object[fieldName];\n // Runtime objects such as Field instances intentionally satisfy required method slots\n // via their shared prototype.\n if (!Object.hasOwn(object, fieldName) &&\n (isOpt ? val !== undefined : expectedType !== 'function')) {\n throw new TypeError(`${label} is invalid: expected own property`);\n }\n if (isOpt && val === undefined)\n return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);\n }\n const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n};\n/**\n * Merges default options and passed options.\n * @param defaults - base option object\n * @param opts - user overrides\n * @param title - label included in thrown override errors\n * @returns Fresh merged option object with a null prototype.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Merge user overrides onto default options.\n * ```ts\n * checkOpts({ dkLen: 32 }, { asyncTick: 10 });\n * ```\n */\nexport function checkOpts(defaults, opts, title = 'opts') {\n aopts(defaults, 'defaults');\n if (opts !== undefined)\n aopts(opts, title);\n // Callers read optional fields directly, so omitted values must not fall through to ambient\n // Object.prototype pollution (for example a forged `dkLen` changing SHAKE's default output).\n const merged = Object.assign(Object.create(null), defaults, opts);\n return merged;\n}\n/**\n * Creates a callable hash function from a stateful class constructor.\n * @param hashCons - hash constructor or factory\n * @param info - optional metadata such as DER OID\n * @returns Frozen callable hash wrapper with `.create()`.\n * Wrapper construction eagerly calls `hashCons(undefined)` once to read\n * `outputLen` / `blockLen`, so constructor side effects happen at module\n * init time.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Wrap a stateful hash constructor into a callable helper.\n * ```ts\n * import { createHasher } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const wrapped = createHasher(sha256.create, { oid: sha256.oid });\n * wrapped(new Uint8Array([1]));\n * ```\n */\nexport function createHasher(hashCons, info = {}) {\n if (typeof hashCons !== 'function')\n throw new TypeError('\"hashCons\" expected function, got type=' + typeof hashCons);\n info = checkOpts({}, info, 'info');\n const hashC = (msg, opts) => hashCons(opts)\n .update(msg)\n .digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.canXOF = tmp.canXOF;\n hashC.create = (opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\n}\n/**\n * Cryptographically secure PRNG backed by `crypto.getRandomValues`.\n * @param bytesLength - number of random bytes to generate\n * @returns Random bytes.\n * The platform `getRandomValues()` implementation still defines any\n * single-call length cap, and this helper rejects oversize requests\n * with a stable library `RangeError` instead of host-specific errors.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}\n * @example\n * Generate a fresh random key or nonce.\n * ```ts\n * const key = randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32) {\n // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.\n anumber(bytesLength, 'bytesLength');\n const cr = typeof globalThis === 'object' ? globalThis.crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n // Web Cryptography API Level 2 \u00A710.1.1:\n // if `byteLength > 65536`, throw `QuotaExceededError`.\n // Keep the guard explicit so callers can see the quota in code\n // instead of discovering it by reading the spec or host errors.\n // This wrapper surfaces the same quota as a stable library RangeError.\n if (bytesLength > 65536)\n throw new RangeError(`\"bytesLength\" expected <= 65536, got ${bytesLength}`);\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n/**\n * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.\n * @param suffix - final OID byte for the selected hash.\n * The helper accepts any byte even though only the documented NIST hash\n * suffixes are meaningful downstream.\n * @returns Object containing the DER-encoded OID.\n * @example\n * Build OID metadata for a NIST hash.\n * ```ts\n * oidNist(0x01);\n * ```\n */\nexport const oidNist = (suffix) => ({\n // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.\n // Larger suffix values would need base-128 OID encoding and a different length byte.\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n", "/**\n * SHA3 (keccak) hash function, based on a new \"Sponge function\" design.\n * Different from older hashes, the internal state is bigger than output size.\n *\n * Check out\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf | FIPS-202},\n * {@link https://keccak.team/keccak.html | Website}, and\n * {@link https://crypto.stackexchange.com/q/15727 | the differences between\n * SHA-3 and Keccak}.\n *\n * Check out `sha3-addons` module for cSHAKE, k12, and others.\n * @module\n */\nimport { split } from \"./_u64.js\";\n// prettier-ignore\nimport { abool, abytes, aexists, anumber, aoutput, checkOpts, clean, createHasher, oidNist, swap32IfBE, u32 } from \"./utils.js\";\n// No __PURE__ annotations in sha3 header:\n// EVERYTHING is in fact used on every export.\n// Various per round constants calculations\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst _7n = BigInt(7);\nconst _256n = BigInt(256);\n// FIPS 202 Algorithm 5 rc(): when the outgoing bit is 1, the 8-bit LFSR xors\n// taps 0, 4, 5, and 6, which compresses to the feedback mask `0x71`.\nconst _0x71n = BigInt(0x71);\nconst SHA3_PI = [];\nconst SHA3_ROTL = [];\nconst _SHA3_IOTA = []; // no pure annotation: var is always used\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n)\n t ^= _1n << ((_1n << BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst IOTAS = split(_SHA3_IOTA, true);\n// `split(..., true)` keeps the local little-endian lane-word layout used by\n// `state32`, so these `H` / `L` tables follow the file's first-word /\n// second-word lane slots rather than `_u64.ts`'s usual high/low naming.\nconst SHA3_IOTA_H = IOTAS[0];\nconst SHA3_IOTA_L = IOTAS[1];\n// 64-bit left rotates as u32 pairs. Inlined here (not imported from _u64) so V8 can\n// inline them into keccakP \u2014 the import path costs ~24% on sha3_256. SHA3 is the only\n// consumer of left-rotates; other hashes use right-rotates from _u64.\n// Valid for s in 1..31 (SH/SL) and 33..63 (BH/BL); keccak never rotates by 0/32/64.\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\nconst rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n// Reused Theta scratch buffer (column parities), same pattern as SHA256_W in sha2.\n// keccakP never calls user code, so the shared buffer cannot be observed mid-permutation.\nconst B = new Uint32Array(5 * 2);\n/**\n * `keccakf1600` internal permutation, additionally allows adjusting the round count.\n * @param s - 5x5 Keccak state encoded as 25 lanes split into 50 uint32 words\n * in this file's local little-endian lane-word order\n * @param rounds - number of rounds to execute\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If `rounds` is outside the supported `1..24` range. {@link Error}\n * @example\n * Permute a Keccak state with the default 24 rounds.\n * ```ts\n * keccakP(new Uint32Array(50));\n * ```\n */\nexport function keccakP(s, rounds = 24) {\n if (!(s instanceof Uint32Array))\n throw new TypeError('\"s\" expected Uint32Array(50), got type=' + typeof s);\n if (s.length !== 50)\n throw new RangeError('\"s\" expected Uint32Array(50), got length=' + s.length);\n anumber(rounds, 'rounds');\n // This implementation precomputes only the standard Keccak-f[1600] 24-round Iota table.\n if (rounds < 1 || rounds > 24)\n throw new Error('\"rounds\" expected integer 1..24');\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta \u03B8\n for (let x = 0; x < 10; x++)\n B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (\u03C1) and Pi (\u03C0)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (\u03C7)\n // Same as:\n // for (let x = 0; x < 10; x++) B[x] = s[y + x];\n // for (let x = 0; x < 10; x++) s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n for (let y = 0; y < 50; y += 10) {\n const b0 = s[y], b1 = s[y + 1], b2 = s[y + 2], b3 = s[y + 3];\n s[y] ^= ~s[y + 2] & s[y + 4];\n s[y + 1] ^= ~s[y + 3] & s[y + 5];\n s[y + 2] ^= ~s[y + 4] & s[y + 6];\n s[y + 3] ^= ~s[y + 5] & s[y + 7];\n s[y + 4] ^= ~s[y + 6] & s[y + 8];\n s[y + 5] ^= ~s[y + 7] & s[y + 9];\n s[y + 6] ^= ~s[y + 8] & b0;\n s[y + 7] ^= ~s[y + 9] & b1;\n s[y + 8] ^= ~b0 & b2;\n s[y + 9] ^= ~b1 & b3;\n }\n // Iota (\u03B9)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n clean(B);\n}\n/**\n * Keccak sponge function.\n * @param blockLen - absorb/squeeze rate in bytes\n * @param suffix - domain separation suffix byte\n * @param outputLen - default digest length in bytes. This base sponge only\n * requires a non-negative integer; wrappers that need positive output\n * lengths must enforce that themselves.\n * @param enableXOF - whether XOF output is allowed\n * @param rounds - number of Keccak-f rounds\n * @example\n * Build a sponge state, absorb bytes, then finalize a digest.\n * ```ts\n * const hash = new Keccak(136, 0x06, 32);\n * hash.update(new Uint8Array([1, 2, 3]));\n * hash.digest();\n * ```\n */\nexport class Keccak {\n state;\n pos = 0;\n posOut = 0;\n finished = false;\n state32;\n destroyed = false;\n blockLen;\n suffix;\n outputLen;\n canXOF;\n enableXOF = false;\n rounds;\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {\n anumber(blockLen, 'blockLen');\n anumber(suffix, 'suffix');\n anumber(rounds, 'rounds');\n abool(enableXOF, 'enableXOF');\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.canXOF = enableXOF;\n this.rounds = rounds;\n // Can be passed from user as dkLen\n anumber(outputLen, 'outputLen');\n // Only keccak-f1600 is supported: 1600 bits (5x5 matrix of 64bit) === 200 bytes of state.\n if (!(0 < blockLen && blockLen < 200))\n throw new Error('\"blockLen\" must be 1..199');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n clone() {\n return this._cloneInto();\n }\n keccak() {\n swap32IfBE(this.state32);\n keccakP(this.state32, this.rounds);\n swap32IfBE(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data) {\n aexists(this);\n abytes(data);\n const { blockLen, state, state32 } = this;\n const len = data.length;\n // Absorb full blocks with u32 XORs when both sides are 4-byte aligned.\n // XOR of same-position words equals XOR of same-position bytes, so this is endianness-safe.\n const canUseU32 = blockLen % 4 === 0 && data.byteOffset % 4 === 0;\n const blockLen32 = blockLen / 4;\n const data32 = canUseU32 && len >= blockLen ? u32(data) : undefined;\n for (let pos = 0; pos < len;) {\n if (data32 !== undefined && this.pos === 0 && pos % 4 === 0 && len - pos >= blockLen) {\n for (let i = 0, o = pos / 4; i < blockLen32; i++)\n state32[i] ^= data32[o + i];\n pos += blockLen;\n // Subclasses (_KeccakPRG) read `this.pos` inside their `keccak()` override,\n // so it must reflect the fully-absorbed block before the permutation fires.\n this.pos = blockLen;\n this.keccak();\n continue;\n }\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++)\n state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen)\n this.keccak();\n }\n return this;\n }\n finish() {\n if (this.finished)\n return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // FIPS 202 appends the SHA3/SHAKE domain-separation suffix before pad10*1.\n // These byte values already include the first padding bit, while the\n // final `0x80` below supplies the closing `1` bit in the last rate byte.\n state[pos] ^= suffix;\n // If that combined suffix lands in the last rate byte and already sets\n // bit 7, absorb it first so the final pad10*1 bit can be xored into a\n // fresh block.\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1)\n this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n writeInto(out) {\n aexists(this, false);\n abytes(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len;) {\n if (this.posOut >= blockLen)\n this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out) {\n // Plain SHA3/Keccak usage with XOF is probably a mistake, but this base\n // class is also reused by SHAKE/cSHAKE/KMAC/TupleHash/ParallelHash/\n // TurboSHAKE/KangarooTwelve wrappers that intentionally enable XOF.\n if (!this.enableXOF)\n throw new Error('XOF is not enabled');\n return this.writeInto(out);\n }\n xof(bytes) {\n anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out) {\n aoutput(out, this);\n if (this.finished)\n throw new Error('digest() was already called');\n // `aoutput(...)` allows oversized buffers; digestInto() must fill only the advertised digest.\n this.writeInto(out.length === this.outputLen ? out : out.subarray(0, this.outputLen));\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.outputLen);\n this.digestInto(out);\n return out;\n }\n destroy() {\n this.destroyed = true;\n clean(this.state);\n }\n _cloneInto(to) {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds);\n // Reused destinations can come from a different rate/capacity variant, so clone must rewrite\n // the sponge geometry as well as the state words.\n to.blockLen = blockLen;\n to.state32.set(this.state32);\n // Sponge padding and XOF output are positional, so both offsets are part of the clone state.\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n // Clones must preserve the public capability bit too; `_KMAC` reuses this path and deep clone\n // tests compare instance fields directly, so leaving `canXOF` behind makes the clone lie.\n to.canXOF = this.canXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\nconst genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);\n/**\n * SHA3-224 hash function.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA3-224.\n * ```ts\n * sha3_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha3_224 = /* @__PURE__ */ genKeccak(0x06, 144, 28, \n/* @__PURE__ */ oidNist(0x07));\n/**\n * SHA3-256 hash function. Different from keccak-256.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA3-256.\n * ```ts\n * sha3_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha3_256 = /* @__PURE__ */ genKeccak(0x06, 136, 32, \n/* @__PURE__ */ oidNist(0x08));\n/**\n * SHA3-384 hash function.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA3-384.\n * ```ts\n * sha3_384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha3_384 = /* @__PURE__ */ genKeccak(0x06, 104, 48, \n/* @__PURE__ */ oidNist(0x09));\n/**\n * SHA3-512 hash function.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA3-512.\n * ```ts\n * sha3_512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha3_512 = /* @__PURE__ */ genKeccak(0x06, 72, 64, \n/* @__PURE__ */ oidNist(0x0a));\n/**\n * Keccak-224 hash function.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with Keccak-224.\n * ```ts\n * keccak_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const keccak_224 = /* @__PURE__ */ genKeccak(0x01, 144, 28);\n/**\n * Keccak-256 hash function. Different from SHA3-256.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with Keccak-256.\n * ```ts\n * keccak_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const keccak_256 = /* @__PURE__ */ genKeccak(0x01, 136, 32);\n/**\n * Keccak-384 hash function.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with Keccak-384.\n * ```ts\n * keccak_384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const keccak_384 = /* @__PURE__ */ genKeccak(0x01, 104, 48);\n/**\n * Keccak-512 hash function.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with Keccak-512.\n * ```ts\n * keccak_512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const keccak_512 = /* @__PURE__ */ genKeccak(0x01, 72, 64);\nconst genShake = (suffix, blockLen, outputLen, info = {}) => createHasher((opts = {}) => {\n opts = checkOpts({}, opts);\n return new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true);\n}, info);\n/**\n * SHAKE128 XOF with 128-bit security and a 16-byte default output.\n * @param msg - message bytes to hash\n * @param opts - Optional output-length override. See {@link ShakeOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHAKE128.\n * ```ts\n * shake128(new Uint8Array([97, 98, 99]), { dkLen: 32 });\n * ```\n */\nexport const shake128 = \n/* @__PURE__ */\ngenShake(0x1f, 168, 16, /* @__PURE__ */ oidNist(0x0b));\n/**\n * SHAKE256 XOF with 256-bit security and a 32-byte default output.\n * @param msg - message bytes to hash\n * @param opts - Optional output-length override. See {@link ShakeOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHAKE256.\n * ```ts\n * shake256(new Uint8Array([97, 98, 99]), { dkLen: 64 });\n * ```\n */\nexport const shake256 = \n/* @__PURE__ */\ngenShake(0x1f, 136, 32, /* @__PURE__ */ oidNist(0x0c));\n/**\n * SHAKE128 XOF with 256-bit output (NIST version).\n * @param msg - message bytes to hash\n * @param opts - Optional output-length override. See {@link ShakeOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHAKE128 using a 32-byte default output.\n * ```ts\n * shake128_32(new Uint8Array([97, 98, 99]), { dkLen: 32 });\n * ```\n */\nexport const shake128_32 = \n/* @__PURE__ */\ngenShake(0x1f, 168, 32, /* @__PURE__ */ oidNist(0x0b));\n/**\n * SHAKE256 XOF with 512-bit output (NIST version).\n * @param msg - message bytes to hash\n * @param opts - Optional output-length override. See {@link ShakeOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHAKE256 using a 64-byte default output.\n * ```ts\n * shake256_64(new Uint8Array([97, 98, 99]), { dkLen: 64 });\n * ```\n */\nexport const shake256_64 = \n/* @__PURE__ */\ngenShake(0x1f, 136, 64, /* @__PURE__ */ oidNist(0x0c));\n", "/**\n * SHA3 (keccak) addons.\n *\n * * cSHAKE, KMAC, TupleHash, ParallelHash + XOF variants from\n * {@link https://csrc.nist.gov/pubs/sp/800/185/final | NIST SP 800-185}\n * * KangarooTwelve \uD83E\uDD98 and TurboSHAKE - reduced-round keccak from\n * {@link https://datatracker.ietf.org/doc/rfc9861/ | RFC 9861}\n * * KeccakPRG: Pseudo-random generator based on Keccak\n * ({@link https://keccak.team/files/CSF-0.1.pdf | pdf})\n * @module\n */\nimport { Keccak } from \"./sha3.js\";\nimport { abytes, aexists, anumber, checkOpts, clean, copyBytes, createHasher, randomBytes, kdfInputToBytes, u32, } from \"./utils.js\";\n// cSHAKE && KMAC (NIST SP800-185)\nconst _8n = /* @__PURE__ */ BigInt(8);\nconst _ffn = /* @__PURE__ */ BigInt(0xff);\n// It is safe to use bigints here, since they used only for length encoding (not actual data).\n// We use bigints in sha256 for lengths too.\n// Callers are still expected to supply SP 800-185-valid lengths\n// (`0 <= x < 2^2040`); this helper does not enforce that bound.\n// Minimal big-endian bytes of `n`, at least one byte long (SP 800-185 \u00A72.3.1).\nfunction encodeBytes(n) {\n n = BigInt(n);\n const res = [Number(n & _ffn)];\n n >>= _8n;\n for (; n > 0; n >>= _8n)\n res.unshift(Number(n & _ffn));\n return res;\n}\n// left_encode(n): byte count is prepended.\nfunction leftEncode(n) {\n const res = encodeBytes(n);\n res.unshift(res.length);\n return new Uint8Array(res);\n}\n// right_encode(n): byte count is appended.\nfunction rightEncode(n) {\n const res = encodeBytes(n);\n res.push(res.length);\n return new Uint8Array(res);\n}\n// `dkLen` range validation is deferred to the downstream Keccak constructor.\nfunction chooseLen(opts, outputLen) {\n opts = checkOpts({}, opts);\n return opts.dkLen === undefined ? outputLen : opts.dkLen;\n}\nconst abytesOrZero = (buf, title = '') => {\n if (buf === undefined)\n return EMPTY_BUFFER;\n abytes(buf, undefined, title);\n return buf;\n};\n// NOTE: second modulo is necessary since we don't need to add padding if the\n// current element takes a whole block.\n// Callers only pass the fixed positive Keccak rates here (`168` or `136`);\n// `block <= 0` is not validated locally.\nconst getPadding = (len, block) => new Uint8Array((block - (len % block)) % block);\n// bytepad(X1 || X2 || ..., rate): absorbs left_encode(rate), then each chunk, then zero-pads\n// to a rate boundary. Encode and pad inplace to avoid unneccesary memory copies/slices so we\n// don't need to zero them later. `rate` is the current cSHAKE/KMAC/TupleHash/ParallelHash\n// block length.\nfunction bytepadUpdate(h, ...chunks) {\n const hash = h;\n const blockLenBytes = leftEncode(hash.blockLen);\n hash.update(blockLenBytes);\n let totalLen = blockLenBytes.length;\n for (const chunk of chunks) {\n hash.update(chunk);\n totalLen += chunk.length;\n }\n hash.update(getPadding(totalLen, hash.blockLen));\n return hash;\n}\n// Personalization\nfunction cshakePers(h, opts = {}) {\n const hash = h;\n opts = checkOpts({}, opts);\n if (opts.personalization === undefined && opts.NISTfn === undefined)\n return hash;\n // bytepad(encode_string(N) || encode_string(S), rate)\n const fn = opts.NISTfn === undefined ? EMPTY_BUFFER : kdfInputToBytes(opts.NISTfn);\n const fnLen = leftEncode(_8n * BigInt(fn.length)); // length in bits\n const pers = abytesOrZero(opts.personalization, 'personalization');\n const persLen = leftEncode(_8n * BigInt(pers.length)); // length in bits\n if (!fn.length && !pers.length)\n return hash;\n // SP 800-185 cSHAKE appends `00` instead of SHAKE's `1111`; in this Keccak implementation\n // that changes the delimited suffix byte from `0x1f` to `0x04` once N or S is non-empty.\n hash.suffix = 0x04;\n return bytepadUpdate(hash, fnLen, fn, persLen, pers);\n}\nconst gencShake = (suffix, blockLen, outputLen) => createHasher((opts = {}) => cshakePers(new Keccak(blockLen, suffix, chooseLen(opts, outputLen), true), opts));\n/**\n * 128-bit NIST cSHAKE XOF.\n * @param msg - message bytes to hash\n * @param opts - Optional output, personalization, and NIST function-name\n * settings. When both `NISTfn` and `personalization` are empty,\n * SP 800-185 defines this as plain SHAKE128. Defaults to 16 output bytes\n * when `dkLen` is omitted. See {@link cShakeOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with cSHAKE128.\n * ```ts\n * cshake128(new Uint8Array([1, 2, 3]), { dkLen: 32 });\n * ```\n * @example\n * Hash a message with SP 800-185 domain separation.\n * ```ts\n * cshake128(new Uint8Array([1, 2, 3]), {\n * dkLen: 32,\n * NISTfn: 'Email Signature',\n * personalization: new Uint8Array([1, 2, 3]),\n * });\n * ```\n */\nexport const cshake128 = /* @__PURE__ */ gencShake(0x1f, 168, 16);\n/**\n * 256-bit NIST cSHAKE XOF.\n * @param msg - message bytes to hash\n * @param opts - Optional output, personalization, and NIST function-name\n * settings. When both `NISTfn` and `personalization` are empty,\n * SP 800-185 defines this as plain SHAKE256. Defaults to 32 output bytes\n * when `dkLen` is omitted. See {@link cShakeOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with cSHAKE256.\n * ```ts\n * cshake256(new Uint8Array([1, 2, 3]), { dkLen: 64 });\n * ```\n */\nexport const cshake256 = /* @__PURE__ */ gencShake(0x1f, 136, 32);\n/**\n * Internal KMAC class.\n * SP 800-185 \u00A78.4.1 still recommends keys at least as long as the target\n * security strength.\n */\nexport class _KMAC extends Keccak {\n constructor(blockLen, outputLen, enableXOF, key, opts = {}) {\n super(blockLen, 0x1f, outputLen, enableXOF);\n // Preload T = bytepad(encode_string(\"KMAC\") || encode_string(S), rate); later updates append\n // newX = bytepad(encode_string(K), rate) || X and `finish()` appends right_encode(L or 0).\n cshakePers(this, { NISTfn: 'KMAC', personalization: opts.personalization });\n abytes(key, undefined, 'key');\n // 1. newX = bytepad(encode_string(K), rate) || X || right_encode(L),\n // with `rate = this.blockLen`.\n bytepadUpdate(this, leftEncode(_8n * BigInt(key.length)), key);\n }\n finish() {\n // SP 800-185 uses right_encode(L) for fixed-length KMAC and right_encode(0) for KMACXOF.\n // outputLen in bits\n if (!this.finished)\n this.update(rightEncode(this.enableXOF ? 0 : _8n * BigInt(this.outputLen)));\n super.finish();\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since the key\n // is already in state and we don't know it.\n // Force \"to\" to be instance of KMAC instead of Sha3.\n if (!to) {\n to = Object.create(Object.getPrototypeOf(this), {});\n to.state = this.state.slice();\n to.blockLen = this.blockLen;\n to.state32 = u32(to.state);\n }\n return super._cloneInto(to);\n }\n clone() {\n return this._cloneInto();\n }\n}\nfunction genKmac(blockLen, outputLen, xof = false) {\n // One-shot XOF wrappers still finalize via `.digest()` because `_KMAC`\n // already bakes the requested output length into the state.\n const kmac = (key, message, opts) => kmac.create(key, opts).update(message).digest();\n kmac.create = (key, opts = {}) => new _KMAC(blockLen, chooseLen(opts, outputLen), xof, key, opts);\n // Same metadata + freeze as `createHasher()` wrappers, so duck-typed\n // consumers (e.g. `ahash()`) treat all wrappers alike.\n kmac.outputLen = outputLen;\n kmac.blockLen = blockLen;\n kmac.canXOF = xof;\n return Object.freeze(kmac);\n}\n/**\n * 128-bit Keccak MAC.\n * @param key - MAC key bytes\n * @param message - message bytes to authenticate\n * @param opts - Optional output and personalization settings. Defaults to\n * 16 output bytes when `dkLen` is omitted. See {@link cShakeOpts}.\n * @returns Authentication tag bytes.\n * @example\n * Authenticate a message with KMAC128.\n * ```ts\n * const key = new Uint8Array([1, 2, 3]);\n * const message = new Uint8Array([4, 5, 6]);\n * kmac128(key, message);\n * ```\n * @example\n * Authenticate a message with output options and an incremental state.\n * ```ts\n * const key = new Uint8Array([1, 2, 3]);\n * const message = new Uint8Array([4, 5, 6]);\n * const opts = { dkLen: 32, personalization: new Uint8Array([7, 8, 9]) };\n * const tag = kmac128(key, message, opts);\n * const out = new Uint8Array(32);\n * kmac128.create(key, { dkLen: 32 }).update(message).digestInto(out);\n * ```\n */\nexport const kmac128 = /* @__PURE__ */ genKmac(168, 16);\n/**\n * 256-bit Keccak MAC.\n * @param key - MAC key bytes\n * @param message - message bytes to authenticate\n * @param opts - Optional output and personalization settings. Defaults to\n * 32 output bytes when `dkLen` is omitted. See {@link cShakeOpts}.\n * @returns Authentication tag bytes.\n * @example\n * Authenticate a message with KMAC256.\n * ```ts\n * kmac256(new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]));\n * ```\n */\nexport const kmac256 = /* @__PURE__ */ genKmac(136, 32);\n/**\n * 128-bit Keccak-MAC XOF.\n * @param key - MAC key bytes\n * @param message - message bytes to authenticate\n * @param opts - Optional output and personalization settings. Defaults to\n * 16 output bytes when `dkLen` is omitted. See {@link cShakeOpts}.\n * @returns Authentication tag bytes.\n * @example\n * Authenticate a message with KMAC128 XOF output.\n * ```ts\n * kmac128xof(new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]), { dkLen: 32 });\n * ```\n */\nexport const kmac128xof = /* @__PURE__ */ genKmac(168, 16, true);\n/**\n * 256-bit Keccak-MAC XOF.\n * @param key - MAC key bytes\n * @param message - message bytes to authenticate\n * @param opts - Optional output and personalization settings. Defaults to\n * 32 output bytes when `dkLen` is omitted. See {@link cShakeOpts}.\n * @returns Authentication tag bytes.\n * @example\n * Authenticate a message with KMAC256 XOF output.\n * ```ts\n * kmac256xof(new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]), { dkLen: 64 });\n * ```\n */\nexport const kmac256xof = /* @__PURE__ */ genKmac(136, 32, true);\n/**\n * Internal TupleHash class for byte-array tuple elements.\n * This implementation relies on SP 800-185's byte-oriented encoding form\n * rather than arbitrary bit strings.\n */\nexport class _TupleHash extends Keccak {\n // Cheaper than a per-instance `this.update = ...` closure: switches the class-method\n // update from plain absorption (during the cSHAKE preload) to tuple-element encoding.\n tupleMode = false;\n constructor(blockLen, outputLen, enableXOF, opts = {}) {\n super(blockLen, 0x1f, outputLen, enableXOF);\n cshakePers(this, { NISTfn: 'TupleHash', personalization: opts.personalization });\n this.tupleMode = true;\n }\n update(data) {\n if (!this.tupleMode)\n return super.update(data);\n abytes(data);\n // SP 800-185 encodes each tuple element as\n // encode_string(X[i]) = left_encode(len(X[i])) || X[i].\n super.update(leftEncode(_8n * BigInt(data.length)));\n super.update(data);\n return this;\n }\n finish() {\n // SP 800-185 uses right_encode(L) for fixed-length TupleHash\n // and right_encode(0) for TupleHashXOF.\n if (!this.finished)\n // outputLen in bits\n super.update(rightEncode(this.enableXOF ? 0 : _8n * BigInt(this.outputLen)));\n super.finish();\n }\n _cloneInto(to) {\n to ||= new _TupleHash(this.blockLen, this.outputLen, this.enableXOF);\n to.tupleMode = this.tupleMode;\n return super._cloneInto(to);\n }\n clone() {\n return this._cloneInto();\n }\n}\nfunction genTuple(blockLen, outputLen, xof = false) {\n // One-shot XOF wrappers still use `.digest()` because `_TupleHash` stores\n // the requested output length in the state itself.\n const tuple = (messages, opts) => {\n const h = tuple.create(opts);\n if (!Array.isArray(messages))\n throw new Error('expected array of messages');\n for (const msg of messages)\n h.update(msg);\n return h.digest();\n };\n tuple.create = (opts = {}) => new _TupleHash(blockLen, chooseLen(opts, outputLen), xof, opts);\n // Same metadata + freeze as `createHasher()` wrappers, so duck-typed\n // consumers (e.g. `ahash()`) treat all wrappers alike.\n tuple.outputLen = outputLen;\n tuple.blockLen = blockLen;\n tuple.canXOF = xof;\n return Object.freeze(tuple);\n}\n/**\n * 128-bit TupleHASH. `tuple(['ab', 'cd']) != tuple(['a', 'bcd'])`.\n * @param messages - ordered byte-array tuple\n * @param opts - Optional output and personalization settings. Defaults to\n * 16 output bytes when `dkLen` is omitted. See {@link cShakeOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a tuple of byte arrays with TupleHash128.\n * ```ts\n * tuplehash128([new Uint8Array([1]), new Uint8Array([2])]);\n * ```\n */\nexport const tuplehash128 = /* @__PURE__ */ genTuple(168, 16);\n/**\n * 256-bit TupleHASH. `tuple(['ab', 'cd']) != tuple(['a', 'bcd'])`.\n * @param messages - ordered byte-array tuple\n * @param opts - Optional output and personalization settings. Defaults to\n * 32 output bytes when `dkLen` is omitted. See {@link cShakeOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a tuple of byte arrays with TupleHash256.\n * ```ts\n * tuplehash256([new Uint8Array([1]), new Uint8Array([2])]);\n * ```\n */\nexport const tuplehash256 = /* @__PURE__ */ genTuple(136, 32);\n/**\n * 128-bit TupleHASH XOF.\n * @param messages - ordered byte-array tuple\n * @param opts - Optional output and personalization settings. Defaults to\n * 16 output bytes when `dkLen` is omitted. See {@link cShakeOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a tuple of byte arrays with TupleHash128 XOF output.\n * ```ts\n * tuplehash128xof([new Uint8Array([1]), new Uint8Array([2])], { dkLen: 32 });\n * ```\n */\nexport const tuplehash128xof = /* @__PURE__ */ genTuple(168, 16, true);\n/**\n * 256-bit TupleHASH XOF.\n * @param messages - ordered byte-array tuple\n * @param opts - Optional output and personalization settings. Defaults to\n * 32 output bytes when `dkLen` is omitted. See {@link cShakeOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a tuple of byte arrays with TupleHash256 XOF output.\n * ```ts\n * tuplehash256xof([new Uint8Array([1]), new Uint8Array([2])], { dkLen: 64 });\n * ```\n */\nexport const tuplehash256xof = /* @__PURE__ */ genTuple(136, 32, true);\n/** Internal Parallel Keccak Hash class. */\nexport class _ParallelHash extends Keccak {\n leafHash;\n leafCons;\n // Pristine leaf instance cloned into `leafHash` per chunk: with the default\n // 8-byte chunks, constructing a fresh leaf per chunk costs ~15% (measured).\n leafTemplate;\n // Reused chaining-value buffer for leaf digests.\n leafCV;\n chunkPos = 0; // Position of current block in chunk\n chunksDone = 0; // How many chunks we already have\n chunkLen;\n // Cheaper than a per-instance `this.update = ...` closure: switches the class-method\n // update from plain absorption (during the cSHAKE preload) to leaf chunking.\n leafMode = false;\n constructor(blockLen, outputLen, leafCons, enableXOF, opts = {}) {\n super(blockLen, 0x1f, outputLen, enableXOF);\n cshakePers(this, { NISTfn: 'ParallelHash', personalization: opts.personalization });\n this.leafCons = leafCons;\n let { blockLen: B = 8 } = opts;\n anumber(B);\n // blockLen=0 makes take=0 in update(), so pos never advances and the hash hangs.\n if (B < 1)\n throw new Error('\"blockLen\" must be >= 1, got ' + B);\n this.chunkLen = B;\n // SP 800-185 initializes z = left_encode(B); each completed chunk appends\n // one fixed-size cSHAKE leaf digest before finish() adds right_encode(n)\n // and right_encode(L or 0).\n super.update(leftEncode(B));\n this.leafMode = true;\n }\n flushLeaf() {\n const cv = (this.leafCV ||= new Uint8Array(this.leafHash.outputLen));\n this.leafHash.digestInto(cv);\n super.update(cv);\n this.chunksDone++;\n }\n update(data) {\n if (!this.leafMode)\n return super.update(data);\n aexists(this);\n abytes(data);\n const { chunkLen, leafCons } = this;\n for (let pos = 0, len = data.length; pos < len;) {\n if (this.chunkPos == chunkLen || !this.leafHash) {\n if (this.leafHash)\n this.flushLeaf();\n // Clone a pristine template instead of re-running the constructor;\n // resurrects the just-digested leaf allocation in place.\n this.leafTemplate ||= leafCons();\n this.leafHash = this.leafTemplate._cloneInto(this.leafHash);\n this.chunkPos = 0;\n }\n const take = Math.min(chunkLen - this.chunkPos, len - pos);\n this.leafHash.update(data.subarray(pos, pos + take));\n this.chunkPos += take;\n pos += take;\n }\n return this;\n }\n finish() {\n if (this.finished)\n return;\n if (this.leafHash)\n this.flushLeaf();\n // SP 800-185 finishes ParallelHash as\n // z || right_encode(n) || right_encode(L); XOF mode replaces\n // right_encode(L) with right_encode(0).\n super.update(rightEncode(this.chunksDone));\n // outputLen in bits\n super.update(rightEncode(this.enableXOF ? 0 : _8n * BigInt(this.outputLen)));\n super.finish();\n }\n // Overriding hides Keccak's flat implementation, which would otherwise be inherited\n // and silently miss the tree state (leaf hash, chunk counters).\n _cloneInto(to) {\n to ||= new _ParallelHash(this.blockLen, this.outputLen, this.leafCons, this.enableXOF);\n to.leafCons = this.leafCons;\n // Clone the cached template/CV as regular state: this also overwrites\n // stale wrong-variant values on reused destinations.\n if (this.leafTemplate)\n to.leafTemplate = this.leafTemplate._cloneInto(to.leafTemplate);\n else if (to.leafTemplate) {\n to.leafTemplate.destroy();\n to.leafTemplate = undefined;\n }\n if (this.leafCV) {\n if (to.leafCV && to.leafCV.length === this.leafCV.length)\n to.leafCV.set(this.leafCV);\n else\n to.leafCV = this.leafCV.slice();\n }\n else\n to.leafCV = undefined;\n // Reused destinations can carry a stale partial leaf\n // when the source is still on the root sponge.\n if (this.leafHash)\n to.leafHash = this.leafHash._cloneInto(to.leafHash);\n else if (to.leafHash) {\n to.leafHash.destroy();\n to.leafHash = undefined;\n }\n to.chunkPos = this.chunkPos;\n to.chunkLen = this.chunkLen;\n to.chunksDone = this.chunksDone;\n to.leafMode = this.leafMode;\n return super._cloneInto(to);\n }\n destroy() {\n super.destroy.call(this);\n if (this.leafHash)\n this.leafHash.destroy();\n if (this.leafTemplate)\n this.leafTemplate.destroy();\n if (this.leafCV)\n clean(this.leafCV);\n }\n clone() {\n return this._cloneInto();\n }\n}\nfunction genPrl(blockLen, outputLen, leaf, xof = false) {\n const parallel = (message, opts) => parallel.create(opts).update(message).digest();\n parallel.create = (opts = {}) => new _ParallelHash(blockLen, chooseLen(opts, outputLen), \n // SP 800-185 fixes leaf digests at 256 bits for ParallelHash128 and\n // 512 bits for ParallelHash256; only the final cSHAKE output uses the\n // caller-selected dkLen.\n () => leaf.create({ dkLen: 2 * outputLen }), xof, opts);\n // Same metadata + freeze as `createHasher()` wrappers.\n parallel.outputLen = outputLen;\n parallel.blockLen = blockLen;\n parallel.canXOF = xof;\n return Object.freeze(parallel);\n}\n/**\n * 128-bit ParallelHash. In JS, it is not parallel.\n * @param msg - message bytes to hash\n * @param opts - Optional output, personalization, and chunking settings.\n * Defaults to 16 output bytes when `dkLen` is omitted.\n * See {@link ParallelOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with ParallelHash128.\n * ```ts\n * parallelhash128(new Uint8Array([1, 2, 3]));\n * ```\n * @example\n * Hash a message with chunking and personalization settings.\n * ```ts\n * parallelhash128(new Uint8Array([1, 2, 3]), {\n * blockLen: 8,\n * dkLen: 32,\n * personalization: new Uint8Array([4, 5, 6]),\n * });\n * ```\n */\nexport const parallelhash128 = /* @__PURE__ */ genPrl(168, 16, cshake128);\n/**\n * 256-bit ParallelHash. In JS, it is not parallel.\n * @param msg - message bytes to hash\n * @param opts - Optional output, personalization, and chunking settings.\n * Defaults to 32 output bytes when `dkLen` is omitted.\n * See {@link ParallelOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with ParallelHash256.\n * ```ts\n * parallelhash256(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const parallelhash256 = /* @__PURE__ */ genPrl(136, 32, cshake256);\n/**\n * 128-bit ParallelHash XOF. In JS, it is not parallel.\n * @param msg - message bytes to hash\n * @param opts - Optional output, personalization, and chunking settings.\n * Defaults to 16 output bytes when `dkLen` is omitted.\n * See {@link ParallelOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with ParallelHash128 XOF output.\n * ```ts\n * parallelhash128xof(new Uint8Array([1, 2, 3]), { dkLen: 32 });\n * ```\n */\nexport const parallelhash128xof = /* @__PURE__ */ genPrl(168, 16, cshake128, true);\n/**\n * 256-bit ParallelHash XOF. In JS, it is not parallel.\n * @param msg - message bytes to hash\n * @param opts - Optional output, personalization, and chunking settings.\n * Defaults to 32 output bytes when `dkLen` is omitted.\n * See {@link ParallelOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with ParallelHash256 XOF output.\n * ```ts\n * parallelhash256xof(new Uint8Array([1, 2, 3]), { dkLen: 64 });\n * ```\n */\nexport const parallelhash256xof = /* @__PURE__ */ genPrl(136, 32, cshake256, true);\nconst genTurbo = (blockLen, outputLen) => createHasher((opts = {}) => {\n opts = checkOpts({}, opts);\n const D = opts.D === undefined ? 0x1f : opts.D;\n // RFC 9861 \u00A72.1 fixes the default `D = 0x1f`; \u00A72.2 defines the 12-round\n // TurboSHAKE family selected here.\n if (!Number.isSafeInteger(D) || D < 0x01 || D > 0x7f)\n throw new Error('\"D\" (domain separation byte) must be 0x01..0x7f, got: ' + D);\n const dkLen = chooseLen(opts, outputLen);\n // RFC 9861 \u00A7\u00A72.1-2.2 define output length L as a positive integer.\n if (dkLen < 1)\n throw new Error('\"dkLen\" must be >= 1');\n return new Keccak(blockLen, D, dkLen, true, 12);\n});\n/**\n * TurboSHAKE 128-bit: reduced 12-round keccak.\n * Should've been a simple \"shake with 12 rounds\", but we got a whole new\n * spec about Turbo SHAKE Pro MAX.\n * @param msg - message bytes to hash\n * @param opts - Optional output-length and domain-separation settings.\n * RFC 9861 \u00A72.1 defaults `D` to `0x1f`. Defaults to 32 output bytes when\n * `dkLen` is omitted. See {@link TurboshakeOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with TurboSHAKE128.\n * ```ts\n * turboshake128(new Uint8Array([1, 2, 3]), { dkLen: 32 });\n * ```\n * @example\n * Hash a message with an explicit domain-separation byte.\n * ```ts\n * turboshake128(new Uint8Array([1, 2, 3]), { dkLen: 32, D: 0x1f });\n * ```\n */\nexport const turboshake128 = /* @__PURE__ */ genTurbo(168, 32);\n/**\n * TurboSHAKE 256-bit: reduced 12-round keccak.\n * @param msg - message bytes to hash\n * @param opts - Optional output-length and domain-separation settings.\n * RFC 9861 \u00A72.1 defaults `D` to `0x1f`. Defaults to 64 output bytes when\n * `dkLen` is omitted. See {@link TurboshakeOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with TurboSHAKE256.\n * ```ts\n * turboshake256(new Uint8Array([1, 2, 3]), { dkLen: 64 });\n * ```\n */\nexport const turboshake256 = /* @__PURE__ */ genTurbo(136, 64);\n// Same as NIST rightEncode, but returns `[0]` for the zero string.\n// Callers still need to keep `x < 256^255` per RFC 9861 \u00A73.3.\nfunction rightEncodeK12(n) {\n n = BigInt(n);\n const res = [];\n for (; n > 0; n >>= _8n)\n res.unshift(Number(n & _ffn));\n res.push(res.length);\n return Uint8Array.from(res);\n}\nconst EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();\n// RFC 9861 \u00A73.2 FinalNode prefix for S_0 and the CV-list terminator.\nconst K12_TREE = /* @__PURE__ */ Uint8Array.from([3, 0, 0, 0, 0, 0, 0, 0]);\nconst K12_FINAL = /* @__PURE__ */ Uint8Array.from([0xff, 0xff]);\n/** Internal K12 hash class. */\nexport class _KangarooTwelve extends Keccak {\n chunkLen = 8192;\n leafHash;\n // Pristine leaf instance cloned into `leafHash` per chunk, same pattern as _ParallelHash:\n // streaming reuses two leaf allocations total instead of one per 8KB chunk.\n leafTemplate;\n // Reused chaining-value buffer for leaf digests.\n leafCV;\n leafLen;\n personalization;\n chunkPos = 0; // Position of current block in chunk\n chunksDone = 0; // How many chunks we already have\n constructor(blockLen, leafLen, outputLen, rounds, opts) {\n super(blockLen, 0x07, outputLen, true, rounds);\n opts = checkOpts({}, opts);\n // RFC 9861 \u00A73 defines output length L as a positive integer.\n if (outputLen < 1)\n throw new Error('\"dkLen\" must be >= 1');\n this.leafLen = leafLen;\n this.personalization =\n opts.personalization === undefined\n ? EMPTY_BUFFER\n : copyBytes(abytes(opts.personalization, undefined, 'personalization'));\n }\n update(data) {\n aexists(this);\n abytes(data);\n const { chunkLen, blockLen, leafLen, rounds } = this;\n for (let pos = 0, len = data.length; pos < len;) {\n if (this.chunkPos == chunkLen) {\n if (this.leafHash)\n this.flushLeaf();\n else {\n // RFC 9861 \u00A73.2 switches from SingleNode (`07`) to FinalNode (`06`)\n // once S exceeds 8192 bytes and prefixes S_0 with\n // `03 00 00 00 00 00 00 00`.\n this.suffix = 0x06; // Its safe to change suffix here since its used only in digest()\n super.update(K12_TREE);\n }\n // Secondary chunks S_1..S_(n-1) become fixed-length\n // CV_i = TurboSHAKE*(S_i, `0B`, 32|64) chaining values.\n // Clone a pristine template instead of re-running the constructor;\n // resurrects the just-digested leaf allocation in place.\n this.leafTemplate ??= new Keccak(blockLen, 0x0b, leafLen, false, rounds);\n this.leafHash = this.leafTemplate._cloneInto(this.leafHash);\n this.chunksDone++;\n this.chunkPos = 0;\n }\n const take = Math.min(chunkLen - this.chunkPos, len - pos);\n const chunk = data.subarray(pos, pos + take);\n if (this.leafHash)\n this.leafHash.update(chunk);\n else\n super.update(chunk);\n this.chunkPos += take;\n pos += take;\n }\n return this;\n }\n flushLeaf() {\n const leafHash = this.leafHash;\n const cv = (this.leafCV ||= new Uint8Array(leafHash.outputLen));\n leafHash.digestInto(cv);\n super.update(cv);\n }\n finish() {\n if (this.finished)\n return;\n const { personalization } = this;\n // RFC 9861 \u00A73.2 forms S = M || C || length_encode(|C|) before any tree hashing logic.\n this.update(personalization).update(rightEncodeK12(personalization.length));\n // Leaf hash\n if (this.leafHash) {\n // Multi-chunk K12 appends\n // CV_1..CV_(n-1) || length_encode(n-1) || `FF FF`\n // before the final TurboSHAKE call.\n this.flushLeaf();\n super.update(rightEncodeK12(this.chunksDone));\n super.update(K12_FINAL);\n }\n super.finish.call(this);\n }\n destroy() {\n super.destroy.call(this);\n if (this.leafHash)\n this.leafHash.destroy();\n if (this.leafTemplate)\n this.leafTemplate.destroy();\n if (this.leafCV)\n clean(this.leafCV);\n // Personalization is copied on create/clone, so destroy can wipe it\n // without touching caller input.\n if (this.personalization !== EMPTY_BUFFER)\n clean(this.personalization);\n this.personalization = EMPTY_BUFFER;\n }\n // Overriding hides Keccak's flat implementation, which would otherwise be inherited\n // and silently miss the tree state (leaf hash, chunk counters).\n _cloneInto(to) {\n const { blockLen, leafLen, leafHash, outputLen, personalization, rounds } = this;\n const fresh = to === undefined;\n // Personalization is absorbed only during finish(), so clones need the same pending value.\n to ||= new _KangarooTwelve(blockLen, leafLen, outputLen, rounds, {\n personalization: personalization === EMPTY_BUFFER ? undefined : personalization,\n });\n super._cloneInto(to);\n // Reused destinations can carry a stale leaf from an older multi-chunk state.\n if (leafHash)\n to.leafHash = leafHash._cloneInto(to.leafHash);\n else if (to.leafHash) {\n to.leafHash.destroy();\n to.leafHash = undefined;\n }\n // Cached leaf state is part of a reusable clone: stale destroyed or wrong-variant values\n // otherwise fail or change the digest only after the replacement crosses a tree boundary.\n if (this.leafTemplate)\n to.leafTemplate = this.leafTemplate._cloneInto(to.leafTemplate);\n else if (to.leafTemplate) {\n to.leafTemplate.destroy();\n to.leafTemplate = undefined;\n }\n if (this.leafCV) {\n if (to.leafCV && to.leafCV.length === this.leafCV.length)\n to.leafCV.set(this.leafCV);\n else\n to.leafCV = this.leafCV.slice();\n }\n else\n to.leafCV = undefined;\n // Snapshot the pending personalization without aliasing source or caller-owned input.\n if (!fresh) {\n const old = to.personalization;\n if (personalization === EMPTY_BUFFER) {\n if (old !== EMPTY_BUFFER)\n clean(old);\n to.personalization = EMPTY_BUFFER;\n }\n else if (old === EMPTY_BUFFER || old.length !== personalization.length) {\n const copy = copyBytes(personalization);\n if (old !== EMPTY_BUFFER)\n clean(old);\n to.personalization = copy;\n }\n else {\n // Reuse compatible private storage so live-destination clones neither allocate\n // nor abandon user data.\n old.set(personalization);\n }\n }\n to.leafLen = this.leafLen;\n to.chunkPos = this.chunkPos;\n to.chunksDone = this.chunksDone;\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * 128-bit KangarooTwelve (k12): reduced 12-round keccak.\n * @param msg - message bytes to hash\n * @param opts - Optional output and personalization settings. Defaults to\n * 32 output bytes when `dkLen` is omitted. See {@link KangarooOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with KangarooTwelve-128.\n * ```ts\n * kt128(new Uint8Array([1, 2, 3]));\n * ```\n * @example\n * Hash a message with KangarooTwelve-128 personalization.\n * ```ts\n * kt128(new Uint8Array([1, 2, 3]), {\n * dkLen: 64,\n * personalization: new Uint8Array([4, 5, 6]),\n * });\n * ```\n */\nexport const kt128 = /* @__PURE__ */ createHasher((opts = {}) => new _KangarooTwelve(168, 32, chooseLen(opts, 32), 12, opts));\n/**\n * 256-bit KangarooTwelve (k12): reduced 12-round keccak.\n * @param msg - message bytes to hash\n * @param opts - Optional output and personalization settings. Defaults to\n * 64 output bytes when `dkLen` is omitted. See {@link KangarooOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with KangarooTwelve-256.\n * ```ts\n * kt256(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const kt256 = /* @__PURE__ */ createHasher((opts = {}) => new _KangarooTwelve(136, 64, chooseLen(opts, 64), 12, opts));\nconst genHopMAC = (hash) => {\n const kt = hash;\n return ((key, message, personalization, dkLen) => kt(key, { personalization: kt(message, { personalization }), dkLen }));\n};\n/**\n * 128-bit KangarooTwelve-based MAC.\n *\n * These untested (there is no test vectors or implementation available). Use at your own risk.\n * HopMAC128(Key, M, C, L) = KT128(Key, KT128(M, C, 32), L)\n * HopMAC256(Key, M, C, L) = KT256(Key, KT256(M, C, 64), L)\n * The inner KangarooTwelve call always uses a fixed 32-byte digest here,\n * regardless of the outer `dkLen`.\n * @param key - MAC key bytes\n * @param message - message bytes to authenticate\n * @param personalization - personalization bytes mixed into the inner hash\n * @param dkLen - optional output length in bytes\n * @returns Authentication tag bytes.\n * @example\n * Authenticate a message with HopMAC128.\n * ```ts\n * HopMAC128(new Uint8Array([1]), new Uint8Array([2]), new Uint8Array([3]), 32);\n * ```\n */\nexport const HopMAC128 = /* @__PURE__ */ genHopMAC(kt128);\n/**\n * 256-bit KangarooTwelve-based MAC.\n * Like `HopMAC128`, there are no test vectors or known independent\n * implementations available for cross-checking.\n * @param key - MAC key bytes\n * @param message - message bytes to authenticate\n * @param personalization - personalization bytes mixed into the inner hash\n * @param dkLen - optional output length in bytes. The inner KangarooTwelve\n * call still uses a fixed 64-byte digest here, regardless of the outer\n * `dkLen`.\n * @returns Authentication tag bytes.\n * @example\n * Authenticate a message with HopMAC256.\n * ```ts\n * HopMAC256(new Uint8Array([1]), new Uint8Array([2]), new Uint8Array([3]), 64);\n * ```\n */\nexport const HopMAC256 = /* @__PURE__ */ genHopMAC(kt256);\n/**\n * More at\n * {@link https://github.com/XKCP/XKCP/tree/master/lib/high/Keccak/PRG}.\n * Accepted capacities must keep `rho = 1598 - capacity` byte-aligned, and\n * `.clean()` later also requires `rate > 801`.\n */\nexport class _KeccakPRG extends Keccak {\n rate;\n entropyAdded = false;\n constructor(capacity) {\n anumber(capacity);\n const rate = 1600 - capacity;\n const rho = rate - 2;\n // Rho must be full bytes\n if (capacity < 0 || capacity > 1600 - 10 || rho % 8)\n throw new Error('invalid capacity');\n // blockLen = rho in bytes\n super(rho / 8, 0, 0, true);\n this.rate = rate;\n this.posOut = Math.floor((rate + 7) / 8);\n }\n keccak() {\n // Duplex padding\n this.state[this.pos] ^= 0x01;\n this.state[this.blockLen] ^= 0x02; // Rho is full bytes\n super.keccak();\n this.pos = 0;\n this.posOut = 0;\n }\n update(data) {\n super.update(data);\n this.posOut = this.blockLen;\n return this;\n }\n finish() { }\n digestInto(_out) {\n throw new Error('digest is not allowed, use .randomBytes() instead');\n }\n addEntropy(seed) {\n // Check lifecycle before asking the system RNG for entropy that cannot be used.\n aexists(this);\n if (seed !== undefined) {\n abytes(seed, undefined, 'seed');\n if (seed.length === 0)\n throw new Error('\"seed\" must not be empty');\n }\n const generated = seed === undefined;\n const entropy = generated ? randomBytes() : seed;\n try {\n this.update(entropy);\n this.entropyAdded = true;\n }\n finally {\n // This temporary is library-owned; caller-provided entropy remains caller-owned.\n if (generated)\n clean(entropy);\n }\n }\n xofInto(out) {\n aexists(this, false);\n if (!this.entropyAdded)\n throw new Error('addEntropy() must be called before randomBytes()');\n return super.xofInto(out);\n }\n randomBytes(length) {\n return this.xof(length);\n }\n clean() {\n // clean() mutates live sponge state just like randomBytes(),\n // so destroyed instances must reject it.\n aexists(this, false);\n if (this.rate < 1600 / 2 + 1)\n throw new Error('rate is too low to use .forget()');\n this.keccak();\n for (let i = 0; i < this.blockLen; i++)\n this.state[i] = 0;\n this.pos = this.blockLen;\n this.keccak();\n this.posOut = this.blockLen;\n }\n // Keccak cloning includes `posOut`, which preserves the PRG's current output phase.\n _cloneInto(to) {\n const { rate } = this;\n to ||= new _KeccakPRG(1600 - rate);\n super._cloneInto(to);\n to.rate = rate;\n to.entropyAdded = this.entropyAdded;\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * KeccakPRG: pseudo-random generator based on Keccak.\n * See {@link https://keccak.team/files/CSF-0.1.pdf}.\n * Fresh instances reject output until `.addEntropy()` has been called. With no\n * argument, `addEntropy()` obtains 32 bytes from the platform CSPRNG; callers\n * may instead supply their own non-empty entropy bytes.\n * @param capacity - sponge capacity in bits. Accepted values are those that\n * keep `rho = 1598 - capacity` byte-aligned; the default `254` is chosen\n * because it satisfies that duplex layout while leaving a wide byte-aligned\n * rate.\n * @returns PRG instance backed by a Keccak sponge.\n * @example\n * Create a Keccak-based pseudorandom generator and read bytes from it.\n * ```ts\n * import { keccakprg } from '@noble/hashes/sha3-addons.js';\n *\n * const prg = keccakprg(254);\n * prg.addEntropy();\n * prg.randomBytes(8);\n * ```\n */\nexport const keccakprg = (capacity = 254) => new _KeccakPRG(capacity);\n", "/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, aoutput, clean, } from \"./utils.js\";\n/**\n * Internal class for HMAC.\n * Accepts any byte key, although RFC 2104 \u00A73 recommends keys at least\n * `HashLen` bytes long.\n */\nexport class _HMAC {\n oHash;\n iHash;\n blockLen;\n outputLen;\n canXOF = false;\n finished = false;\n destroyed = false;\n constructor(hash, key) {\n ahash(hash);\n abytes(key, undefined, 'key');\n this.iHash = hash.create();\n if (typeof this.iHash.update !== 'function')\n throw new Error('expected Hash instance');\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++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of the first block) of the outer hash here,\n // we can re-use it between multiple calls via clone.\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n clean(pad);\n }\n update(buf) {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const buf = out.subarray(0, this.outputLen);\n // Reuse the first outputLen bytes for the inner digest; the outer hash consumes them before\n // overwriting that same prefix with the final tag, leaving any oversized tail untouched.\n this.iHash.digestInto(buf);\n this.oHash.update(buf);\n this.oHash.digestInto(buf);\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) {\n // Create new instance without calling constructor since the key\n // is already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen, canXOF } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.canXOF = canXOF;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\nexport const hmac = /* @__PURE__ */ (() => {\n const hmac_ = ((hash, key, message) => new _HMAC(hash, key).update(message).digest());\n hmac_.create = (hash, key) => new _HMAC(hash, key);\n return hmac_;\n})();\n", "/**\n * HKDF (RFC 5869): extract + expand in one step.\n * See {@link https://soatok.blog/2021/11/17/understanding-hkdf/}.\n * @module\n */\nimport { hmac } from \"./hmac.js\";\nimport { abytes, ahash, anumber, clean } from \"./utils.js\";\n/**\n * HKDF-extract from spec. Less important part. `HKDF-Extract(IKM, salt) -> PRK`\n * Arguments position differs from spec (IKM is first one, since it is not optional)\n * Local validation only checks `hash`; `ikm` / `salt` byte validation is delegated to `hmac()`.\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n * @returns Pseudorandom key derived from input keying material.\n * @example\n * Run the HKDF extract step.\n * ```ts\n * import { extract } from '@noble/hashes/hkdf.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * extract(sha256, new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]));\n * ```\n */\nexport function extract(hash, ikm, salt) {\n ahash(hash);\n // NOTE: some libraries treat zero-length array as 'not provided';\n // we don't, since we have undefined as 'not provided'\n // https://github.com/RustCrypto/KDFs/issues/15\n if (salt === undefined)\n salt = new Uint8Array(hash.outputLen);\n return hmac(hash, salt, ikm);\n}\n// Shared mutable scratch byte for the RFC 5869 block counter `N`.\n// Safe to reuse because `expand()` is synchronous and resets it with `clean(...)` before returning.\nconst HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0);\n// Shared RFC 5869 empty string for both `info === undefined` and the first-block `T(0)` input.\nconst EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();\n/**\n * HKDF-expand from the spec. The most important part. `HKDF-Expand(PRK, info, L) -> OKM`\n * @param hash - hash function that would be used (e.g. sha256)\n * @param prk - a pseudorandom key of at least HashLen octets\n * (usually, the output from the extract step)\n * @param info - optional context and application specific information (can be a zero-length string)\n * @param length - length of output keying material in bytes.\n * RFC 5869 \u00A72.3 allows `0..255*HashLen`, so `0` returns an empty OKM.\n * @param _recycled - Internal destroyed extract hashes owned by the combined `hkdf()` call.\n * @returns Output keying material with the requested length.\n * @throws If the requested output length exceeds the HKDF limit\n * for the selected hash. {@link Error}\n * @example\n * Run the HKDF expand step.\n * ```ts\n * import { expand } from '@noble/hashes/hkdf.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * expand(sha256, new Uint8Array(32), new Uint8Array([1, 2, 3]), 16);\n * ```\n */\nexport function expand(hash, prk, info, length = 32, _recycled) {\n ahash(hash);\n anumber(length, 'length');\n abytes(prk, undefined, 'prk');\n const olen = hash.outputLen;\n // RFC 5869 \u00A72.3: PRK is \"a pseudorandom key of at least HashLen octets\".\n if (prk.length < olen)\n throw new Error('\"prk\" must be at least HashLen octets');\n // RFC 5869 \u00A72.3 only bounds `L` by `<= 255*HashLen`; `L=0` is valid and yields empty OKM.\n if (length > 255 * olen)\n throw new Error('Length must be <= 255*HashLen');\n const blocks = Math.ceil(length / olen);\n if (info === undefined)\n info = EMPTY_BUFFER;\n else\n abytes(info, undefined, 'info');\n if (!blocks) {\n if (_recycled)\n clean(prk); // Full hkdf() owns this intermediate PRK.\n return new Uint8Array();\n }\n // first L(ength) octets of T\n // The private PRK can become both T and a one-block result after HMAC consumes the key.\n const okm = _recycled && blocks === 1 ? prk : new Uint8Array(blocks * olen);\n const { iHash, oHash } = hmac.create(hash, prk);\n // Driving them directly also skips `_HMAC.digestInto`'s per-digest destroy.\n const T = _recycled ? prk : new Uint8Array(olen);\n // Full hkdf() donates one destroyed extract hash; standalone creates one alternating worker.\n const worker = blocks > 1 ? _recycled?.iHash || hash.create() : undefined;\n for (let counter = 0; counter < blocks - 1; counter++) {\n HKDF_COUNTER[0] = counter + 1;\n const iWork = iHash._cloneInto(worker);\n // T(0) = empty string (zero length)\n // T(N) = HMAC-Hash(PRK, T(N-1) | info | N)\n if (counter)\n iWork.update(T);\n iWork.update(info).update(HKDF_COUNTER).digestInto(T);\n oHash._cloneInto(worker).update(T).digestInto(T);\n okm.set(T, olen * counter);\n }\n // Midstates are key-equivalent: they allow computing HMAC(prk, ...) for any message.\n HKDF_COUNTER[0] = blocks; // Final block consumes them; retain worker for cleanup.\n if (blocks > 1)\n iHash.update(T);\n iHash.update(info).update(HKDF_COUNTER).digestInto(T);\n oHash.update(T).digestInto(T);\n okm.set(T, olen * (blocks - 1));\n iHash.destroy(); // Raw digests may leave key-derived base/worker state; wipe all explicitly.\n oHash.destroy();\n worker?.destroy();\n if (T !== okm)\n clean(T); // Wipe private T/PRK; standalone preserves caller-owned PRK.\n clean(HKDF_COUNTER);\n // Exact fit: return without the extra copy.\n if (length === okm.length)\n return okm;\n // Copy the requested prefix, then wipe the full buffer: its tail holds\n // up to HashLen-1 bytes of derived key material past `length`.\n const res = okm.slice(0, length);\n clean(okm);\n return res;\n}\n/**\n * HKDF (RFC 5869): derive keys from an initial input.\n * Combines hkdf_extract + hkdf_expand in one step\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n * @param info - optional context and application specific information bytes\n * @param length - length of output keying material in bytes.\n * RFC 5869 \u00A72.3 allows `0..255*HashLen`, so `0` returns an empty OKM.\n * @returns Output keying material derived from the input key.\n * @throws If the requested output length exceeds the HKDF limit\n * for the selected hash. {@link Error}\n * @example\n * HKDF (RFC 5869): derive keys from an initial input.\n * ```ts\n * import { hkdf } from '@noble/hashes/hkdf.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { randomBytes, utf8ToBytes } from '@noble/hashes/utils.js';\n * const inputKey = randomBytes(32);\n * const salt = randomBytes(32);\n * const info = utf8ToBytes('application-key');\n * const okm = hkdf(sha256, inputKey, salt, info, 32);\n * ```\n */\nexport const hkdf = (hash, ikm, salt, info, length) => {\n ahash(hash);\n if (salt === undefined)\n salt = new Uint8Array(hash.outputLen);\n const HMAC = hmac.create(hash, salt).update(ikm);\n // The intermediate PRK is secret key material; wipe it instead of\n // leaving it for GC.\n return expand(hash, HMAC.digest(), info, length, HMAC); // expand() owns and consumes it.\n};\n", "/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { setU64FromNum } from \"./_u64.js\";\nimport { abytes, aexists, aoutput, createView } from \"./utils.js\";\n/**\n * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.\n * Returns bits from `b` when `a` is set, otherwise from `c`.\n * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never\n * set the same bit.\n * @param a - selector word\n * @param b - word chosen when selector bit is set\n * @param c - word chosen when selector bit is clear\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit choice primitive.\n * ```ts\n * Chi(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/**\n * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.\n * Returns bits shared by at least two inputs.\n * @param a - first input word\n * @param b - second input word\n * @param c - third input word\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit majority primitive.\n * ```ts\n * Maj(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Maj(a, b, c) {\n return (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 * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit\n * strings with partial-byte tails.\n * @param blockLen - internal block size in bytes\n * @param outputLen - digest size in bytes\n * @param padOffset - trailing length field size in bytes\n * @param isLE - whether length and state words are encoded in little-endian\n * @example\n * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.\n * ```ts\n * import { _SHA1 } from '@noble/hashes/legacy.js';\n * const hash = new _SHA1();\n * hash.update(new Uint8Array([97, 98, 99]));\n * hash.digest();\n * ```\n */\nexport class HashMD {\n blockLen;\n outputLen;\n canXOF = false;\n padOffset;\n isLE;\n // For partial updates less than block size\n buffer;\n view;\n finished = false;\n length = 0;\n pos = 0;\n destroyed = false;\n constructor(blockLen, outputLen, padOffset, isLE) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n let processed = false;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path only when there is no buffered partial block: `take === blockLen` implies\n // `this.pos === 0`, so we can process full blocks directly from the input view.\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n processed = true;\n continue;\n }\n // When the whole input is buffered in one go (common for short messages), passing `data`\n // directly avoids allocating a subarray view.\n buffer.set(pos === 0 && take === len ? data : 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 processed = true;\n }\n }\n this.length += data.length;\n // Shared schedule buffers only pick up input-derived words inside process(); if everything\n // was buffered without processing, there is nothing to zero.\n if (processed)\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(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, then zero-pad the rest of the block\n buffer[pos++] = 0b10000000;\n buffer.fill(0, pos);\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 buffer.fill(0);\n }\n // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from\n // the padding fill above, and JS will overflow before user input can make that half non-zero.\n // So we only need to write the low 64 bits here (`length * 8` only scales the exponent of an\n // integer below 2**53, so the split inside the helper stays exact).\n setU64FromNum(view, blockLen - 8, this.length * 8, isLE);\n this.process(view, 0);\n // The final block above is processed outside update(), so the shared message-schedule\n // buffers (e.g. SHA256_W) would otherwise retain input-derived words after digest().\n this.roundClean();\n // digest() passes our own `buffer` as `out`; reuse its cached view instead of allocating one.\n const oview = out === buffer ? view : createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n const outLen = len / 4;\n const state = this.get();\n // Subclass-misconfiguration invariant: outputLen must be 32-bit aligned and fit the state.\n if (len % 4 || outLen > state.length)\n throw new Error('invalid outputLen');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return\n // fresh bytes to the caller.\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneIntoMeta(to) {\n const { buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and\n // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.\n if (pos)\n to.buffer.set(buffer); // Avoid a hot modulo guard.\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state from RFC 6234 \u00A76.1: the first 32 bits of the fractional parts of the\n * square roots of the first eight prime numbers. Exported as a shared table; callers must treat\n * it as read-only because constructors copy words from it by index. */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state `H(0)` from RFC 6234 \u00A76.1. Exported as a shared table; callers must\n * treat it as read-only because constructors copy words from it by index. */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state from RFC 6234 \u00A76.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth\n * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only\n * because constructors copy halves from it by index. */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state from RFC 6234 \u00A76.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first\n * eight prime numbers. Exported as a shared table; callers must treat it as read-only because\n * constructors copy halves from it by index. */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n", "/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, oidNist, rotr } from \"./utils.js\";\n/**\n * SHA-224 / SHA-256 round constants from RFC 6234 \u00A75.1: the first 32 bits\n * of the cube roots of the first 64 primes (2..311).\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\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/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 \u00A76.2 step 1. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 \u00A76.2. */\nclass SHA2_32B extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // Numeric initializers matter: starting the fields as `undefined` changes\n // V8's field representation and makes sha256 3x slower (measured).\n A = 0;\n B = 0;\n C = 0;\n D = 0;\n E = 0;\n F = 0;\n G = 0;\n H = 0;\n constructor(outputLen, IV) {\n super(64, outputLen, 8, false);\n this.A = IV[0] | 0;\n this.B = IV[1] | 0;\n this.C = IV[2] | 0;\n this.D = IV[3] | 0;\n this.E = IV[4] | 0;\n this.F = IV[5] | 0;\n this.G = IV[6] | 0;\n this.H = IV[7] | 0;\n }\n get() {\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 set(A, B, C, D, E, F, G, H) {\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 _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\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)\n 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 roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/** Internal SHA-256 hash class grounded in RFC 6234 \u00A76.2. */\nexport class _SHA256 extends SHA2_32B {\n constructor() {\n super(32, SHA256_IV);\n }\n}\n/** Internal SHA-224 hash class grounded in RFC 6234 \u00A76.2 and \u00A78.5. */\nexport class _SHA224 extends SHA2_32B {\n constructor() {\n super(28, SHA224_IV);\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// SHA-384 / SHA-512 round constants from RFC 6234 \u00A75.2:\n// 80 full 64-bit words split into high/low halves.\n// prettier-ignore\nconst K512 = /* @__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))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable high-half schedule buffer for the RFC 6234 \u00A76.4 64-bit `W_t` words.\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\n// Reusable low-half schedule buffer for the RFC 6234 \u00A76.4 64-bit `W_t` words.\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 \u00A76.4. */\nclass SHA2_64B extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n // Numeric initializers matter: starting the fields as `undefined` changes\n // V8's field representation and slows hashing down (measured on sha256).\n Ah = 0;\n Al = 0;\n Bh = 0;\n Bl = 0;\n Ch = 0;\n Cl = 0;\n Dh = 0;\n Dl = 0;\n Eh = 0;\n El = 0;\n Fh = 0;\n Fl = 0;\n Gh = 0;\n Gl = 0;\n Hh = 0;\n Hl = 0;\n constructor(outputLen, IV) {\n super(128, outputLen, 16, false);\n this.Ah = IV[0] | 0;\n this.Al = IV[1] | 0;\n this.Bh = IV[2] | 0;\n this.Bl = IV[3] | 0;\n this.Ch = IV[4] | 0;\n this.Cl = IV[5] | 0;\n this.Dh = IV[6] | 0;\n this.Dl = IV[7] | 0;\n this.Eh = IV[8] | 0;\n this.El = IV[9] | 0;\n this.Fh = IV[10] | 0;\n this.Fl = IV[11] | 0;\n this.Gh = IV[12] | 0;\n this.Gl = IV[13] | 0;\n this.Hh = IV[14] | 0;\n this.Hl = IV[15] | 0;\n }\n // prettier-ignore\n get() {\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 set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\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 _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\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 // SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_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 roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n/** Internal SHA-512 hash class grounded in RFC 6234 \u00A76.3 and \u00A76.4. */\nexport class _SHA512 extends SHA2_64B {\n constructor() {\n super(64, SHA512_IV);\n }\n}\n/** Internal SHA-384 hash class grounded in RFC 6234 \u00A76.3 and \u00A76.4. */\nexport class _SHA384 extends SHA2_64B {\n constructor() {\n super(48, SHA384_IV);\n }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See the repo-side derivation recipe in `test/misc/sha2-gen-iv.js`.\n * These IV literals are checked against that script rather than a dedicated\n * local RFC section.\n */\n/** SHA-512/224 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA-512/256 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared\n * RFC 6234 \u00A76.4 compression engine. */\nexport class _SHA512_224 extends SHA2_64B {\n constructor() {\n super(28, T224_IV);\n }\n}\n/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared\n * RFC 6234 \u00A76.4 compression engine. */\nexport class _SHA512_256 extends SHA2_64B {\n constructor() {\n super(32, T256_IV);\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-256.\n * ```ts\n * sha256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(), \n/* @__PURE__ */ oidNist(0x01));\n/**\n * SHA2-224 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-224.\n * ```ts\n * sha224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new _SHA224(), \n/* @__PURE__ */ oidNist(0x04));\n/**\n * SHA2-512 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512.\n * ```ts\n * sha512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new _SHA512(), \n/* @__PURE__ */ oidNist(0x03));\n/**\n * SHA2-384 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-384.\n * ```ts\n * sha384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new _SHA384(), \n/* @__PURE__ */ oidNist(0x02));\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/256.\n * ```ts\n * sha512_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new _SHA512_256(), \n/* @__PURE__ */ oidNist(0x06));\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/224.\n * ```ts\n * sha512_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new _SHA512_224(), \n/* @__PURE__ */ oidNist(0x05));\n", "const U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();\nconst _32n = /* @__PURE__ */ BigInt(32);\n// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high\n// }` to match little-endian word order rather than the property names.\nfunction fromBig(n, le = false) {\n if (le)\n 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// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array\n// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.\nfunction split(lst, le = false) {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS\n// bitwise results back to uint32 first, and little-endian callers must swap.\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// Split a JS number into u32 halves without a BigInt allocation. Exact only for integers\n// `0 <= n < 2**53`; callers use it on byte / bit counters, which JS length math caps far below\n// that (an ArrayBuffer cannot exceed 2**53 - 1 bytes).\nconst fromNumH = (n) => (n / 2 ** 32) | 0;\nconst fromNumL = (n) => n >>> 0;\n// Drop-in replacement for `view.setBigUint64(byteOffset, BigInt(n), isLE)` without the per-call\n// BigInt allocation. Same `n < 2**53` precondition as `fromNumH`/`fromNumL`.\nfunction setU64FromNum(view, byteOffset, n, isLE) {\n const h = fromNumH(n);\n const l = fromNumL(n);\n view.setUint32(byteOffset, isLE ? l : h, isLE);\n view.setUint32(byteOffset + 4, isLE ? h : l, isLE);\n}\n// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`.\nconst shrSH = (h, _l, s) => h >>> s;\n// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`.\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half.\nconst rotr32H = (_h, l) => l;\n// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half.\nconst rotr32L = (h, _l) => h;\n// 64-bit left rotates (rotl*) are not defined here: sha3.ts, their only consumer, keeps\n// local copies so V8 inlines them into keccakP.\n// Add two split 64-bit words and return the split `{ h, l }` sum.\n// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out\n// of the low sum and instead use division.\nfunction add(Ah, Al, Bh, Bl) {\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\n// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`.\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\n// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`.\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`.\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\n// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`.\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`.\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\n// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`.\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, fromNumH, fromNumL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, setU64FromNum, shrSH, shrSL, split, toBig };\n", "/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - value to test\n * @returns `true` when the value is a Uint8Array-compatible view.\n * @example\n * Check whether a value is a Uint8Array-compatible view.\n * ```ts\n * isBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function isBytes(a) {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.\n // The fallback still requires a real ArrayBuffer view, so plain\n // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and\n // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n 'BYTES_PER_ELEMENT' in a &&\n a.BYTES_PER_ELEMENT === 1));\n}\n// Shared error-message prefix builder. Only called on throw paths, so assert\n// success paths never pay for the string concatenation.\nconst atitle = (title) => (title ? `\"${title}\" ` : '');\n/**\n * Asserts something is a non-negative integer.\n * @param n - number to validate\n * @param title - label included in thrown errors\n * @returns The validated number.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a non-negative integer option.\n * ```ts\n * anumber(32, 'length');\n * ```\n */\nexport function anumber(n, title = '') {\n if (typeof n !== 'number')\n throw new TypeError(atitle(title) + 'expected number, got ' + typeof n);\n if (!Number.isSafeInteger(n) || n < 0)\n throw new RangeError(atitle(title) + 'expected integer >= 0, got ' + n);\n return n;\n}\n/**\n * Asserts something is a boolean.\n * @param value - value to validate\n * @param title - label included in thrown errors\n * @returns The validated boolean.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a boolean option.\n * ```ts\n * abool(true, 'enableXOF');\n * ```\n */\nexport function abool(value, title = '') {\n if (typeof value !== 'boolean')\n throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);\n return value;\n}\n/**\n * Asserts something is Uint8Array.\n * @param value - value to validate\n * @param length - optional exact length constraint\n * @param title - label included in thrown errors\n * @returns The validated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate that a value is a byte array.\n * ```ts\n * abytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function abytes(value, length, title = '') {\n // Success path first: this runs at the start of every update() / digestInto(), and the\n // common `abytes(data)` form must not pay for length handling it does not use.\n if (isBytes(value) && (length === undefined || value.length === length))\n return value;\n // Error path: recompute freely to build the exact message.\n if (length !== undefined)\n anumber(length, 'length');\n const bytes = isBytes(value);\n const ofLen = length !== undefined ? ` of length ${length}` : '';\n const got = bytes ? `length=${value.length}` : `type=${typeof value}`;\n const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes)\n throw new TypeError(message);\n throw new RangeError(message);\n}\n/**\n * Copies bytes into a fresh Uint8Array.\n * Buffer-style slices can alias the same backing store, so callers that need ownership should copy.\n * @param bytes - source bytes to clone\n * @returns Freshly allocated copy of `bytes`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Clone a byte array before mutating it.\n * ```ts\n * const copy = copyBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function copyBytes(bytes) {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes));\n}\n/**\n * Asserts something is a wrapped hash constructor.\n * @param h - hash constructor to validate\n * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}\n * @throws On invalid hash metadata ranges or values. {@link RangeError}\n * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}\n * @example\n * Validate a callable hash wrapper.\n * ```ts\n * import { ahash } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * ahash(sha256);\n * ```\n */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new TypeError('expected hash wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass\n // validation and can produce empty outputs instead of failing fast.\n if (h.outputLen < 1 || h.blockLen < 1)\n throw new Error('hash blockLen / outputLen must be >= 1');\n}\nconst aobject = (value, label) => {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n throw new TypeError((label === 'object' ? '' : `\"${label}\" `) + 'expected object, got type=' + typeof value);\n};\nconst aopts = (value, label) => {\n aobject(value, label);\n const proto = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null)\n throw new TypeError(`\"${label}\" expected plain object`);\n // Object.assign() treats an own \"__proto__\" source key as a write to the target's legacy\n // prototype setter. Reject it before merging so inherited option values cannot be injected.\n if (Object.hasOwn(value, '__proto__'))\n throw new TypeError(`\"${label}.__proto__\" is not allowed`);\n};\n/**\n * Asserts a hash instance has not been destroyed or finished.\n * @param instance - hash instance to validate\n * @param checkFinished - whether to reject finalized instances\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Validate that a hash instance is still usable.\n * ```ts\n * import { aexists } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aexists(hash);\n * ```\n */\nexport function aexists(instance, checkFinished = true) {\n // Runs on every update()/digestInto(); the flags are library-owned booleans, so only their\n // truthiness is checked - re-validating their type per call was pure hot-path overhead.\n if (instance.destroyed)\n throw new Error('hash was destroyed');\n if (checkFinished && instance.finished)\n throw new Error('digest() was already called');\n}\n/**\n * Asserts output is a sufficiently-sized byte array.\n * @param out - destination buffer\n * @param instance - hash instance providing output length\n * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a caller-provided digest buffer.\n * ```ts\n * import { aoutput } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aoutput(new Uint8Array(hash.outputLen), hash);\n * ```\n */\nexport function aoutput(out, instance) {\n abytes(out, undefined, 'output');\n // `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast\n // when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call.\n const min = instance.outputLen;\n if (!(out.length >= min)) {\n throw new RangeError('\"output\" expected length >= ' + min);\n }\n}\n/**\n * Casts a typed array view to Uint8Array.\n * @param arr - source typed array\n * @returns Uint8Array view over the same buffer.\n * @example\n * Reinterpret a typed array as bytes.\n * ```ts\n * u8(new Uint32Array([1, 2]));\n * ```\n */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Casts a typed array view to Uint32Array.\n * `arr.byteOffset` must already be 4-byte aligned or the platform\n * Uint32Array constructor will throw.\n * @param arr - source typed array\n * @returns Uint32Array view over the same buffer.\n * @example\n * Reinterpret a byte array as 32-bit words.\n * ```ts\n * u32(new Uint8Array(8));\n * ```\n */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/**\n * Zeroizes typed arrays in place. Warning: JS provides no guarantees.\n * @param arrays - arrays to overwrite with zeros\n * @example\n * Zeroize sensitive buffers in place.\n * ```ts\n * clean(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - source typed array\n * @returns DataView over the same buffer region.\n * @example\n * Create a DataView over an existing buffer.\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Rotate-right operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the right.\n * ```ts\n * rotr(0x12345678, 8);\n * ```\n */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/**\n * Rotate-left operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the left.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Whether the current platform is little-endian. */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/**\n * Byte-swap operation for uint32 values.\n * @param word - source word\n * @returns Word with reversed byte order.\n * @example\n * Reverse the byte order of a 32-bit word.\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/**\n * Conditionally byte-swaps one 32-bit word on big-endian platforms.\n * @param n - source word\n * @returns Original or byte-swapped word depending on platform endianness.\n * @example\n * Normalize a 32-bit word for host endianness.\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n) >>> 0;\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - array to mutate\n * @returns The same array after mutation; callers pass live state arrays here.\n * @example\n * Reverse the byte order of every word in place.\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n/**\n * Conditionally byte-swaps a Uint32Array on big-endian platforms.\n * @param u - array to normalize for host endianness\n * @returns Original or byte-swapped array depending on platform endianness.\n * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.\n * @example\n * Normalize a word array for host endianness.\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string.\n * Uses the built-in function when available and assumes it matches the tested\n * fallback semantics.\n * @param bytes - bytes to encode\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Convert bytes to lowercase hexadecimal.\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\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// Strict ASCII nibble parser: non-ASCII hex lookalikes are rejected as undefined.\n// ASCII codes: '0'..'9' = 48..57, 'A'..'F' = 65..70, 'a'..'f' = 97..102.\n// prettier-ignore\nfunction asciiToBase16(ch) {\n return ch >= 48 && ch <= 57 ? ch - 48 // '2' => 50-48\n : ch >= 65 && ch <= 70 ? ch - (65 - 10) // 'B' => 66-(65-10)\n : ch >= 97 && ch <= 102 ? ch - (97 - 10) // 'b' => 98-(97-10)\n : undefined;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - hexadecimal string to decode\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode lowercase hexadecimal into bytes.\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return Uint8Array.fromHex(hex);\n }\n catch (error) {\n if (error instanceof SyntaxError)\n throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new RangeError('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)); // parse first char, multiply it by 16\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); // parse second char\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9\n }\n return array;\n}\n/**\n * Yields to the host task scheduler so timers, I/O, and rendering can make progress.\n * Uses the Web Scheduling API when available or `setTimeout` as a cross-platform fallback.\n * Host-task yields are much slower than microtasks (roughly 1ms with the timer fallback), so\n * async loops should use `asyncTick >= 10` to amortize scheduling overhead to about 10% while\n * still allowing other event-loop work to proceed.\n * @param onReject - optional cleanup invoked only if the host yield fails\n * @example\n * Yield to the next scheduler tick.\n * ```ts\n * await nextTick();\n * ```\n */\nexport function nextTick(onReject) {\n const host = globalThis;\n if (typeof host.scheduler?.yield === 'function') {\n const promise = host.scheduler.yield();\n // Keep the original scheduler rejection; this handler exists only for cleanup.\n if (onReject)\n promise.catch(onReject);\n return promise;\n }\n return new Promise((resolve) => host.setTimeout(resolve, 0));\n}\n/**\n * Returns control to the host event loop every `tick` milliseconds to avoid blocking long loops.\n * @param iters - number of loop iterations to run\n * @param tick - maximum time slice in milliseconds\n * @param cb - callback executed on each iteration\n * @param onReject - optional cleanup invoked only if a host yield fails\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Run a loop that periodically yields back to the event loop.\n * ```ts\n * await asyncLoop(2, 0, () => {});\n * ```\n */\nexport async function asyncLoop(iters, tick, cb, onReject) {\n anumber(iters, 'iters');\n anumber(tick, 'tick');\n if (typeof cb !== 'function')\n throw new TypeError('callback must be a function');\n // Callback is synchronous by contract; asyncLoop only yields between sync work windows.\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)\n continue;\n await nextTick(onReject);\n // Track only synchronous work time; scheduler delay after yielding is outside our budget.\n ts = Date.now();\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * Non-ASCII details are delegated to the platform `TextEncoder`.\n * @param str - string to encode\n * @returns UTF-8 encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode a string as UTF-8 bytes.\n * ```ts\n * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new TypeError('string expected');\n const encoded = new TextEncoder().encode(str);\n try {\n // Copy into the current realm for Firefox extension contexts. Callers that own the returned\n // buffer can then wipe it independently of TextEncoder's temporary result.\n return new Uint8Array(encoded); // https://bugzil.la/1681809\n }\n finally {\n clean(encoded);\n }\n}\n/**\n * Helper for KDFs: consumes Uint8Array or string.\n * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.\n * @param data - user-provided KDF input\n * @param errorTitle - label included in thrown errors\n * @returns Byte representation of the input.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Normalize KDF input to bytes.\n * ```ts\n * kdfInputToBytes('password');\n * ```\n */\nexport function kdfInputToBytes(data, errorTitle = '') {\n if (typeof data === 'string')\n return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - arrays to concatenate\n * @returns Concatenated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Concatenate multiple byte arrays.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays) {\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 * Validates declared required and optional field types on a plain object.\n * This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct\n * one-line guards such as `abytes()`, `abool()`, or `anumber()` instead.\n * @param object - object to validate\n * @param fields - map of required field names to expected types\n * @param optFields - map of optional field names to expected types\n * @param title - label included in thrown errors\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate required and optional option fields.\n * ```ts\n * validateObject({ N: 1024, dkLen: 32 }, { N: 'number' }, { dkLen: 'number' });\n * ```\n */\nexport const validateObject = (object, fields = {}, optFields = {}, title = 'object') => {\n aobject(object, title);\n aobject(fields, 'fields');\n aobject(optFields, 'optFields');\n function checkField(fieldName, expectedType, isOpt) {\n const label = title === 'object' ? `param \"${String(fieldName)}\"` : `\"${title}.${String(fieldName)}\"`;\n // Config fields must be explicit own properties. Optional inherited values are rejected too\n // because callers keep reading the same options object after validation.\n const val = object[fieldName];\n // Runtime objects such as Field instances intentionally satisfy required method slots\n // via their shared prototype.\n if (!Object.hasOwn(object, fieldName) &&\n (isOpt ? val !== undefined : expectedType !== 'function')) {\n throw new TypeError(`${label} is invalid: expected own property`);\n }\n if (isOpt && val === undefined)\n return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);\n }\n const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n};\n/**\n * Merges default options and passed options.\n * @param defaults - base option object\n * @param opts - user overrides\n * @param title - label included in thrown override errors\n * @returns Fresh merged option object with a null prototype.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Merge user overrides onto default options.\n * ```ts\n * checkOpts({ dkLen: 32 }, { asyncTick: 10 });\n * ```\n */\nexport function checkOpts(defaults, opts, title = 'opts') {\n aopts(defaults, 'defaults');\n if (opts !== undefined)\n aopts(opts, title);\n // Callers read optional fields directly, so omitted values must not fall through to ambient\n // Object.prototype pollution (for example a forged `dkLen` changing SHAKE's default output).\n const merged = Object.assign(Object.create(null), defaults, opts);\n return merged;\n}\n/**\n * Creates a callable hash function from a stateful class constructor.\n * @param hashCons - hash constructor or factory\n * @param info - optional metadata such as DER OID\n * @returns Frozen callable hash wrapper with `.create()`.\n * Wrapper construction eagerly calls `hashCons(undefined)` once to read\n * `outputLen` / `blockLen`, so constructor side effects happen at module\n * init time.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Wrap a stateful hash constructor into a callable helper.\n * ```ts\n * import { createHasher } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const wrapped = createHasher(sha256.create, { oid: sha256.oid });\n * wrapped(new Uint8Array([1]));\n * ```\n */\nexport function createHasher(hashCons, info = {}) {\n if (typeof hashCons !== 'function')\n throw new TypeError('\"hashCons\" expected function, got type=' + typeof hashCons);\n info = checkOpts({}, info, 'info');\n const hashC = (msg, opts) => hashCons(opts)\n .update(msg)\n .digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.canXOF = tmp.canXOF;\n hashC.create = (opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\n}\n/**\n * Cryptographically secure PRNG backed by `crypto.getRandomValues`.\n * @param bytesLength - number of random bytes to generate\n * @returns Random bytes.\n * The platform `getRandomValues()` implementation still defines any\n * single-call length cap, and this helper rejects oversize requests\n * with a stable library `RangeError` instead of host-specific errors.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}\n * @example\n * Generate a fresh random key or nonce.\n * ```ts\n * const key = randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32) {\n // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.\n anumber(bytesLength, 'bytesLength');\n const cr = typeof globalThis === 'object' ? globalThis.crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n // Web Cryptography API Level 2 \u00A710.1.1:\n // if `byteLength > 65536`, throw `QuotaExceededError`.\n // Keep the guard explicit so callers can see the quota in code\n // instead of discovering it by reading the spec or host errors.\n // This wrapper surfaces the same quota as a stable library RangeError.\n if (bytesLength > 65536)\n throw new RangeError(`\"bytesLength\" expected <= 65536, got ${bytesLength}`);\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n/**\n * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.\n * @param suffix - final OID byte for the selected hash.\n * The helper accepts any byte even though only the documented NIST hash\n * suffixes are meaningful downstream.\n * @returns Object containing the DER-encoded OID.\n * @example\n * Build OID metadata for a NIST hash.\n * ```ts\n * oidNist(0x01);\n * ```\n */\nexport const oidNist = (suffix) => ({\n // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.\n // Larger suffix values would need base-128 OID encoding and a different length byte.\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n", "/**\n * SHA3 (keccak) hash function, based on a new \"Sponge function\" design.\n * Different from older hashes, the internal state is bigger than output size.\n *\n * Check out\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf | FIPS-202},\n * {@link https://keccak.team/keccak.html | Website}, and\n * {@link https://crypto.stackexchange.com/q/15727 | the differences between\n * SHA-3 and Keccak}.\n *\n * Check out `sha3-addons` module for cSHAKE, k12, and others.\n * @module\n */\nimport { split } from \"./_u64.js\";\n// prettier-ignore\nimport { abool, abytes, aexists, anumber, aoutput, checkOpts, clean, createHasher, oidNist, swap32IfBE, u32 } from \"./utils.js\";\n// No __PURE__ annotations in sha3 header:\n// EVERYTHING is in fact used on every export.\n// Various per round constants calculations\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst _7n = BigInt(7);\nconst _256n = BigInt(256);\n// FIPS 202 Algorithm 5 rc(): when the outgoing bit is 1, the 8-bit LFSR xors\n// taps 0, 4, 5, and 6, which compresses to the feedback mask `0x71`.\nconst _0x71n = BigInt(0x71);\nconst SHA3_PI = [];\nconst SHA3_ROTL = [];\nconst _SHA3_IOTA = []; // no pure annotation: var is always used\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n)\n t ^= _1n << ((_1n << BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst IOTAS = split(_SHA3_IOTA, true);\n// `split(..., true)` keeps the local little-endian lane-word layout used by\n// `state32`, so these `H` / `L` tables follow the file's first-word /\n// second-word lane slots rather than `_u64.ts`'s usual high/low naming.\nconst SHA3_IOTA_H = IOTAS[0];\nconst SHA3_IOTA_L = IOTAS[1];\n// 64-bit left rotates as u32 pairs. Inlined here (not imported from _u64) so V8 can\n// inline them into keccakP \u2014 the import path costs ~24% on sha3_256. SHA3 is the only\n// consumer of left-rotates; other hashes use right-rotates from _u64.\n// Valid for s in 1..31 (SH/SL) and 33..63 (BH/BL); keccak never rotates by 0/32/64.\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\nconst rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n// Reused Theta scratch buffer (column parities), same pattern as SHA256_W in sha2.\n// keccakP never calls user code, so the shared buffer cannot be observed mid-permutation.\nconst B = new Uint32Array(5 * 2);\n/**\n * `keccakf1600` internal permutation, additionally allows adjusting the round count.\n * @param s - 5x5 Keccak state encoded as 25 lanes split into 50 uint32 words\n * in this file's local little-endian lane-word order\n * @param rounds - number of rounds to execute\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If `rounds` is outside the supported `1..24` range. {@link Error}\n * @example\n * Permute a Keccak state with the default 24 rounds.\n * ```ts\n * keccakP(new Uint32Array(50));\n * ```\n */\nexport function keccakP(s, rounds = 24) {\n if (!(s instanceof Uint32Array))\n throw new TypeError('\"s\" expected Uint32Array(50), got type=' + typeof s);\n if (s.length !== 50)\n throw new RangeError('\"s\" expected Uint32Array(50), got length=' + s.length);\n anumber(rounds, 'rounds');\n // This implementation precomputes only the standard Keccak-f[1600] 24-round Iota table.\n if (rounds < 1 || rounds > 24)\n throw new Error('\"rounds\" expected integer 1..24');\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta \u03B8\n for (let x = 0; x < 10; x++)\n B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (\u03C1) and Pi (\u03C0)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (\u03C7)\n // Same as:\n // for (let x = 0; x < 10; x++) B[x] = s[y + x];\n // for (let x = 0; x < 10; x++) s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n for (let y = 0; y < 50; y += 10) {\n const b0 = s[y], b1 = s[y + 1], b2 = s[y + 2], b3 = s[y + 3];\n s[y] ^= ~s[y + 2] & s[y + 4];\n s[y + 1] ^= ~s[y + 3] & s[y + 5];\n s[y + 2] ^= ~s[y + 4] & s[y + 6];\n s[y + 3] ^= ~s[y + 5] & s[y + 7];\n s[y + 4] ^= ~s[y + 6] & s[y + 8];\n s[y + 5] ^= ~s[y + 7] & s[y + 9];\n s[y + 6] ^= ~s[y + 8] & b0;\n s[y + 7] ^= ~s[y + 9] & b1;\n s[y + 8] ^= ~b0 & b2;\n s[y + 9] ^= ~b1 & b3;\n }\n // Iota (\u03B9)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n clean(B);\n}\n/**\n * Keccak sponge function.\n * @param blockLen - absorb/squeeze rate in bytes\n * @param suffix - domain separation suffix byte\n * @param outputLen - default digest length in bytes. This base sponge only\n * requires a non-negative integer; wrappers that need positive output\n * lengths must enforce that themselves.\n * @param enableXOF - whether XOF output is allowed\n * @param rounds - number of Keccak-f rounds\n * @example\n * Build a sponge state, absorb bytes, then finalize a digest.\n * ```ts\n * const hash = new Keccak(136, 0x06, 32);\n * hash.update(new Uint8Array([1, 2, 3]));\n * hash.digest();\n * ```\n */\nexport class Keccak {\n state;\n pos = 0;\n posOut = 0;\n finished = false;\n state32;\n destroyed = false;\n blockLen;\n suffix;\n outputLen;\n canXOF;\n enableXOF = false;\n rounds;\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {\n anumber(blockLen, 'blockLen');\n anumber(suffix, 'suffix');\n anumber(rounds, 'rounds');\n abool(enableXOF, 'enableXOF');\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.canXOF = enableXOF;\n this.rounds = rounds;\n // Can be passed from user as dkLen\n anumber(outputLen, 'outputLen');\n // Only keccak-f1600 is supported: 1600 bits (5x5 matrix of 64bit) === 200 bytes of state.\n if (!(0 < blockLen && blockLen < 200))\n throw new Error('\"blockLen\" must be 1..199');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n clone() {\n return this._cloneInto();\n }\n keccak() {\n swap32IfBE(this.state32);\n keccakP(this.state32, this.rounds);\n swap32IfBE(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data) {\n aexists(this);\n abytes(data);\n const { blockLen, state, state32 } = this;\n const len = data.length;\n // Absorb full blocks with u32 XORs when both sides are 4-byte aligned.\n // XOR of same-position words equals XOR of same-position bytes, so this is endianness-safe.\n const canUseU32 = blockLen % 4 === 0 && data.byteOffset % 4 === 0;\n const blockLen32 = blockLen / 4;\n const data32 = canUseU32 && len >= blockLen ? u32(data) : undefined;\n for (let pos = 0; pos < len;) {\n if (data32 !== undefined && this.pos === 0 && pos % 4 === 0 && len - pos >= blockLen) {\n for (let i = 0, o = pos / 4; i < blockLen32; i++)\n state32[i] ^= data32[o + i];\n pos += blockLen;\n // Subclasses (_KeccakPRG) read `this.pos` inside their `keccak()` override,\n // so it must reflect the fully-absorbed block before the permutation fires.\n this.pos = blockLen;\n this.keccak();\n continue;\n }\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++)\n state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen)\n this.keccak();\n }\n return this;\n }\n finish() {\n if (this.finished)\n return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // FIPS 202 appends the SHA3/SHAKE domain-separation suffix before pad10*1.\n // These byte values already include the first padding bit, while the\n // final `0x80` below supplies the closing `1` bit in the last rate byte.\n state[pos] ^= suffix;\n // If that combined suffix lands in the last rate byte and already sets\n // bit 7, absorb it first so the final pad10*1 bit can be xored into a\n // fresh block.\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1)\n this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n writeInto(out) {\n aexists(this, false);\n abytes(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len;) {\n if (this.posOut >= blockLen)\n this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out) {\n // Plain SHA3/Keccak usage with XOF is probably a mistake, but this base\n // class is also reused by SHAKE/cSHAKE/KMAC/TupleHash/ParallelHash/\n // TurboSHAKE/KangarooTwelve wrappers that intentionally enable XOF.\n if (!this.enableXOF)\n throw new Error('XOF is not enabled');\n return this.writeInto(out);\n }\n xof(bytes) {\n anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out) {\n aoutput(out, this);\n if (this.finished)\n throw new Error('digest() was already called');\n // `aoutput(...)` allows oversized buffers; digestInto() must fill only the advertised digest.\n this.writeInto(out.length === this.outputLen ? out : out.subarray(0, this.outputLen));\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.outputLen);\n this.digestInto(out);\n return out;\n }\n destroy() {\n this.destroyed = true;\n clean(this.state);\n }\n _cloneInto(to) {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds);\n // Reused destinations can come from a different rate/capacity variant, so clone must rewrite\n // the sponge geometry as well as the state words.\n to.blockLen = blockLen;\n to.state32.set(this.state32);\n // Sponge padding and XOF output are positional, so both offsets are part of the clone state.\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n // Clones must preserve the public capability bit too; `_KMAC` reuses this path and deep clone\n // tests compare instance fields directly, so leaving `canXOF` behind makes the clone lie.\n to.canXOF = this.canXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\nconst genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);\n/**\n * SHA3-224 hash function.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA3-224.\n * ```ts\n * sha3_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha3_224 = /* @__PURE__ */ genKeccak(0x06, 144, 28, \n/* @__PURE__ */ oidNist(0x07));\n/**\n * SHA3-256 hash function. Different from keccak-256.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA3-256.\n * ```ts\n * sha3_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha3_256 = /* @__PURE__ */ genKeccak(0x06, 136, 32, \n/* @__PURE__ */ oidNist(0x08));\n/**\n * SHA3-384 hash function.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA3-384.\n * ```ts\n * sha3_384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha3_384 = /* @__PURE__ */ genKeccak(0x06, 104, 48, \n/* @__PURE__ */ oidNist(0x09));\n/**\n * SHA3-512 hash function.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA3-512.\n * ```ts\n * sha3_512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha3_512 = /* @__PURE__ */ genKeccak(0x06, 72, 64, \n/* @__PURE__ */ oidNist(0x0a));\n/**\n * Keccak-224 hash function.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with Keccak-224.\n * ```ts\n * keccak_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const keccak_224 = /* @__PURE__ */ genKeccak(0x01, 144, 28);\n/**\n * Keccak-256 hash function. Different from SHA3-256.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with Keccak-256.\n * ```ts\n * keccak_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const keccak_256 = /* @__PURE__ */ genKeccak(0x01, 136, 32);\n/**\n * Keccak-384 hash function.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with Keccak-384.\n * ```ts\n * keccak_384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const keccak_384 = /* @__PURE__ */ genKeccak(0x01, 104, 48);\n/**\n * Keccak-512 hash function.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with Keccak-512.\n * ```ts\n * keccak_512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const keccak_512 = /* @__PURE__ */ genKeccak(0x01, 72, 64);\nconst genShake = (suffix, blockLen, outputLen, info = {}) => createHasher((opts = {}) => {\n opts = checkOpts({}, opts);\n return new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true);\n}, info);\n/**\n * SHAKE128 XOF with 128-bit security and a 16-byte default output.\n * @param msg - message bytes to hash\n * @param opts - Optional output-length override. See {@link ShakeOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHAKE128.\n * ```ts\n * shake128(new Uint8Array([97, 98, 99]), { dkLen: 32 });\n * ```\n */\nexport const shake128 = \n/* @__PURE__ */\ngenShake(0x1f, 168, 16, /* @__PURE__ */ oidNist(0x0b));\n/**\n * SHAKE256 XOF with 256-bit security and a 32-byte default output.\n * @param msg - message bytes to hash\n * @param opts - Optional output-length override. See {@link ShakeOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHAKE256.\n * ```ts\n * shake256(new Uint8Array([97, 98, 99]), { dkLen: 64 });\n * ```\n */\nexport const shake256 = \n/* @__PURE__ */\ngenShake(0x1f, 136, 32, /* @__PURE__ */ oidNist(0x0c));\n/**\n * SHAKE128 XOF with 256-bit output (NIST version).\n * @param msg - message bytes to hash\n * @param opts - Optional output-length override. See {@link ShakeOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHAKE128 using a 32-byte default output.\n * ```ts\n * shake128_32(new Uint8Array([97, 98, 99]), { dkLen: 32 });\n * ```\n */\nexport const shake128_32 = \n/* @__PURE__ */\ngenShake(0x1f, 168, 32, /* @__PURE__ */ oidNist(0x0b));\n/**\n * SHAKE256 XOF with 512-bit output (NIST version).\n * @param msg - message bytes to hash\n * @param opts - Optional output-length override. See {@link ShakeOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHAKE256 using a 64-byte default output.\n * ```ts\n * shake256_64(new Uint8Array([97, 98, 99]), { dkLen: 64 });\n * ```\n */\nexport const shake256_64 = \n/* @__PURE__ */\ngenShake(0x1f, 136, 64, /* @__PURE__ */ oidNist(0x0c));\n", "/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abytes as abytes_, anumber as anumber_, bytesToHex as bytesToHex_, concatBytes as concatBytes_, hexToBytes as hexToBytes_, isBytes as isBytes_, randomBytes as randomBytes_, } from '@noble/hashes/utils.js';\n/**\n * Validates that a value is an array, optionally validating each element.\n * @param item - Value to validate.\n * @param title - Label included in thrown errors.\n * @param inner - Optional per-element validator, called with the element and its label.\n * @returns The validated array.\n * @example\n * Validate an array of points before batch processing.\n *\n * ```ts\n * aarray([1n, 2n], 'scalars');\n * ```\n */\nexport function aarray(item, title, inner = () => { }) {\n if (!Array.isArray(item))\n throw new TypeError(`\"${title}\" expected array, got type=${typeof item}`);\n for (let i = 0; i < item.length; i++)\n inner(item[i], `${title}[${i}]`);\n return item;\n}\n/**\n * Validates that a value is a byte array.\n * @param value - Value to validate.\n * @param length - Optional exact byte length.\n * @param title - Optional field name.\n * @returns Original byte array.\n * @example\n * Reject non-byte input before passing data into curve code.\n *\n * ```ts\n * abytes(new Uint8Array(1));\n * ```\n */\nexport const abytes = (value, length, title) => abytes_(value, length, title);\n/**\n * Validates that a value is a non-negative safe integer.\n * @param n - Value to validate.\n * @param title - Optional field name.\n * @returns The validated number.\n * @example\n * Validate a numeric length before allocating buffers.\n *\n * ```ts\n * anumber(1);\n * ```\n */\nexport const anumber = anumber_;\n/**\n * Asserts something is a string.\n * @param value - Value to validate.\n * @param title - Label included in thrown errors.\n * @returns The validated string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a label string.\n *\n * ```ts\n * astring('example', 'label');\n * ```\n */\nexport function astring(value, title = '') {\n if (typeof value !== 'string') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(prefix + 'expected string, got type=' + typeof value);\n }\n return value;\n}\n/**\n * Asserts something is a plain object-ish value, not null or array.\n * @param value - Value to validate.\n * @param title - Label included in thrown errors.\n * @returns The validated object.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate an options object before checking fields.\n *\n * ```ts\n * aobject({ flag: true });\n * ```\n */\nexport function aobject(value, title = 'object') {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n throw new TypeError(title === 'object'\n ? 'expected valid options object'\n : `\"${title}\" expected object, got type=${typeof value}`);\n return value;\n}\n/**\n * Asserts something is a function.\n * @param value - Value to validate.\n * @param title - Label included in thrown errors.\n * @returns The validated function.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a required method before calling it.\n *\n * ```ts\n * afunction(() => true, 'predicate');\n * ```\n */\nexport function afunction(value, title) {\n if (typeof value !== 'function')\n throw new TypeError(`\"${title}\" is invalid: expected function, got ${typeof value}`);\n return value;\n}\n/**\n * Encodes bytes as lowercase hex.\n * @param bytes - Bytes to encode.\n * @returns Lowercase hex string.\n * @example\n * Serialize bytes as hex for logging or fixtures.\n *\n * ```ts\n * bytesToHex(Uint8Array.of(1, 2, 3));\n * ```\n */\nexport const bytesToHex = bytesToHex_;\n/**\n * Concatenates byte arrays.\n * @param arrays - Byte arrays to join.\n * @returns Concatenated bytes.\n * @example\n * Join domain-separated chunks into one buffer.\n *\n * ```ts\n * concatBytes(Uint8Array.of(1), Uint8Array.of(2));\n * ```\n */\nexport const concatBytes = (...arrays) => concatBytes_(...arrays);\n/**\n * Decodes lowercase or uppercase hex into bytes.\n * @param hex - Hex string to decode.\n * @returns Decoded bytes.\n * @example\n * Parse fixture hex into bytes before hashing.\n *\n * ```ts\n * hexToBytes('0102');\n * ```\n */\nexport const hexToBytes = (hex) => hexToBytes_(hex);\n/**\n * Checks whether a value is a Uint8Array.\n * @param a - Value to inspect.\n * @returns `true` when `a` is a Uint8Array.\n * @example\n * Branch on byte input before decoding it.\n *\n * ```ts\n * isBytes(new Uint8Array(1));\n * ```\n */\nexport const isBytes = isBytes_;\n/**\n * Reads random bytes from the platform CSPRNG.\n * @param bytesLength - Number of random bytes to read.\n * @returns Fresh random bytes.\n * @example\n * Generate a random seed for a keypair.\n *\n * ```ts\n * randomBytes(2);\n * ```\n */\nexport const randomBytes = (bytesLength) => randomBytes_(bytesLength);\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n// Shared error-message prefix builder. Only called on throw paths, so assert\n// success paths never pay for the string concatenation.\nconst atitle = (title) => (title ? `\"${title}\" ` : '');\n/**\n * Validates that a flag is boolean.\n * @param value - Value to validate.\n * @param title - Optional field name.\n * @returns Original value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Reject non-boolean option flags early.\n *\n * ```ts\n * abool(true);\n * ```\n */\nexport function abool(value, title = '') {\n if (typeof value !== 'boolean')\n throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);\n return value;\n}\n/**\n * Validates that a value is a non-negative bigint or safe integer.\n * @param n - Value to validate.\n * @returns The same validated value.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate one integer-like value before serializing it.\n *\n * ```ts\n * abignumber(1n);\n * ```\n */\nexport function abignumber(n) {\n if (typeof n === 'bigint') {\n if (!isPosBig(n))\n throw new RangeError('positive bigint expected, got ' + n);\n }\n else\n anumber(n);\n return n;\n}\n/**\n * Validates that a value is a safe integer.\n * @param value - Integer to validate.\n * @param title - Optional field name.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a window size before scalar arithmetic uses it.\n *\n * ```ts\n * asafenumber(1);\n * ```\n */\nexport function asafenumber(value, title = '') {\n if (typeof value !== 'number') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(prefix + 'expected number, got type=' + typeof value);\n }\n if (!Number.isSafeInteger(value)) {\n const prefix = title && `\"${title}\" `;\n throw new RangeError(prefix + 'expected safe integer, got ' + value);\n }\n}\n/**\n * Encodes a bigint into even-length big-endian hex.\n * The historical \"unpadded\" name only means \"no fixed-width field padding\"; odd-length hex still\n * gets one leading zero nibble so the result always represents whole bytes.\n * @param num - Number to encode.\n * @returns Big-endian hex string.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Encode a scalar into hex without a `0x` prefix.\n *\n * ```ts\n * numberToHexUnpadded(255n);\n * ```\n */\nexport function numberToHexUnpadded(num) {\n const hex = abignumber(num).toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\n/**\n * Parses a big-endian hex string into bigint.\n * Accepts odd-length hex through the native `BigInt('0x' + hex)` parser and currently surfaces the\n * same native `SyntaxError` for malformed hex instead of wrapping it in a library-specific error.\n * @param hex - Hex string without `0x`.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Parse a scalar from fixture hex.\n *\n * ```ts\n * hexToNumber('ff');\n * ```\n */\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n// BE: Big Endian, LE: Little Endian\n/**\n * Parses big-endian bytes into bigint.\n * @param bytes - Bytes in big-endian order.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Read a scalar encoded in network byte order.\n *\n * ```ts\n * bytesToNumberBE(Uint8Array.of(1, 0));\n * ```\n */\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex_(bytes));\n}\n/**\n * Parses little-endian bytes into bigint.\n * @param bytes - Bytes in little-endian order.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Read a scalar encoded in little-endian form.\n *\n * ```ts\n * bytesToNumberLE(Uint8Array.of(1, 0));\n * ```\n */\nexport function bytesToNumberLE(bytes) {\n return hexToNumber(bytesToHex_(copyBytes(abytes_(bytes)).reverse()));\n}\n/**\n * Encodes a bigint into fixed-length big-endian bytes.\n * @param n - Number to encode.\n * @param len - Output length in bytes. Must be greater than zero.\n * @returns Big-endian byte array.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If a documented runtime validation or state check fails. {@link Error}\n * @example\n * Serialize a scalar into a 32-byte field element.\n *\n * ```ts\n * numberToBytesBE(255n, 2);\n * ```\n */\nexport function numberToBytesBE(n, len) {\n anumber_(len);\n if (len === 0)\n throw new Error('zero output length is invalid');\n n = abignumber(n);\n const expectedLen = len * 2;\n const hex = n.toString(16);\n // Detect overflow before hex parsing so oversized values don't leak the shared odd-hex error.\n if (hex.length > expectedLen)\n throw new RangeError('number is too large');\n return hexToBytes_(hex.padStart(expectedLen, '0'));\n}\n/**\n * Encodes a bigint into fixed-length little-endian bytes.\n * @param n - Number to encode.\n * @param len - Output length in bytes.\n * @returns Little-endian byte array.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If a documented runtime validation or state check fails. {@link Error}\n * @example\n * Serialize a scalar for little-endian protocols.\n *\n * ```ts\n * numberToBytesLE(255n, 2);\n * ```\n */\nexport function numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\n/**\n * Encodes a bigint into variable-length big-endian bytes.\n * @param n - Number to encode.\n * @returns Variable-length big-endian bytes.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Serialize a bigint without fixed-width padding.\n *\n * ```ts\n * numberToVarBytesBE(255n);\n * ```\n */\nexport function numberToVarBytesBE(n) {\n return hexToBytes_(numberToHexUnpadded(abignumber(n)));\n}\n// Compares 2 u8a-s in kinda constant time\n/**\n * Compares two byte arrays in constant-ish time.\n * @param a - Left byte array.\n * @param b - Right byte array.\n * @returns `true` when bytes match.\n * @example\n * Compare two encoded points without early exit.\n *\n * ```ts\n * equalBytes(Uint8Array.of(1), Uint8Array.of(1));\n * ```\n */\nexport function equalBytes(a, b) {\n a = abytes(a);\n b = abytes(b);\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n * @param bytes - Bytes to copy.\n * @returns Detached copy.\n * @example\n * Make an isolated copy before mutating serialized bytes.\n *\n * ```ts\n * copyBytes(Uint8Array.of(1, 2, 3));\n * ```\n */\nexport function copyBytes(bytes) {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes));\n}\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as `TextEncoder` for ASCII or throws.\n * @param ascii - ASCII input text.\n * @returns Encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode an ASCII domain-separation tag.\n *\n * ```ts\n * asciiToBytes('ABC');\n * ```\n */\nexport function asciiToBytes(ascii) {\n if (typeof ascii !== 'string')\n throw new TypeError('ascii string expected, got ' + typeof ascii);\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new RangeError(`string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`);\n }\n return charCode;\n });\n}\n/**\n * Checks whether n is non-negative bigint. Historical name.\n * @param n - candidate value\n * @returns `true` when the value is bigint and 0 or larger\n * @example\n * Check a candidate scalar before range validation.\n *\n * ```ts\n * isPosBig(2n);\n * ```\n */\nexport function isPosBig(n) {\n return typeof n === 'bigint' && _0n <= n;\n}\n/**\n * Checks whether a bigint lies inside a half-open range.\n * @param n - Candidate value.\n * @param min - Inclusive lower bound.\n * @param max - Exclusive upper bound.\n * @returns `true` when the value is inside the range.\n * @example\n * Check whether a candidate scalar fits the field order.\n *\n * ```ts\n * inRange(2n, 1n, 3n);\n * ```\n */\nexport function inRange(n, min, max) {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n/**\n * Asserts `min <= n < max`. NOTE: upper bound is exclusive.\n * @param title - Value label for error messages.\n * @param n - Candidate value.\n * @param min - Inclusive lower bound.\n * @param max - Exclusive upper bound.\n * Wrong-type inputs are not separated from out-of-range values here: they still flow through the\n * shared `RangeError` path because this is only a throwing wrapper around `inRange(...)`.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Assert that a bigint stays within one half-open range.\n *\n * ```ts\n * aInRange('x', 2n, 1n, 256n);\n * ```\n */\nexport function aInRange(title, n, min, max) {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new RangeError('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n// Bit operations\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n * @param n - Value to inspect.\n * @returns Bit length.\n * @throws If the value is negative. {@link Error}\n * @example\n * Measure the bit length of a scalar before serialization.\n *\n * ```ts\n * bitLen(8n);\n * ```\n */\nexport function bitLen(n) {\n // Size callers in this repo only use non-negative orders / scalars, so negative inputs are a\n // contract bug and must not silently collapse to zero bits.\n if (n < _0n)\n throw new Error('expected non-negative bigint, got ' + n);\n // Native radix conversion beats a shift loop at every size, and the loop is quadratic in bits.\n return n === _0n ? 0 : n.toString(2).length;\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 * @param n - Source value.\n * @param pos - Bit position. Negative positions are passed through to raw\n * bigint shift semantics; because the mask is built as `1n << pos`,\n * they currently collapse to `0n` and make the helper a no-op.\n * @returns Bit as bigint.\n * @example\n * Gets single bit at position.\n *\n * ```ts\n * bitGet(5n, 0);\n * ```\n */\nexport function bitGet(n, pos) {\n if (typeof n !== 'bigint')\n throw new TypeError('\"n\" expected bigint, got type=' + typeof n);\n asafenumber(pos, 'pos');\n return (n >> BigInt(pos)) & _1n;\n}\n/**\n * Sets single bit at position.\n * @param n - Source value.\n * @param pos - Bit position. Negative positions are passed through to raw bigint shift semantics,\n * so they currently behave like left shifts.\n * @param value - Whether the bit should be set.\n * @returns Updated bigint.\n * @example\n * Sets single bit at position.\n *\n * ```ts\n * bitSet(0n, 1, true);\n * ```\n */\nexport function bitSet(n, pos, value) {\n if (typeof n !== 'bigint')\n throw new TypeError('\"n\" expected bigint, got type=' + typeof n);\n asafenumber(pos, 'pos');\n abool(value, 'value');\n const mask = _1n << BigInt(pos);\n // Clearing needs AND-not here; OR with zero leaves an already-set bit untouched.\n return value ? n | mask : n & ~mask;\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 * @param n - Number of bits. Negative widths are currently passed through to raw bigint shift\n * semantics and therefore produce `-1n`.\n * @returns Bitmask value.\n * @example\n * Calculate mask for N bits.\n *\n * ```ts\n * bitMask(4);\n * ```\n */\nexport const bitMask = (n) => {\n asafenumber(n, 'n');\n return (_1n << BigInt(n)) - _1n;\n};\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @param hashLen - Hash output size in bytes. Callers are expected to pass a positive length; `0`\n * is not rejected here and would make the internal generate loop non-progressing.\n * @param qByteLen - Requested output size in bytes. Callers are expected to pass a positive length.\n * @param hmacFn - HMAC implementation.\n * @returns Function that will call DRBG until the predicate returns anything\n * other than `undefined`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Build a deterministic nonce generator for RFC6979-style signing.\n *\n * ```ts\n * import { createHmacDrbg } from '@noble/curves/utils.js';\n * import { hmac } from '@noble/hashes/hmac.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hmacFn = (key: Uint8Array, msg: Uint8Array) => hmac(sha256, key, msg);\n * const drbg = createHmacDrbg(32, 32, hmacFn);\n * const seed = new Uint8Array(32);\n * drbg(seed, (bytes) => bytes);\n * ```\n */\nexport function createHmacDrbg(hashLen, qByteLen, hmacFn) {\n anumber_(hashLen, 'hashLen');\n anumber_(qByteLen, 'qByteLen');\n if (typeof hmacFn !== 'function')\n throw new TypeError('hmacFn must be a function');\n // creates Uint8Array\n const u8n = (len) => new Uint8Array(len);\n const NULL = Uint8Array.of();\n const byte0 = Uint8Array.of(0x00);\n const byte1 = Uint8Array.of(0x01);\n const _maxDrbgIters = 1000;\n // Step B, Step C: set hashLen to 8*ceil(hlen/8).\n // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 signatures.\n let v = u8n(hashLen);\n // Steps B and C of RFC6979 3.2.\n let k = u8n(hashLen);\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 // hmac(k)(v, ...values)\n const h = (...msgs) => hmacFn(k, concatBytes(v, ...msgs));\n const reseed = (seed = NULL) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(byte0, seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0)\n return;\n k = h(byte1, 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++ >= _maxDrbgIters)\n throw new Error('drbg: tried max amount of iterations');\n let len = 0;\n const out = [];\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, pred) => {\n reset();\n reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until the predicate accepts a candidate.\n // Falsy values like 0 are valid outputs.\n while ((res = pred(gen())) === undefined)\n reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n/**\n * Validates declared required and optional field types on a plain object.\n * Extra keys are intentionally ignored because many callers validate only the subset they use from\n * richer option bags or runtime objects.\n * This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct\n * one-line guards such as `aobject()`, `afunction()`, `abool()`, or `asafenumber()` instead.\n * @param object - Object to validate.\n * @param fields - Required field types.\n * @param optFields - Optional field types.\n * @param title - Object label included in thrown errors.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Check user options before building a curve helper.\n *\n * ```ts\n * validateObject({ flag: true }, { flag: 'boolean' });\n * ```\n */\nexport function validateObject(object, fields = {}, optFields = {}, title = 'object') {\n aobject(object, title);\n aobject(fields, 'fields');\n aobject(optFields, 'optFields');\n function checkField(fieldName, expectedType, isOpt) {\n const label = title === 'object' ? `param \"${String(fieldName)}\"` : `\"${title}.${String(fieldName)}\"`;\n // Config fields must be explicit own properties. Optional inherited values are rejected too\n // because callers keep reading the same options object after validation.\n const val = object[fieldName];\n // Runtime objects such as Field instances intentionally satisfy required method slots\n // via their shared prototype.\n if (!Object.hasOwn(object, fieldName) &&\n (isOpt ? val !== undefined : expectedType !== 'function')) {\n throw new TypeError(`${label} is invalid: expected own property`);\n }\n if (isOpt && val === undefined)\n return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);\n }\n const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n}\n/**\n * Throws not implemented error.\n * @returns Never returns.\n * @throws If the unfinished code path is reached. {@link Error}\n * @example\n * Surface the placeholder error from an unfinished code path.\n *\n * ```ts\n * try {\n * notImplemented();\n * } catch {}\n * ```\n */\nexport const notImplemented = () => {\n throw new Error('not implemented');\n};\n", "/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { aarray, abool, abytes, afunction, anumber, aobject, asafenumber, bitLen, bytesToNumberBE, bytesToNumberLE, numberToBytesBE, numberToBytesLE, } from \"../utils.js\";\n// Numbers aren't used in x25519 / x448 builds\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2);\n// prettier-ignore\nconst _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5);\n// prettier-ignore\nconst _7n = /* @__PURE__ */ BigInt(7), _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9);\nconst _15n = /* @__PURE__ */ BigInt(15), _16n = /* @__PURE__ */ BigInt(16);\n// 2^64: exponents below this use plain square-and-multiply in pow()/FpPow(); the windowed path's\n// table build (14 multiplications) only pays off for longer exponents (break-even ~50 bits).\nconst POW_WINDOWED_MIN = /* @__PURE__ */ BigInt('0x10000000000000000');\n/**\n * @param a - Dividend value.\n * @param b - Positive modulus.\n * @returns Reduced value in `[0, b)` only when `b` is positive.\n * @throws If the modulus is not positive. {@link Error}\n * @example\n * Normalize a bigint into one field residue.\n *\n * ```ts\n * mod(-1n, 5n);\n * ```\n */\nexport function mod(a, b) {\n if (b <= _0n)\n throw new Error('mod: expected positive modulus, got ' + b);\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to a power with modular reduction.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * Low-level helper: callers that need canonical residues must pass a valid `num` for the chosen\n * modulus instead of relying on the `power===0/1` fast paths to normalize it.\n * @param num - Base value.\n * @param power - Exponent value.\n * @param modulo - Reduction modulus.\n * @returns Modular exponentiation result.\n * @throws If the modulus or exponent is invalid. {@link Error}\n * @example\n * Raise one bigint to a modular power.\n *\n * ```ts\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n * ```\n */\nexport function pow(num, power, modulo) {\n if (modulo <= _1n)\n throw new Error('pow: expected modulus > 1, got ' + modulo);\n // Non-bigint exponents coerce every comparison below to false and would silently return 1.\n if (typeof power !== 'bigint')\n throw new TypeError('invalid exponent: expected bigint, got ' + typeof power);\n if (power < _0n)\n throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n)\n return _1n;\n if (power === _1n)\n return num;\n let d = num % modulo;\n if (d < _0n)\n d += modulo;\n // Control flow in both branches below depends only on the exponent, never on `num` \u2014 invertCt()\n // relies on that for its (public-exponent) secret-independence guarantee.\n if (power < POW_WINDOWED_MIN) {\n // Square-and-multiply: cheaper than the windowed path for short exponents.\n let p = _1n;\n while (power > _0n) {\n if (power & _1n)\n p = (p * d) % modulo;\n d = (d * d) % modulo;\n power >>= _1n;\n }\n return p;\n }\n // Fixed 4-bit windows, MSB-first: a 14-multiplication table drops per-window cost to <1\n // multiplication (vs ~2 per window for square-and-multiply), ~25-30% faster for the dense\n // 256-bit exponents of sqrt / Legendre / invertCt.\n const digits = [];\n while (power > _0n) {\n digits.push(Number(power & _15n));\n power >>= _4n;\n }\n const table = new Array(16);\n table[0] = _1n;\n table[1] = d;\n for (let i = 2; i < 16; i++)\n table[i] = (table[i - 1] * d) % modulo;\n let p = table[digits[digits.length - 1]]; // top digit is nonzero: the loop above stops on 0\n for (let w = digits.length - 2; w >= 0; w--) {\n p = (p * p) % modulo;\n p = (p * p) % modulo;\n p = (p * p) % modulo;\n p = (p * p) % modulo;\n const digit = digits[w];\n if (digit !== 0)\n p = (p * table[digit]) % modulo;\n }\n return p;\n}\n/**\n * Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)`.\n * Low-level helper: callers that need canonical residues must pass a valid `x` for the chosen\n * modulus; the `power===0` fast path intentionally returns the input unchanged.\n * @param x - Base value.\n * @param power - Number of squarings.\n * @param modulo - Reduction modulus.\n * @returns Repeated-squaring result.\n * @throws If the exponent is negative. {@link Error}\n * @example\n * Apply repeated squaring inside one field.\n *\n * ```ts\n * pow2(3n, 2n, 11n);\n * ```\n */\nexport function pow2(x, power, modulo) {\n if (modulo <= _1n)\n throw new Error('pow2: expected modulus > 1, got ' + modulo);\n if (power < _0n)\n throw new Error('pow2: expected non-negative exponent, got ' + power);\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.\n * Implemented using the {@link https://brilliant.org/wiki/extended-euclidean-algorithm/ | extended Euclidean algorithm}.\n * @param number - Value to invert.\n * @param modulo - Modulus greater than 1.\n * @returns Multiplicative inverse.\n * @throws If the modulus is invalid or the inverse does not exist. {@link Error}\n * @example\n * Compute one modular inverse with the extended Euclidean algorithm.\n *\n * ```ts\n * invert(3n, 11n);\n * ```\n */\nexport function invert(number, modulo) {\n if (number === _0n)\n throw new Error('invert: expected non-zero number');\n // modulo = 1 is the zero ring: gcd(x, 1) = 1 makes the loop below \"succeed\" and return the\n // useless inverse 0. Reject it like pow() and invertCt() do.\n if (modulo <= _1n)\n throw new Error('invert: expected modulus > 1, got ' + modulo);\n // This is variable-time: the loop count depends on `number`. For a secret-independent\n // (Fermat) alternative over a prime modulus, see {@link invertCt} (~4x slower).\n let a = mod(number, modulo);\n let b = modulo;\n // Only the B\u00E9zout coefficient of `number` (x/u chain) is tracked; the coefficient of `modulo`\n // never affects the output, so it is not computed.\n // prettier-ignore\n let x = _0n, u = _1n;\n while (a !== _0n) {\n const q = b / a;\n const r = b - a * q;\n const m = x - u * q;\n // prettier-ignore\n b = a, a = r, x = u, u = m;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n/**\n * Inverses number over modulo using Fermat's little theorem: `a^(p-2) \u2261 a\u207B\u00B9 (mod p)`.\n *\n * Unlike {@link invert} (extended Euclidean), the exponent `p-2` is a public constant, so the\n * underlying square-and-multiply has the same control flow for every secret `a`: there is no\n * data-dependent branching or loop count that could leak `a` through timing (e.g. Minerva-style\n * ECDSA nonce-inversion attacks). This is only \"algorithmically\" constant-time \u2014 JS bigint\n * multiplication/reduction is still value-dependent \u2014 and it is roughly 4x slower than\n * {@link invert}.\n *\n * REQUIRES a prime modulus; Fermat's theorem does not hold otherwise. The result is verified to be\n * a real inverse, so a non-prime modulus (or a non-invertible input) fails closed with an error\n * instead of returning a wrong value.\n * @param a - Value to invert.\n * @param prime - Prime modulus.\n * @returns Multiplicative inverse in `[1, prime)`.\n * @throws If the modulus is below 2, the input reduces to zero, or the inverse does not exist.\n * {@link Error}\n * @example\n * Compute one modular inverse without secret-dependent branching.\n *\n * ```ts\n * invertCt(3n, 11n); // 4n, since 3 * 4 = 12 \u2261 1 (mod 11)\n * ```\n */\nexport function invertCt(a, prime) {\n if (prime <= _1n)\n throw new Error('invertCt: expected prime modulus > 1, got ' + prime);\n const an = mod(a, prime);\n if (an === _0n)\n throw new Error('invertCt: expected non-zero number');\n // Exponent (prime - 2) is public, so FpPow's square-and-multiply is secret-independent.\n const inverse = pow(an, prime - _2n, prime);\n // O(1) safety net: verifies the inverse and rejects composite moduli where a^(p-2) is not one.\n if (mod(an * inverse, prime) !== _1n)\n throw new Error('invertCt: does not exist');\n return inverse;\n}\nfunction assertIsSquare(Fp, root, n) {\n const F = Fp;\n if (!F.eql(F.sqr(root), n))\n throw new Error('Cannot find square root');\n}\n// The Legendre symbol and every sqrt variant here are only defined over an odd (prime) modulus.\n// An even ORDER makes their integer divisions \u2014 (p-1)/2, (p+1)/4, (p-5)/8, (p+7)/16 \u2014 truncate and\n// silently return a wrong result, so reject it explicitly at the entry points instead. This is a\n// cheap necessary-condition check, not a primality test (composite odd moduli are caught later by\n// the Legendre-result / assertIsSquare checks).\nfunction aoddModulus(order, fnName) {\n if ((order & _1n) === _0n)\n throw new Error(fnName + ': expected odd modulus, got ' + order);\n}\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4(Fp, n) {\n const F = Fp;\n const p1div4 = (F.ORDER + _1n) / _4n;\n const root = F.pow(n, p1div4);\n assertIsSquare(F, root, n);\n return root;\n}\n// Equivalent `q = 5 (mod 8)` square-root formula (Atkin-style), not the RFC Appendix I.2 CMOV\n// pseudocode verbatim.\nfunction sqrt5mod8(Fp, n) {\n const F = Fp;\n const p5div8 = (F.ORDER - _5n) / _8n;\n const n2 = F.mul(n, _2n);\n const v = F.pow(n2, p5div8);\n const nv = F.mul(n, v);\n const i = F.mul(F.mul(nv, _2n), v);\n const root = F.mul(nv, F.sub(i, F.ONE));\n assertIsSquare(F, root, n);\n return root;\n}\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P) {\n const Fp_ = Field(P);\n const tn = tonelliShanks(P);\n const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n const c3 = tn(Fp_, Fp_.neg(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 return ((Fp, n) => {\n const F = Fp;\n let tv1 = F.pow(n, c4); // 1. tv1 = x^c4\n let tv2 = F.mul(tv1, c1); // 2. tv2 = c1 * tv1\n const tv3 = F.mul(tv1, c2); // 3. tv3 = c2 * tv1\n const tv4 = F.mul(tv1, c3); // 4. tv4 = c3 * tv1\n const e1 = F.eql(F.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n const e2 = F.eql(F.sqr(tv3), n); // 6. e2 = (tv3^2) == x\n tv1 = F.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n tv2 = F.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n const e3 = F.eql(F.sqr(tv2), n); // 9. e3 = (tv2^2) == x\n const root = F.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2\n assertIsSquare(F, root, n);\n return root;\n });\n}\n/**\n * Tonelli-Shanks square root search algorithm.\n * This implementation is variable-time: it searches data-dependently for the first non-residue `Z`\n * and for the smallest `i` in the main loop, unlike RFC 9380 Appendix I.4's constant-time shape.\n * 1. {@link https://eprint.iacr.org/2012/685.pdf | eprint 2012/685}, page 12\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * @param P - field order\n * @returns function that takes field Fp (created from P) and number n\n * @throws If the field is too small, non-prime, or the square root does not exist. {@link Error}\n * @example\n * Construct a square-root helper for primes that need Tonelli-Shanks.\n *\n * ```ts\n * import { Field, tonelliShanks } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const sqrt = tonelliShanks(17n)(Fp, 4n);\n * ```\n */\nexport function tonelliShanks(P) {\n // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n)\n throw new Error('sqrt is not defined for small field');\n aoddModulus(P, 'tonelliShanks');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000)\n throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1)\n return sqrt3mod4;\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp, n) {\n const F = Fp;\n if (F.is0(n))\n return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(F, n) !== 1)\n throw new Error('Cannot find square root');\n // Initialize variables for the main loop\n let M = S;\n let c = F.mul(F.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = F.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = F.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n // Main loop\n // while t != 1\n while (!F.eql(t, F.ONE)) {\n // Unreachable over a genuine field (no zero divisors; n=0 already returned above). A zero t\n // means composite ORDER, where a fabricated root would be wrong: fail closed instead.\n if (F.is0(t))\n throw new Error('Cannot find square root: probably non-prime P');\n let i = 1;\n // Find the smallest i >= 1 such that t^(2^i) \u2261 1 (mod P)\n let t_tmp = F.sqr(t); // t^(2^1)\n while (!F.eql(t_tmp, F.ONE)) {\n i++;\n t_tmp = F.sqr(t_tmp); // t^(2^2)...\n if (i === M)\n throw new Error('Cannot find square root');\n }\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = F.pow(c, exponent); // b = 2^(M - i - 1)\n // Update variables\n M = i;\n c = F.sqr(b); // c = b^2\n t = F.mul(t, c); // t = (t * b^2)\n R = F.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P \u2261 3 (mod 4)\n * 2. P \u2261 5 (mod 8)\n * 3. P \u2261 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * 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 choose a root by oddness\n * (used for hash-to-curve).\n * @param P - Field order.\n * @returns Square-root helper. The generic fallback inherits Tonelli-Shanks' variable-time\n * behavior and this selector assumes prime-field-style integer moduli.\n * @throws If the field is unsupported or the square root does not exist. {@link Error}\n * @example\n * Choose the square-root helper appropriate for one field modulus.\n *\n * ```ts\n * import { Field, FpSqrt } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const sqrt = FpSqrt(17n)(Fp, 4n);\n * ```\n */\nexport function FpSqrt(P) {\n aoddModulus(P, 'Fp.sqrt');\n // P \u2261 3 (mod 4) => \u221An = n^((P+1)/4)\n if (P % _4n === _3n)\n return sqrt3mod4;\n // P \u2261 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n)\n return sqrt5mod8;\n // P \u2261 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n if (P % _16n === _9n)\n return sqrt9mod16(P);\n // Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n/**\n * @param num - Value to inspect.\n * @param modulo - Field modulus.\n * @returns `true` when the least-significant little-endian bit is set.\n * @throws If the modulus is invalid for `mod(...)`. {@link Error}\n * @example\n * Inspect the low bit used by little-endian sign conventions.\n *\n * ```ts\n * isNegativeLE(3n, 11n);\n * ```\n */\nexport const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;\n// prettier-ignore\n// Arithmetic-only subset checked by validateField(). This is intentionally not the full runtime\n// IField contract: helpers like `isValidNot0`, `invertBatch`, `toBytes`, `fromBytes`, `cmov`, and\n// field-specific extras like `isOdd` are left to the callers that actually need them.\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n];\n/**\n * @param field - Field implementation.\n * @returns Validated field. This only checks the arithmetic subset needed by generic helpers; it\n * does not guarantee full runtime-method coverage for serialization, batching, `cmov`, or\n * field-specific extras beyond positive `BYTES` / `BITS`.\n * @throws If the field shape or numeric metadata are invalid. {@link Error}\n * @example\n * Check that a field implementation exposes the operations curve code expects.\n *\n * ```ts\n * import { Field, validateField } from '@noble/curves/abstract/modular.js';\n * const Fp = validateField(Field(17n));\n * ```\n */\nexport function validateField(field) {\n aobject(field, 'field');\n if (typeof field.ORDER !== 'bigint')\n throw new TypeError('param \"ORDER\" is invalid: expected bigint, got ' + typeof field.ORDER);\n // Runtime field implementations must expose real integer byte/bit sizes; fractional / NaN /\n // infinite metadata breaks encoders and caches.\n asafenumber(field.BYTES, 'BYTES');\n asafenumber(field.BITS, 'BITS');\n for (const name of FIELD_FIELDS)\n afunction(field[name], 'field.' + name);\n // Runtime field implementations must expose positive byte/bit sizes; zero leaks through the\n // numeric shape checks above but still breaks encoding helpers and cached-length assumptions.\n if (field.BYTES < 1 || field.BITS < 1)\n throw new Error('invalid field: expected BYTES/BITS > 0');\n if (field.ORDER <= _1n)\n throw new Error('invalid field: expected ORDER > 1, got ' + field.ORDER);\n return field;\n}\n// Generic field functions\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @param Fp - Field implementation.\n * @param num - Base value.\n * @param power - Exponent value.\n * @returns Powered field element.\n * @throws If the exponent is negative. {@link Error}\n * @example\n * Raise one field element to a public exponent.\n *\n * ```ts\n * import { Field, FpPow } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const x = FpPow(Fp, 3n, 5n);\n * ```\n */\nexport function FpPow(Fp, num, power) {\n validateField(Fp);\n const F = Fp;\n // Non-bigint exponents (e.g. an accidental field element) coerce every comparison below to\n // false and would silently return ONE.\n if (typeof power !== 'bigint')\n throw new TypeError('invalid exponent: expected bigint, got ' + typeof power);\n if (power < _0n)\n throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n)\n return F.ONE;\n if (power === _1n)\n return num;\n if (power < POW_WINDOWED_MIN) {\n // Square-and-multiply: cheaper than the windowed path for short exponents (e.g. poseidon\n // sbox x^5), which would waste the 14-multiplication table build.\n let p = F.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n)\n p = F.mul(p, d);\n d = F.sqr(d);\n power >>= _1n;\n }\n return p;\n }\n // Fixed 4-bit windows, MSB-first \u2014 same shape as pow() above, over generic field ops.\n // Speeds up dense long exponents (extension-field sqrt / Legendre, e.g. Fp2 decompression).\n const digits = [];\n while (power > _0n) {\n digits.push(Number(power & _15n));\n power >>= _4n;\n }\n const table = new Array(16);\n table[0] = F.ONE;\n table[1] = num;\n for (let i = 2; i < 16; i++)\n table[i] = F.mul(table[i - 1], num);\n let p = table[digits[digits.length - 1]]; // top digit is nonzero: the loop above stops on 0\n for (let w = digits.length - 2; w >= 0; w--) {\n p = F.sqr(F.sqr(F.sqr(F.sqr(p))));\n const digit = digits[w];\n if (digit !== 0)\n p = F.mul(p, table[digit]);\n }\n return p;\n}\nexport function FpInvertBatch(Fp, nums, passZero = false) {\n validateField(Fp);\n aarray(nums, 'nums');\n abool(passZero, 'passZero');\n const F = Fp;\n const inverted = new Array(nums.length).fill(passZero ? F.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (F.is0(num))\n return acc;\n inverted[i] = acc;\n return F.mul(acc, num);\n }, F.ONE);\n // Invert last element\n const invertedAcc = F.inv(multipliedAcc);\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))\n return acc;\n // Non-zero `num` means the forward pass already stored a defined prefix product at index i.\n inverted[i] = F.mul(acc, inverted[i]);\n return F.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n/**\n * @param Fp - Field implementation.\n * @param lhs - Dividend value.\n * @param rhs - Divisor value.\n * @returns Division result.\n * @throws If the divisor is non-invertible. {@link Error}\n * @example\n * Divide one field element by another.\n *\n * ```ts\n * import { Field, FpDiv } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const x = FpDiv(Fp, 6n, 3n);\n * ```\n */\nexport function FpDiv(Fp, lhs, rhs) {\n validateField(Fp);\n const F = Fp;\n return F.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, F.ORDER) : F.inv(rhs));\n}\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\n * * (a | p) \u2261 1 if a is a square (mod p), quadratic residue\n * * (a | p) \u2261 -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) \u2261 0 if a \u2261 0 (mod p)\n * @param Fp - Field implementation.\n * @param n - Value to inspect.\n * @returns Legendre symbol.\n * @throws If the powered value does not match a valid Legendre symbol. {@link Error}\n * @example\n * Compute the Legendre symbol of one field element.\n *\n * ```ts\n * import { Field, FpLegendre } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const symbol = FpLegendre(Fp, 4n);\n * ```\n */\nexport function FpLegendre(Fp, n) {\n validateField(Fp);\n const F = Fp;\n aoddModulus(F.ORDER, 'FpLegendre');\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (F.ORDER - _1n) / _2n;\n const powered = F.pow(n, p1mod2);\n const yes = F.eql(powered, F.ONE);\n const zero = F.eql(powered, F.ZERO);\n const no = F.eql(powered, F.neg(F.ONE));\n if (!yes && !zero && !no)\n throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n/**\n * @param Fp - Field implementation.\n * @param n - Value to inspect.\n * @returns `true` when `Fp.sqrt(n)` exists. This includes `0`, even though strict \"quadratic\n * residue\" terminology often reserves that name for the non-zero square class.\n * @throws If the field returns an invalid Legendre symbol value. {@link Error}\n * @example\n * Check whether one field element has a square root in the field.\n *\n * ```ts\n * import { Field, FpIsSquare } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const isSquare = FpIsSquare(Fp, 4n);\n * ```\n */\nexport function FpIsSquare(Fp, n) {\n const l = FpLegendre(Fp, n);\n // Zero is a square too: 0 = 0^2, and Fp.sqrt(0) already returns 0.\n return l !== -1;\n}\n/**\n * @param n - Curve order. Callers are expected to pass a positive order.\n * @param nBitLength - Optional cached bit length. Callers are expected to pass a positive cached\n * value when overriding the derived bit length.\n * @returns Byte and bit lengths.\n * @throws If the order or cached bit length is invalid. {@link Error}\n * @example\n * Measure the encoding sizes needed for one modulus.\n *\n * ```ts\n * nLength(255n);\n * ```\n */\nexport function nLength(n, nBitLength) {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined)\n anumber(nBitLength);\n if (n <= _0n)\n throw new Error('invalid n length: expected positive n, got ' + n);\n if (nBitLength !== undefined && nBitLength < 1)\n throw new Error('invalid n length: expected positive bit length, got ' + nBitLength);\n const bits = bitLen(n);\n // Cached bit lengths smaller than ORDER would truncate serialized scalars/elements and poison\n // any math that relies on the derived field metadata.\n if (nBitLength !== undefined && nBitLength < bits)\n throw new Error(`invalid n length: expected nBitLength (${nBitLength}) >= bitLen(n) (${bits})`);\n const _nBitLength = nBitLength !== undefined ? nBitLength : bits;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n// Keep the lazy sqrt cache off-instance so Field(...) can return a frozen object. Otherwise the\n// cached helper write would keep the field surface externally mutable.\nconst FIELD_SQRT = new WeakMap();\nclass _Field {\n ORDER;\n BITS;\n BYTES;\n isLE;\n ZERO = _0n;\n ONE = _1n;\n _lengths;\n _mod;\n constructor(ORDER, opts = {}) {\n // ORDER <= 1 is degenerate: ONE would not be a valid field element and helpers like pow/inv\n // would stop modeling field arithmetic.\n if (ORDER <= _1n)\n throw new Error('invalid field: expected ORDER > 1, got ' + ORDER);\n let _nbitLength = undefined;\n this.isLE = false;\n if (opts != null && typeof opts === 'object') {\n // Cached bit lengths are trusted here and should already be positive / consistent with ORDER.\n if (typeof opts.BITS === 'number')\n _nbitLength = opts.BITS;\n if (typeof opts.sqrt === 'function')\n // `_Field.prototype` is frozen below, so custom sqrt hooks must become own properties\n // explicitly instead of relying on writable prototype shadowing via assignment.\n Object.defineProperty(this, 'sqrt', { value: opts.sqrt, enumerable: true });\n if (typeof opts.isLE === 'boolean')\n this.isLE = opts.isLE;\n if (opts.allowedLengths)\n this._lengths = Object.freeze(opts.allowedLengths.slice());\n if (typeof opts.modFromBytes === 'boolean')\n this._mod = opts.modFromBytes;\n }\n const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);\n if (nByteLength > 2048)\n throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n this.ORDER = ORDER;\n this.BITS = nBitLength;\n this.BYTES = nByteLength;\n Object.freeze(this);\n }\n create(num) {\n return mod(num, this.ORDER);\n }\n isValid(num) {\n if (typeof num !== 'bigint')\n throw new TypeError('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < this.ORDER; // 0 is valid element, but it's not invertible\n }\n is0(num) {\n return num === _0n;\n }\n // is valid and invertible\n isValidNot0(num) {\n return !this.is0(num) && this.isValid(num);\n }\n isOdd(num) {\n return (num & _1n) === _1n;\n }\n neg(num) {\n return mod(-num, this.ORDER);\n }\n eql(lhs, rhs) {\n return lhs === rhs;\n }\n sqr(num) {\n return mod(num * num, this.ORDER);\n }\n add(lhs, rhs) {\n return mod(lhs + rhs, this.ORDER);\n }\n sub(lhs, rhs) {\n return mod(lhs - rhs, this.ORDER);\n }\n mul(lhs, rhs) {\n return mod(lhs * rhs, this.ORDER);\n }\n pow(num, power) {\n return pow(num, power, this.ORDER);\n }\n div(lhs, rhs) {\n return mod(lhs * invert(rhs, this.ORDER), this.ORDER);\n }\n // Same as above, but doesn't normalize\n sqrN(num) {\n return num * num;\n }\n addN(lhs, rhs) {\n return lhs + rhs;\n }\n subN(lhs, rhs) {\n return lhs - rhs;\n }\n mulN(lhs, rhs) {\n return lhs * rhs;\n }\n inv(num) {\n return invert(num, this.ORDER);\n }\n sqrt(num) {\n // Caching sqrt helpers speeds up sqrt9mod16 by 5x and Tonelli-Shanks by about 10% without keeping\n // the field instance itself mutable.\n let sqrt = FIELD_SQRT.get(this);\n if (!sqrt)\n FIELD_SQRT.set(this, (sqrt = FpSqrt(this.ORDER)));\n return sqrt(this, num);\n }\n toBytes(num) {\n // Serialize fixed-width limbs without re-validating the field range. Callers that need a\n // canonical encoding must pass a valid element; some protocols intentionally serialize raw\n // residues here and reduce or validate them elsewhere.\n return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);\n }\n fromBytes(bytes, skipValidation = false) {\n abytes(bytes);\n const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;\n if (allowedLengths) {\n // `allowedLengths` must list real positive byte lengths; otherwise empty input would get\n // padded into zero and silently decode as a field element.\n if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);\n }\n const padded = new Uint8Array(BYTES);\n // isLE add 0 to right, !isLE to the left.\n padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n bytes = padded;\n }\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n if (modFromBytes)\n scalar = mod(scalar, ORDER);\n if (!skipValidation)\n if (!this.isValid(scalar))\n throw new Error('invalid field element: outside of range 0..ORDER');\n // Range validation is optional here because some protocols intentionally decode raw residues\n // and reduce or validate them elsewhere.\n return scalar;\n }\n // TODO: we don't need it here, move out to separate fn\n invertBatch(lst) {\n // `passZero` keeps the `bigint[]` contract honest: zero inputs map to `0` instead of leaking\n // `undefined` into a `bigint[]`. Callers that must distinguish non-invertible inputs should use\n // `FpInvertBatch` directly, whose default omits `passZero` and returns `(bigint | undefined)[]`.\n return FpInvertBatch(this, lst, true);\n }\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov(a, b, condition) {\n // Field elements have `isValid(...)`; the CMOV branch bit is a direct runtime input, so reject\n // non-boolean selectors here instead of letting JS truthiness silently change arithmetic.\n abool(condition, 'condition');\n return condition ? b : a;\n }\n}\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. Frozen stable object shape; the lazy sqrt cache lives in a module-level `WeakMap`.\n * Fragile: always run a benchmark on a change.\n * Security note: operations and low-level serializers like `toBytes` don't check `isValid` for\n * all elements for performance and protocol-flexibility reasons; callers are responsible for\n * supplying valid elements when they need canonical field behavior.\n * This is low-level code, please make sure you know what you're doing.\n *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER - field order, probably prime, or could be composite\n * @param opts - Field options such as bit length or endianness. See {@link FieldOpts}.\n * @returns Frozen field instance with a stable object shape. This wrapper forwards `opts` straight\n * into `_Field`, so it inherits `_Field`'s assumptions about cached sizes and `allowedLengths`.\n * @example\n * Construct one prime field with optional overrides.\n *\n * ```ts\n * Field(11n);\n * ```\n */\nexport function Field(ORDER, opts = {}) {\n // Freeze the shared method surface before any instance is reachable; otherwise callers can\n // poison every Field instance by monkey-patching `_Field.prototype` even if each instance is\n // frozen. Freezing here instead of module scope keeps `_Field` tree-shakeable for importers\n // that never construct a field; the call is idempotent and cheap.\n Object.freeze(_Field.prototype);\n return new _Field(ORDER, opts);\n}\n/**\n * @param Fp - Field implementation.\n * @param elm - Value to square-root.\n * @returns Odd square root when two roots exist. The special case `elm = 0` still returns `0`,\n * which is the only square root but is not odd.\n * @throws If the field lacks oddness checks or the square root does not exist. {@link Error}\n * @example\n * Select the odd square root when two roots exist.\n *\n * ```ts\n * import { Field, FpSqrtOdd } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const root = FpSqrtOdd(Fp, 4n);\n * ```\n */\nexport function FpSqrtOdd(Fp, elm) {\n validateField(Fp);\n const F = Fp;\n if (!F.isOdd)\n throw new Error(\"Field doesn't have isOdd\");\n const root = F.sqrt(elm);\n return F.isOdd(root) ? root : F.neg(root);\n}\n/**\n * @param Fp - Field implementation.\n * @param elm - Value to square-root.\n * @returns Even square root.\n * @throws If the field lacks oddness checks or the square root does not exist. {@link Error}\n * @example\n * Select the even square root when two roots exist.\n *\n * ```ts\n * import { Field, FpSqrtEven } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const root = FpSqrtEven(Fp, 4n);\n * ```\n */\nexport function FpSqrtEven(Fp, elm) {\n validateField(Fp);\n const F = Fp;\n if (!F.isOdd)\n throw new Error(\"Field doesn't have isOdd\");\n const root = F.sqrt(elm);\n return F.isOdd(root) ? F.neg(root) : root;\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. Callers are expected to pass an\n * order greater than 1.\n * @returns byte length of field\n * @throws If the field order is not a bigint. {@link Error}\n * @example\n * Read the fixed-width byte length of one field.\n *\n * ```ts\n * getFieldBytesLength(255n);\n * ```\n */\nexport function getFieldBytesLength(fieldOrder) {\n if (typeof fieldOrder !== 'bigint')\n throw new Error('field order must be bigint');\n // Valid field elements are in 0..ORDER-1, so ORDER <= 1 would make the encoded range degenerate.\n if (fieldOrder <= _1n)\n throw new Error('field order must be greater than 1');\n // Valid field elements are < ORDER, so the maximal encoded element is ORDER - 1.\n const bitLength = bitLen(fieldOrder - _1n);\n return Math.ceil(bitLength / 8);\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 * This is the reduction / modulo-bias lower bound; higher-level helpers may still impose a larger\n * absolute floor for policy reasons.\n * @param fieldOrder - number of field elements greater than 1, usually CURVE.n.\n * @returns byte length of target hash\n * @throws If the field order is invalid. {@link Error}\n * @example\n * Compute the minimum hash length needed for field reduction.\n *\n * ```ts\n * getMinHashLength(255n);\n * ```\n */\nexport function getMinHashLength(fieldOrder) {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\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. The implementation also keeps a hard\n * 16-byte minimum even when `getMinHashLength(...)` is smaller, so toy-small inputs do not look\n * accidentally acceptable for real scalar derivation.\n * See {@link https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ | Kudelski's modulo-bias guide},\n * {@link https://csrc.nist.gov/publications/detail/fips/186/5/final | FIPS 186-5 appendix A.2}, and\n * {@link https://www.rfc-editor.org/rfc/rfc9380#section-5 | RFC 9380 section 5}. Unlike RFC 9380\n * `hash_to_field`, this helper intentionally maps into the non-zero private-scalar range `1..n-1`.\n * @param key - Uniform input bytes.\n * @param fieldOrder - Size of subgroup.\n * @param isLE - interpret hash bytes as LE num\n * @returns valid private scalar\n * @throws If the hash length or field order is invalid for scalar reduction. {@link Error}\n * @example\n * Map hash output into a private scalar range.\n *\n * ```ts\n * mapHashToField(new Uint8Array(48).fill(1), 255n);\n * ```\n */\nexport function mapHashToField(key, fieldOrder, isLE = false) {\n abytes(key);\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = Math.max(getMinHashLength(fieldOrder), 16);\n // No toy-small inputs: the helper is for real scalar derivation, not tiny test curves. No huge\n // inputs: easier to reason about JS timing / allocation behavior.\n if (len < minLen || len > 1024)\n throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n // Map into the non-zero scalar range [1, fieldOrder-1]: reduce mod (fieldOrder-1) to land in\n // [0, fieldOrder-2], then add 1. This shifts the range off zero; it is NOT equal to\n // `mod(num, fieldOrder)` (which spans [0, fieldOrder-1] and can be 0). A residual modulo bias\n // remains but is negligible (~2^-(nBits/2), e.g. ~2^-128 for a 256-bit order) because `key` is\n // required to be at least `getMinHashLength(fieldOrder)` (~1.5x field size) bytes of input.\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n", "/**\n * Experimental implementation of NTT / FFT (Fast Fourier Transform) over finite fields.\n * API may change at any time. The code has not been audited. Feature requests are welcome.\n * @module\n */\nimport { aarray, validateObject } from \"../utils.js\";\nimport { validateField } from \"./modular.js\";\nfunction checkU32(n, title = 'n') {\n // 0xff_ff_ff_ff\n if (typeof n !== 'number')\n throw new TypeError(`wrong u32 integer \"${title}\": expected number, got type=${typeof n}`);\n if (!Number.isSafeInteger(n) || n < 0 || n > 0xffffffff)\n throw new RangeError(`wrong u32 integer \"${title}\": expected 0..4294967295, got ${n}`);\n return n;\n}\n/**\n * Checks if integer is in form of `1 << X`.\n * @param x - Integer to inspect.\n * @returns `true` when the value is a power of two.\n * @example\n * Validate that an FFT size is a power of two.\n *\n * ```ts\n * isPowerOfTwo(8);\n * ```\n */\nexport function isPowerOfTwo(x) {\n checkU32(x, 'x');\n return (x & (x - 1)) === 0 && x !== 0;\n}\n/**\n * @param n - Input value.\n * @returns Next power of two within the u32/array-length domain.\n * @throws If `n` is not a valid unsigned 32-bit integer. {@link Error}\n * @example\n * Round an integer up to the FFT size it needs.\n *\n * ```ts\n * nextPowerOfTwo(9);\n * ```\n */\nexport function nextPowerOfTwo(n) {\n checkU32(n);\n if (n <= 1)\n return 1;\n // FFT sizes here are used as JS array lengths, so `2^32` is not a meaningful result:\n // keep the fast u32 bit-twiddling path and fail explicitly instead of wrapping to 1.\n if (n > 0x8000_0000)\n throw new Error('nextPowerOfTwo overflow: result does not fit u32');\n return (1 << (log2(n - 1) + 1)) >>> 0;\n}\n/**\n * @param n - Value to reverse.\n * @param bits - Number of bits to use.\n * @returns Bit-reversed integer.\n * @throws If `n` is not a valid unsigned 32-bit integer. {@link Error}\n * @example\n * Reverse the low `bits` bits of one index.\n *\n * ```ts\n * reverseBits(3, 3);\n * ```\n */\nexport function reverseBits(n, bits) {\n checkU32(n);\n if (typeof bits !== 'number')\n throw new TypeError('\"bits\" expected number, got type=' + typeof bits);\n if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32)\n throw new Error(`expected integer 0 <= bits <= 32, got ${bits}`);\n let reversed = 0;\n for (let i = 0; i < bits; i++, n >>>= 1)\n reversed = (reversed << 1) | (n & 1);\n // JS bitwise ops are signed i32; cast back so 32-bit reversals stay in the unsigned u32 domain.\n return reversed >>> 0;\n}\n/**\n * Similar to `bitLen(x)-1` but much faster for small integers, like indices.\n * @param n - Input value.\n * @returns Base-2 logarithm. For `n = 0`, the current implementation returns `-1`.\n * @example\n * Compute the radix-2 stage count for one transform size.\n *\n * ```ts\n * log2(8);\n * ```\n */\nexport function log2(n) {\n checkU32(n);\n return 31 - Math.clz32(n);\n}\n/**\n * Moves lowest bit to highest position, which at first step splits\n * array on even and odd indices, then it applied again to each part,\n * which is core of fft\n * @param values - Mutable coefficient array.\n * @returns Mutated input array.\n * @throws If the array length is not a positive power of two. {@link Error}\n * @example\n * Reorder coefficients into bit-reversed order in place.\n *\n * ```ts\n * const values = Uint8Array.from([0, 1, 2, 3]);\n * bitReversalInplace(values);\n * ```\n */\nexport function bitReversalInplace(values) {\n if (!values ||\n typeof values !== 'object' ||\n typeof values.length !== 'number')\n throw new TypeError('\"values\" expected array-like, got type=' + typeof values);\n const n = values.length;\n // Size-1 FFT is the identity, so bit-reversal must stay a no-op there instead of rejecting it.\n if (!isPowerOfTwo(n))\n throw new Error('expected positive power-of-two length, got ' + n);\n const bits = log2(n);\n for (let i = 0; i < n; i++) {\n const j = reverseBits(i, bits);\n if (i < j) {\n const tmp = values[i];\n values[i] = values[j];\n values[j] = tmp;\n }\n }\n return values;\n}\n/**\n * @param values - Input values.\n * @returns Reordered copy.\n * @throws If the array length is not a positive power of two. {@link Error}\n * @example\n * Return a reordered copy instead of mutating the input in place.\n *\n * ```ts\n * const reordered = bitReversalPermutation([0, 1, 2, 3]);\n * ```\n */\nexport function bitReversalPermutation(values) {\n aarray(values, 'values');\n return bitReversalInplace(values.slice());\n}\nconst _1n = /** @__PURE__ */ BigInt(1);\nfunction findGenerator(field) {\n let G = BigInt(2);\n for (; field.eql(field.pow(G, field.ORDER >> _1n), field.ONE); G++)\n ;\n return G;\n}\n/**\n * We limit roots up to 2**31, which is a lot: 2-billion polynomial should be rare.\n * @param field - Field implementation.\n * @param generator - Optional trusted non-quadratic-residue override for callers that already know the field.\n * @returns Roots-of-unity cache.\n * @example\n * Cache roots once, then ask for the omega table of one FFT size.\n *\n * ```ts\n * import { rootsOfUnity } from '@noble/curves/abstract/fft.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const roots = rootsOfUnity(Field(17n));\n * const omega = roots.omega(4);\n * ```\n */\nexport function rootsOfUnity(field, generator) {\n validateField(field);\n if (generator !== undefined && typeof generator !== 'bigint')\n throw new TypeError('\"generator\" expected bigint, got type=' + typeof generator);\n // Factor field.ORDER-1 as oddFactor * 2^powerOfTwo\n let oddFactor = field.ORDER - _1n;\n let powerOfTwo = 0;\n for (; (oddFactor & _1n) !== _1n; powerOfTwo++, oddFactor >>= _1n)\n ;\n // Find non quadratic residue\n let G = generator !== undefined ? BigInt(generator) : findGenerator(field);\n // Powers of generator\n const omegas = new Array(powerOfTwo + 1);\n omegas[powerOfTwo] = field.pow(G, oddFactor);\n for (let i = powerOfTwo; i > 0; i--)\n omegas[i - 1] = field.sqr(omegas[i]);\n // Compute all roots of unity for powers up to maxPower\n const rootsCache = [];\n const checkBits = (bits) => {\n checkU32(bits, 'bits');\n if (bits > 31 || bits > powerOfTwo)\n throw new Error('rootsOfUnity: wrong bits ' + bits + ' powerOfTwo=' + powerOfTwo);\n return bits;\n };\n const precomputeRoots = (maxPower) => {\n checkBits(maxPower);\n for (let power = maxPower; power >= 0; power--) {\n if (rootsCache[power])\n continue; // Skip if we've already computed roots for this power\n const above = rootsCache[power + 1];\n const rootsAtPower = [];\n if (above) {\n // \u03C9_{2^p} = \u03C9_{2^{p+1}}\u00B2, so the smaller table is the even-index stride of the bigger\n // one: only the largest requested power pays for the multiplication chain.\n for (let j = 0; j < 2 ** power; j++)\n rootsAtPower.push(above[2 * j]);\n }\n else {\n for (let j = 0, cur = field.ONE; j < 2 ** power; j++, cur = field.mul(cur, omegas[power]))\n rootsAtPower.push(cur);\n }\n rootsCache[power] = rootsAtPower;\n }\n return rootsCache[maxPower];\n };\n const brpCache = new Map();\n const inverseCache = new Map();\n // roots()/brp()/inverse() expose shared cached arrays by reference for speed; callers must treat them as read-only.\n // NOTE: we use bits instead of power, because power = 2**bits,\n // but power is not necessarily isPowerOfTwo(power)!\n return {\n info: { G, powerOfTwo, oddFactor },\n roots: (bits) => {\n const b = checkBits(bits);\n return precomputeRoots(b);\n },\n brp(bits) {\n const b = checkBits(bits);\n if (brpCache.has(b))\n return brpCache.get(b);\n else {\n const res = bitReversalPermutation(this.roots(b));\n brpCache.set(b, res);\n return res;\n }\n },\n inverse(bits) {\n const b = checkBits(bits);\n if (inverseCache.has(b))\n return inverseCache.get(b);\n else {\n // \u03C9\u1D3A = 1, so inv(\u03C9\u1D4F) = \u03C9\u1D3A\u207B\u1D4F: the inverse table is the reversed roots table.\n // Value-identical to field.invertBatch(roots), but skips its 3N muls + inversion.\n const r = this.roots(b);\n const res = [r[0]].concat(r.slice(1).reverse());\n inverseCache.set(b, res);\n return res;\n }\n },\n omega: (bits) => omegas[checkBits(bits)],\n clear: () => {\n rootsCache.splice(0, rootsCache.length);\n brpCache.clear();\n inverseCache.clear();\n },\n };\n}\n/**\n * Constructs different flavors of FFT. radix2 implementation of low level mutating API. Flavors:\n *\n * - DIT (Decimation-in-Time): Bottom-Up (leaves to root), Cooley-Tukey\n * - DIF (Decimation-in-Frequency): Top-Down (root to leaves), Gentleman-Sande\n *\n * DIT takes brp input, returns natural output.\n * DIF takes natural input, returns brp output.\n *\n * The output is actually identical. Time / frequence distinction is not meaningful\n * for Polynomial multiplication in fields.\n * Which means if protocol supports/needs brp output/inputs, then we can skip this step.\n *\n * Cyclic NTT: Rq = Zq[x]/(x^n-1). butterfly_DIT+loop_DIT OR butterfly_DIF+loop_DIT, roots are omega\n * Negacyclic NTT: Rq = Zq[x]/(x^n+1). butterfly_DIT+loop_DIF, at least for mlkem / mldsa\n *\n * `invertButterflies` indexes roots by a per-butterfly-group counter (`grp`): forward\n * (`dit: false`) reads `roots[grp]` with grp = 1..; inverse (`dit: true`) reads `roots[N - grp]`\n * with grp restarting at 1. With `skipStages: 0` one table serves both directions (\u03C9\u1D3A = 1 makes\n * the reversed walk self-inverse). With `skipStages > 0` the inverse walk starts at `N - 1`\n * instead of continuing where the skipped stages would have left off, so the caller must supply\n * a table shaped for that (ML-KEM: `\u03B6^BitRev7(i)` over all N=256 indices, whose aliased upper\n * half is exactly the FIPS 203 inverse walk).\n * @param F - Field operations.\n * @param coreOpts - FFT configuration. See {@link FFTCoreOpts}:\n * - `N`: Transform size. Must be a power of two.\n * - `roots`: Stage roots for the selected transform size.\n * - `dit`: Whether to run the DIT variant instead of DIF.\n * - `invertButterflies` (optional): Whether to invert butterfly placement.\n * - `skipStages` (optional): Number of initial stages to skip.\n * - `brp` (optional): Whether to apply bit-reversal permutation at the boundary.\n * @returns Low-level FFT loop.\n * @throws If the FFT options or cached roots are invalid for the requested size. {@link Error}\n * @example\n * Constructs different flavors of FFT.\n *\n * ```ts\n * import { FFTCore, rootsOfUnity } from '@noble/curves/abstract/fft.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const roots = rootsOfUnity(Fp).roots(2);\n * const loop = FFTCore(Fp, { N: 4, roots, dit: true });\n * const values = loop([1n, 2n, 3n, 4n]);\n * ```\n */\nexport const FFTCore = (F, coreOpts) => {\n validateObject(coreOpts, { N: 'number', roots: 'object', dit: 'boolean' }, { invertButterflies: 'boolean', skipStages: 'number', brp: 'boolean' }, 'coreOpts');\n const { N, roots, dit, invertButterflies = false, skipStages = 0, brp = true } = coreOpts;\n checkU32(N, 'coreOpts.N');\n const bits = log2(N);\n if (!isPowerOfTwo(N))\n throw new Error('FFT: Polynomial size should be power of two');\n checkU32(skipStages, 'coreOpts.skipStages');\n const maxSkipStages = bits === 0 ? 0 : bits - 1;\n // Skipping every stage leaves only boundary layout changes, not a valid FFT loop shape.\n if (skipStages > maxSkipStages)\n throw new Error(`FFT: wrong skipStages: expected 0 <= skipStages <= ${maxSkipStages}`);\n // Wrong-sized root tables can stay in-bounds for some loop shapes and silently compute nonsense.\n if (roots.length !== N)\n throw new Error(`FFT: wrong roots length: expected ${N}, got ${roots.length}`);\n const isDit = dit !== invertButterflies;\n return (values) => {\n if (values.length !== N)\n throw new Error('FFT: wrong Polynomial length');\n if (dit && brp)\n bitReversalInplace(values);\n for (let i = 0, g = 1; i < bits - skipStages; i++) {\n // For each stage s (sub-FFT length m = 2^s)\n const s = dit ? i + 1 + skipStages : bits - i;\n const m = 1 << s;\n const m2 = m >> 1;\n const stride = N >> s;\n // Loop over each subarray of length m\n for (let k = 0; k < N; k += m) {\n // Loop over each butterfly within the subarray\n for (let j = 0, grp = g++; j < m2; j++) {\n const rootPos = invertButterflies ? (dit ? N - grp : grp) : j * stride;\n const i0 = k + j;\n const i1 = k + j + m2;\n const omega = roots[rootPos];\n const b = values[i1];\n const a = values[i0];\n // Inlining gives us 10% perf in kyber vs functions\n if (isDit) {\n const t = F.mul(b, omega); // Standard DIT butterfly\n values[i0] = F.add(a, t);\n values[i1] = F.sub(a, t);\n }\n else if (invertButterflies) {\n values[i0] = F.add(b, a); // DIT loop + inverted butterflies (Kyber decode)\n values[i1] = F.mul(F.sub(b, a), omega);\n }\n else {\n values[i0] = F.add(a, b); // Standard DIF butterfly\n values[i1] = F.mul(F.sub(a, b), omega);\n }\n }\n }\n }\n if (!dit && brp)\n bitReversalInplace(values);\n return values;\n };\n};\n/**\n * NTT aka FFT over finite field (NOT over complex numbers).\n * Naming mirrors other libraries.\n * @param roots - Roots-of-unity cache.\n * @param opts - Field operations. See {@link FFTOpts}.\n * @returns Forward and inverse FFT helpers.\n * @example\n * NTT aka FFT over finite field (NOT over complex numbers).\n *\n * ```ts\n * import { FFT, rootsOfUnity } from '@noble/curves/abstract/fft.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const fft = FFT(rootsOfUnity(Fp), Fp);\n * const values = fft.direct([1n, 2n, 3n, 4n]);\n * ```\n */\nexport function FFT(roots, opts) {\n // Loops are cached per (size, direction, brp flags): FFTCore construction validates options\n // and allocates closures, which costs more than a small transform itself. The cached loop\n // closes over the root table active at first use; `roots.clear()` rebuilds value-identical\n // tables, so a stale reference stays correct.\n const loops = new Map();\n const getLoop = (N, rootsTable, key) => {\n const cached = loops.get(key);\n if (cached)\n return cached;\n const brpInput = !!(key & 2);\n const brpOutput = !!(key & 1);\n let loop;\n if (brpInput && brpOutput) {\n // we cannot optimize this case, but lets support it anyway\n const core = FFTCore(opts, { N, roots: rootsTable, dit: false, brp: false });\n loop = (values) => core(bitReversalInplace(values));\n }\n else if (brpInput)\n loop = FFTCore(opts, { N, roots: rootsTable, dit: true, brp: false });\n else if (brpOutput)\n loop = FFTCore(opts, { N, roots: rootsTable, dit: false, brp: false });\n else\n loop = FFTCore(opts, { N, roots: rootsTable, dit: true, brp: true }); // all natural\n loops.set(key, loop);\n return loop;\n };\n const loopKey = (bits, isInverse, brpInput, brpOutput) => (bits << 3) | (isInverse ? 4 : 0) | (brpInput ? 2 : 0) | (brpOutput ? 1 : 0);\n return {\n direct(values, brpInput = false, brpOutput = false) {\n const N = values.length;\n if (!isPowerOfTwo(N))\n throw new Error('FFT: Polynomial size should be power of two');\n const bits = log2(N);\n const key = loopKey(bits, false, brpInput, brpOutput);\n return getLoop(N, roots.roots(bits), key)(values.slice());\n },\n inverse(values, brpInput = false, brpOutput = false) {\n const N = values.length;\n if (!isPowerOfTwo(N))\n throw new Error('FFT: Polynomial size should be power of two');\n const bits = log2(N);\n const key = loopKey(bits, true, brpInput, brpOutput);\n const res = getLoop(N, roots.inverse(bits), key)(values.slice());\n const ivm = opts.inv(BigInt(values.length)); // scale\n // we can get brp output if we use dif instead of dit!\n for (let i = 0; i < res.length; i++)\n res[i] = opts.mul(res[i], ivm);\n // Allows to re-use non-inverted roots, but is VERY fragile\n // return [res[0]].concat(res.slice(1).reverse());\n // inverse calculated as pow(-1), which transforms into \u03C9^{-kn} (-> reverses indices)\n return res;\n },\n };\n}\nexport function poly(field, roots, create, fft, length) {\n validateField(field);\n const F = field;\n const _create = create ||\n ((len, elm) => new Array(len).fill(elm ?? F.ZERO));\n // `poly.mul(a, b)` distinguishes polynomial-vs-scalar at runtime, so keep accepted\n // polynomial containers concrete instead of trying to support arbitrary wrappers.\n const isPoly = (x) => {\n if (Array.isArray(x))\n return true;\n if (!ArrayBuffer.isView(x))\n return false;\n const v = x;\n return (typeof v.length === 'number' &&\n typeof v.slice === 'function' &&\n typeof v[Symbol.iterator] === 'function');\n };\n const checkPoly = (title, value) => {\n if (!isPoly(value))\n throw new TypeError(`\"${title}\" expected polynomial, got type=${typeof value}`);\n };\n const checkLength = (a, b) => {\n checkPoly('a', a);\n const L = a.length;\n if (b !== undefined) {\n checkPoly('b', b);\n if (b.length !== L)\n throw new Error(`poly: mismatched lengths ${L} vs ${b.length}`);\n }\n if (length !== undefined && L !== length)\n throw new Error(`poly: expected fixed length ${length}, got ${L}`);\n return L;\n };\n function findOmegaIndex(x, n, brp = false, weights) {\n if (!isPowerOfTwo(n))\n throw new Error('poly.lagrange: expected power of two length, got ' + n);\n // Explicit weights define the interpolation domain, including the Kronecker-\u03B4 shortcut.\n const omega = weights || (brp ? roots.brp(log2(n)) : roots.roots(log2(n)));\n for (let i = 0; i < n; i++)\n if (F.eql(x, omega[i]))\n return i;\n return -1;\n }\n // TODO: mutating versions for mlkem/mldsa\n return {\n roots,\n create: _create,\n length,\n extend: (a, len) => {\n checkLength(a);\n const out = _create(len, F.ZERO);\n // Plain arrays grow when writing past `out.length`, so cap the copy explicitly to keep\n // `extend()` consistent with typed arrays and with its documented truncate behavior.\n for (let i = 0; i < Math.min(a.length, len); i++)\n out[i] = a[i];\n return out;\n },\n degree: (a) => {\n checkLength(a);\n for (let i = a.length - 1; i >= 0; i--)\n if (!F.is0(a[i]))\n return i;\n return -1;\n },\n add: (a, b) => {\n const len = checkLength(a, b);\n const out = _create(len);\n for (let i = 0; i < len; i++)\n out[i] = F.add(a[i], b[i]);\n return out;\n },\n sub: (a, b) => {\n const len = checkLength(a, b);\n const out = _create(len);\n for (let i = 0; i < len; i++)\n out[i] = F.sub(a[i], b[i]);\n return out;\n },\n dot: (a, b) => {\n const len = checkLength(a, b);\n const out = _create(len);\n for (let i = 0; i < len; i++)\n out[i] = F.mul(a[i], b[i]);\n return out;\n },\n mul: (a, b) => {\n if (isPoly(b)) {\n const len = checkLength(a, b);\n if (fft) {\n const A = fft.direct(a, false, true);\n const B = fft.direct(b, false, true);\n for (let i = 0; i < A.length; i++)\n A[i] = F.mul(A[i], B[i]);\n return fft.inverse(A, true, false);\n }\n else {\n // NOTE: this is quadratic and mostly for compat tests with FFT\n const res = _create(len);\n for (let i = 0; i < len; i++) {\n for (let j = 0; j < len; j++) {\n const k = (i + j) % len; // wrap mod length\n res[k] = F.add(res[k], F.mul(a[i], b[j]));\n }\n }\n return res;\n }\n }\n else {\n const out = _create(checkLength(a));\n for (let i = 0; i < out.length; i++)\n out[i] = F.mul(a[i], b);\n return out;\n }\n },\n convolve(a, b) {\n checkPoly('a', a);\n checkPoly('b', b);\n const len = nextPowerOfTwo(a.length + b.length - 1);\n return this.mul(this.extend(a, len), this.extend(b, len));\n },\n shift(p, factor) {\n checkPoly('p', p);\n const out = _create(p.length);\n if (length !== undefined && p.length !== length)\n throw new Error(`poly: expected fixed length ${length}, got ${p.length}`);\n if (!p.length)\n return out;\n out[0] = p[0];\n for (let i = 1, power = F.ONE; i < p.length; i++) {\n power = F.mul(power, factor);\n out[i] = F.mul(p[i], power);\n }\n return out;\n },\n clone: (a) => {\n checkLength(a);\n const out = _create(a.length);\n for (let i = 0; i < a.length; i++)\n out[i] = a[i];\n return out;\n },\n eval: (a, basis) => {\n checkLength(a, basis);\n let acc = F.ZERO;\n for (let i = 0; i < a.length; i++)\n acc = F.add(acc, F.mul(a[i], basis[i]));\n return acc;\n },\n monomial: {\n basis: (x, n) => {\n const out = _create(n);\n let pow = F.ONE;\n for (let i = 0; i < n; i++) {\n out[i] = pow;\n pow = F.mul(pow, x);\n }\n return out;\n },\n eval: (a, x) => {\n checkLength(a);\n // Same as eval(a, monomialBasis(x, a.length)), but it is faster this way\n let acc = F.ZERO;\n for (let i = a.length - 1; i >= 0; i--)\n acc = F.add(F.mul(acc, x), a[i]);\n return acc;\n },\n },\n lagrange: {\n basis: (x, n, brp = false, weights) => {\n if (!isPowerOfTwo(n))\n throw new Error('poly.lagrange: expected power of two length, got ' + n);\n const bits = log2(n);\n const cache = weights || (brp ? roots.brp(bits) : roots.roots(bits)); // [\u03C9\u2070, \u03C9\u00B9, ..., \u03C9\u207F\u207B\u00B9]\n const out = _create(n);\n // Fast Kronecker-\u03B4 shortcut\n const idx = findOmegaIndex(x, n, brp, weights);\n if (idx !== -1) {\n out[idx] = F.ONE;\n return out;\n }\n const tm = F.pow(x, BigInt(n));\n const c = F.mul(F.sub(tm, F.ONE), F.inv(BigInt(n))); // c = (x\u207F - 1)/n\n const denom = _create(n);\n for (let i = 0; i < n; i++)\n denom[i] = F.sub(x, cache[i]);\n const inv = F.invertBatch(denom);\n for (let i = 0; i < n; i++)\n out[i] = F.mul(c, F.mul(cache[i], inv[i]));\n return out;\n },\n eval(a, x, brp = false) {\n checkLength(a);\n const idx = findOmegaIndex(x, a.length, brp);\n if (idx !== -1)\n return a[idx]; // fast path\n const L = this.basis(x, a.length, brp); // L\u1D62(x)\n let acc = F.ZERO;\n for (let i = 0; i < a.length; i++)\n if (!F.is0(a[i]))\n acc = F.add(acc, F.mul(a[i], L[i]));\n return acc;\n },\n },\n vanishing(roots) {\n checkPoly('roots', roots);\n if (length !== undefined && roots.length !== length)\n throw new Error(`poly: expected fixed length ${length}, got ${roots.length}`);\n const out = _create(roots.length + 1, F.ZERO);\n out[0] = F.ONE;\n for (const r of roots) {\n const neg = F.neg(r);\n for (let j = out.length - 1; j > 0; j--)\n out[j] = F.add(F.mul(out[j], neg), out[j - 1]);\n out[0] = F.mul(out[0], neg);\n }\n return out;\n },\n };\n}\n", "/**\n * Utilities for hex, bytearray and number handling.\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { abytes, abytes as abytes_, ahash as ahash_, anumber, bytesToHex, concatBytes, isBytes, isLE, randomBytes as randb, } from '@noble/hashes/utils.js';\n/**\n * Asserts that a value is a byte array and optionally checks its length.\n * Returns the original reference unchanged on success, and currently also accepts Node `Buffer`\n * values through the upstream validator.\n * This helper throws on malformed input, so APIs that must return `false` need to guard lengths\n * before decoding or before calling it.\n * @example\n * Validate that a value is a byte array with the expected length.\n * ```ts\n * abytes(new Uint8Array([1]), 1);\n * ```\n */\nconst abytesDoc = abytes;\nexport { abytesDoc as abytes };\n/**\n * Concatenates byte arrays into a new `Uint8Array`.\n * Zero arguments return an empty `Uint8Array`.\n * Invalid segments throw before allocation because each argument is validated first.\n * @example\n * Concatenate two byte arrays into one result.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nconst concatBytesDoc = concatBytes;\nexport { concatBytesDoc as concatBytes };\n/**\n * Returns cryptographically secure random bytes.\n * Requires `globalThis.crypto.getRandomValues` and throws if that API is unavailable.\n * `bytesLength` is validated by the upstream helper as a non-negative integer before allocation,\n * so negative and fractional values both throw instead of truncating through JS `ToIndex`.\n * @param bytesLength - Number of random bytes to generate.\n * @returns Fresh random bytes.\n * @example\n * Generate a fresh random seed.\n * ```ts\n * const seed = randomBytes(4);\n * ```\n */\nexport const randomBytes = randb;\nexport function aarray(item, title, inner = () => { }) {\n if (!Array.isArray(item))\n throw new TypeError(`\"${title}\" expected array, got type=${typeof item}`);\n for (let i = 0; i < item.length; i++)\n inner(item[i], `${title}[${i}]`);\n return item;\n}\nexport function aobject(value, title = 'object') {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n throw new TypeError(title === 'object'\n ? 'expected valid options object'\n : `\"${title}\" expected object, got type=${typeof value}`);\n return value;\n}\n/**\n * Compares two byte arrays in a length-constant way for equal lengths.\n * Inputs are validated as byte arrays; unequal lengths return `false` immediately.\n * @param a - First byte array.\n * @param b - Second byte array.\n * @returns Whether both arrays contain the same bytes.\n * @example\n * Compare two byte arrays for equality.\n * ```ts\n * equalBytes(new Uint8Array([1]), new Uint8Array([1]));\n * ```\n */\nexport function equalBytes(a, b) {\n a = abytes(a);\n b = abytes(b);\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * Copies bytes into a fresh `Uint8Array`.\n * Returns a detached plain `Uint8Array` after validating that the input is real bytes.\n * @param bytes - Source bytes.\n * @returns Copy of the input bytes.\n * @example\n * Copy bytes into a fresh array.\n * ```ts\n * copyBytes(new Uint8Array([1, 2]));\n * ```\n */\nexport function copyBytes(bytes) {\n // The typed-array constructor copies a typed-array source through its internal byte storage.\n // Unlike `Uint8Array.from`, it does not invoke a subclass-overridden iterator. Keep the explicit\n // validation because the constructor itself would also accept arrays and other typed arrays.\n return new Uint8Array(abytes(bytes));\n}\n/**\n * Byte-swaps each 64-bit lane in place.\n * Falcon's exact binary64 tables are stored as little-endian byte payloads, so BE runtimes need\n * this boundary helper before aliasing them as host `Float64Array` lanes.\n * @param arr - Byte buffer whose length is a multiple of 8.\n * @returns The same buffer after in-place 64-bit lane byte swaps.\n * @example\n * Byte-swap one 64-bit lane in place.\n * ```ts\n * byteSwap64(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]));\n * ```\n */\nexport function byteSwap64(arr) {\n const bytes = new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n for (let i = 0; i < bytes.length; i += 8) {\n const a0 = bytes[i + 0];\n const a1 = bytes[i + 1];\n const a2 = bytes[i + 2];\n const a3 = bytes[i + 3];\n bytes[i + 0] = bytes[i + 7];\n bytes[i + 1] = bytes[i + 6];\n bytes[i + 2] = bytes[i + 5];\n bytes[i + 3] = bytes[i + 4];\n bytes[i + 4] = a3;\n bytes[i + 5] = a2;\n bytes[i + 6] = a1;\n bytes[i + 7] = a0;\n }\n return arr;\n}\n/**\n * Byte-swaps 64-bit lanes on big-endian runtimes and returns the input unchanged on little-endian.\n * This keeps Falcon's binary64 tables in canonical little-endian order before aliasing them as\n * `Float64Array` lanes on the current host.\n * @param arr - Buffer to pass through or swap in place.\n * @returns The same buffer, normalized for Falcon's little-endian table layout.\n * @example\n * Normalize one host-endian buffer for Falcon's float tables.\n * ```ts\n * baswap64If(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]));\n * ```\n */\nexport const baswap64If = isLE\n ? (arr) => arr\n : byteSwap64;\n/**\n * Validates that an options bag is a plain object.\n * @param opts - Options object to validate.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate that an options bag is a plain object.\n * ```ts\n * validateOpts({});\n * ```\n */\nexport function validateOpts(opts) {\n // Arrays silently passed here before, but these call sites expect named option-bag fields.\n if (isBytes(opts))\n throw new TypeError('\"opts\" expected object, got Uint8Array');\n aobject(opts, 'opts');\n const proto = Object.getPrototypeOf(opts);\n // Options are security parameters, not general class instances. Restricting the bag to own\n // properties prevents values injected through Object.prototype (or a custom shared prototype)\n // from silently changing signing behavior. Null-prototype records remain supported.\n if (proto !== null && proto !== Object.prototype)\n throw new TypeError('\"opts\" expected a plain object');\n}\n// Frozen because they are exported: an unfrozen array export lets anything in the\n// process push a key onto the accepted set and silently re-open exactly the hole this\n// validation closes.\n/** Keys accepted by `verify`. */\nexport const VER_OPT_KEYS = /* @__PURE__ */ Object.freeze([\n 'context',\n]);\n/** Keys accepted by `sign`. */\nexport const SIG_OPT_KEYS = /* @__PURE__ */ Object.freeze([\n 'context',\n 'extraEntropy',\n]);\n/**\n * Rejects option keys the caller did not mean to set.\n *\n * Validating the types of known keys while ignoring unknown ones makes a typo\n * indistinguishable from an omission, and for these options an omission is a\n * security downgrade rather than a no-op: `{ ctx }` instead of `{ context }` signs\n * with no domain separation, succeeds, and verifies for anyone who also supplies\n * none. Nothing at any layer reports it. TypeScript catches this through excess\n * property checks, so the exposure is JavaScript callers specifically.\n *\n * @param opts - Options object to check.\n * @param allowed - The keys this call site accepts.\n * Returns a frozen null-prototype snapshot so later reads cannot fall through to a polluted\n * prototype. Like `checkOpts()` in noble-hashes, only enumerable own properties are copied.\n * @throws If any other copied key is present or the bag has a custom prototype. {@link TypeError}\n * @returns Sanitized snapshot of the enumerable own options.\n * @example\n * Accept a known option key. A key the list does not name, such as `ctx`, throws instead.\n * ```ts\n * import { checkOptKeys } from '@noble/post-quantum/utils.js';\n * checkOptKeys({ context: new Uint8Array() }, ['context']);\n * ```\n */\nexport function checkOptKeys(opts, allowed) {\n validateOpts(opts);\n // Snapshot once before validation: Object.assign follows the same own-enumerable option-bag\n // semantics as noble-hashes, while the null prototype keeps omitted fields immune to pollution.\n const normalized = Object.assign(Object.create(null), opts);\n for (const [k, v] of Object.entries(normalized)) {\n // `undefined` means unset everywhere else in these validators, and building an options bag by\n // spread is a normal way to reach these calls, so present-but-undefined stays equivalent to\n // omission.\n if (v === undefined)\n continue;\n if (!allowed.includes(k))\n throw new TypeError('unexpected option \"' + String(k) + '\"; expected one of: ' + allowed.join(', '));\n }\n return Object.freeze(normalized);\n}\n/**\n * Validates common verification options.\n * `context` itself is validated with `abytes(...)`, and individual algorithms may narrow support\n * further after this shared plain-object gate.\n * @param opts - Verification options. See {@link VerOpts}.\n * @param allowed - Keys this call site accepts. Defaults to {@link VER_OPT_KEYS}; surfaces that\n * take extra keys, or take fewer, pass their own list.\n * @throws On wrong argument types. {@link TypeError}\n * @returns Frozen null-prototype snapshot of the validated options.\n * @example\n * Validate common verification options.\n * ```ts\n * validateVerOpts({ context: new Uint8Array([1]) });\n * ```\n */\nexport function validateVerOpts(opts, allowed = VER_OPT_KEYS) {\n const normalized = checkOptKeys(opts, allowed);\n if (normalized.context !== undefined)\n abytes(normalized.context, undefined, 'opts.context');\n return normalized;\n}\n/**\n * Validates common signing options.\n * `extraEntropy` is validated with `abytes(...)`; exact lengths and extra algorithm-specific\n * restrictions are enforced later by callers.\n * @param opts - Signing options. See {@link SigOpts}.\n * @param allowed - Keys this call site accepts. Defaults to {@link SIG_OPT_KEYS}; surfaces that\n * take extra keys, or take fewer, pass their own list.\n * @throws On wrong argument types. {@link TypeError}\n * @returns Frozen null-prototype snapshot of the validated options.\n * @example\n * Validate common signing options.\n * ```ts\n * validateSigOpts({ extraEntropy: new Uint8Array([1]) });\n * ```\n */\nexport function validateSigOpts(opts, allowed = SIG_OPT_KEYS) {\n const normalized = checkOptKeys(opts, allowed);\n if (normalized.context !== undefined)\n abytes(normalized.context, undefined, 'opts.context');\n if (normalized.extraEntropy !== false && normalized.extraEntropy !== undefined)\n abytes(normalized.extraEntropy, undefined, 'opts.extraEntropy');\n return normalized;\n}\n/**\n * Builds a fixed-layout coder from byte lengths and nested coders.\n * Raw-length fields decode as zero-copy `subarray(...)` views, and nested coders may preserve that\n * aliasing too. Nested coder `encode(...)` results are treated as owned scratch: `splitCoder`\n * copies them into the output and then zeroizes them with `fill(0)`. If a nested encoder forwards\n * caller-owned bytes, it must do so only after detaching them into a disposable copy.\n * @param label - Label used in validation errors.\n * @param lengths - Field lengths or nested coders.\n * @returns Composite fixed-length coder.\n * @example\n * Build a fixed-layout coder from byte lengths and nested coders.\n * ```ts\n * splitCoder('demo', 1, 2).encode([new Uint8Array([1]), new Uint8Array([2, 3])]);\n * ```\n */\nexport function splitCoder(label, ...lengths) {\n const getLength = (c) => typeof c === 'number' ? c : c.bytesLen;\n const bytesLen = lengths.reduce((sum, a) => sum + getLength(a), 0);\n return {\n bytesLen,\n encode: (bufs) => {\n const res = new Uint8Array(bytesLen);\n for (let i = 0, pos = 0; i < lengths.length; i++) {\n const c = lengths[i];\n const l = getLength(c);\n const b = typeof c === 'number' ? bufs[i] : c.encode(bufs[i]);\n abytes_(b, l, label);\n res.set(b, pos);\n if (typeof c !== 'number')\n b.fill(0); // clean\n pos += l;\n }\n return res;\n },\n decode: (buf) => {\n abytes_(buf, bytesLen, label);\n const res = [];\n for (const c of lengths) {\n const l = getLength(c);\n const b = buf.subarray(0, l);\n res.push(typeof c === 'number' ? b : c.decode(b));\n buf = buf.subarray(l);\n }\n return res;\n },\n };\n}\n// nano-packed.array (fixed size)\n/**\n * Builds a fixed-length vector coder from another fixed-length coder.\n * Element decoding receives `subarray(...)` views, so aliasing depends on the element coder.\n * Element coder `encode(...)` results are treated as owned scratch: `vecCoder` copies them into\n * the output and then zeroizes them with `fill(0)`. If an element encoder forwards caller-owned\n * bytes, it must do so only after detaching them into a disposable copy. `vecCoder` also trusts\n * the `BytesCoderLen` contract: each encoded element must already be exactly `c.bytesLen` bytes.\n * @param c - Element coder.\n * @param vecLen - Number of elements in the vector.\n * @returns Fixed-length vector coder.\n * @example\n * Build a fixed-length vector coder from another fixed-length coder.\n * ```ts\n * vecCoder(\n * { bytesLen: 1, encode: (n: number) => Uint8Array.of(n), decode: (b: Uint8Array) => b[0] || 0 },\n * 2\n * ).encode([1, 2]);\n * ```\n */\nexport function vecCoder(c, vecLen) {\n const coder = c;\n const bytesLen = vecLen * coder.bytesLen;\n return {\n bytesLen,\n encode: (u) => {\n const uArr = aarray(u, 'u');\n if (uArr.length !== vecLen)\n throw new RangeError(`vecCoder.encode: wrong length=${uArr.length}. Expected: ${vecLen}`);\n const res = new Uint8Array(bytesLen);\n for (let i = 0, pos = 0; i < uArr.length; i++) {\n const b = coder.encode(uArr[i]);\n res.set(b, pos);\n b.fill(0); // clean\n pos += b.length;\n }\n return res;\n },\n decode: (a) => {\n abytes_(a, bytesLen);\n const r = [];\n for (let i = 0; i < a.length; i += coder.bytesLen)\n r.push(coder.decode(a.subarray(i, i + coder.bytesLen)));\n return r;\n },\n };\n}\n/**\n * Overwrites supported typed-array inputs with zeroes in place.\n * Accepts direct typed arrays and one-level arrays of them.\n * @param list - Typed arrays or one-level lists of typed arrays to clear.\n * @example\n * Overwrite typed arrays with zeroes.\n * ```ts\n * const buf = Uint8Array.of(1, 2, 3);\n * cleanBytes(buf);\n * ```\n */\nexport function cleanBytes(...list) {\n for (const t of list) {\n if (Array.isArray(t))\n for (const b of t)\n b.fill(0);\n else\n t.fill(0);\n }\n}\n/**\n * Creates a 32-bit mask with the lowest `bits` bits set.\n * @param bits - Number of low bits to keep.\n * @returns Bit mask with `bits` ones.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Create a low-bit mask for packed-field operations.\n * ```ts\n * const mask = getMask(4);\n * ```\n */\nexport function getMask(bits) {\n anumber(bits, 'bits');\n if (bits > 32)\n throw new RangeError('\"bits\" expected <= 32, got ' + bits);\n // JS shifts are modulo 32, so bit 32 needs an explicit full-width mask.\n return bits === 32 ? 0xffffffff : ~(-1 << bits) >>> 0;\n}\n/** Shared empty byte array used as the default context. */\nexport const EMPTY = /* @__PURE__ */ Uint8Array.of();\n/**\n * Builds the domain-separated message payload for the pure sign/verify paths.\n * Context length `255` is valid; only `ctx.length > 255` is rejected.\n * @param msg - Message bytes.\n * @param ctx - Optional context bytes.\n * @returns Domain-separated message payload.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Build the domain-separated payload before direct signing.\n * ```ts\n * const payload = getMessage(new Uint8Array([1, 2]));\n * ```\n */\nexport function getMessage(msg, ctx = EMPTY) {\n abytes_(msg, undefined, 'msg');\n abytes_(ctx, undefined, 'ctx');\n if (ctx.length > 255)\n throw new RangeError('context should be 255 bytes or less');\n return concatBytes(new Uint8Array([0, ctx.length]), ctx, msg);\n}\n// DER tag+length plus the shared NIST hash OID arc 2.16.840.1.101.3.4.2.* used by the\n// FIPS 204 / FIPS 205 pre-hash wrappers; the final byte selects SHA-256, SHA-512, SHAKE128,\n// SHAKE256, or another approved hash/XOF under that subtree.\n// 06 09 60 86 48 01 65 03 04 02\nconst oidNistP = /* @__PURE__ */ Uint8Array.from([6, 9, 0x60, 0x86, 0x48, 1, 0x65, 3, 4, 2]);\n/**\n * Output length, in bytes, that each XOF OID under this arc denotes.\n *\n * Unlike a fixed hash, an XOF's OID is a promise about the digest length: RFC 8702\n * defines id-shake128 as SHAKE128 with 256-bit output and id-shake256 as SHAKE256 with\n * 512-bit output, and FIPS 204 / FIPS 205 use exactly those pairings for pre-hash. Both\n * bare noble-hashes defaults are half these values, so neither can be signed under its\n * own OID.\n */\nconst XOF_OID_OUTPUT_LEN = /* @__PURE__ */ (() => ({\n '060960864801650304020b': 32, // id-shake128, SHAKE128(M, 256)\n '060960864801650304020c': 64, // id-shake256, SHAKE256(M, 512)\n}))();\n/**\n * Validates that a hash exposes a NIST hash OID and enough collision resistance.\n * Current accepted surface is broader than the FIPS algorithm tables: any hash/XOF under the NIST\n * `2.16.840.1.101.3.4.2.*` subtree is accepted if its effective `outputLen` is strong enough.\n * XOF callers must pass a callable whose `outputLen` matches the digest length they actually intend\n * to sign; bare `shake128` / `shake256` defaults are too short for the stronger prehash modes.\n * @param hash - Hash function to validate.\n * @param requiredStrength - Minimum required collision-resistance strength in bits.\n * @throws If the hash metadata or collision resistance is insufficient. {@link Error}\n * @example\n * Validate that a hash exposes a NIST hash OID and enough collision resistance.\n * ```ts\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { checkHash } from '@noble/post-quantum/utils.js';\n * checkHash(sha256, 128);\n * ```\n */\nexport function checkHash(hash, requiredStrength = 0) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new TypeError('\"hash\" expected hash function, got type=' + typeof hash);\n ahash_(hash);\n anumber(requiredStrength, 'requiredStrength');\n const oid = hash.oid;\n abytes_(oid, undefined, 'hash.oid');\n if (!equalBytes(oid.subarray(0, 10), oidNistP))\n throw new Error('\"hash.oid\" is invalid: expected NIST hash');\n // FIPS 204 / FIPS 205 require both collision and second-preimage strength; for approved NIST\n // hashes/XOFs under this OID subtree, the collision bound from the configured digest length is\n // the tighter runtime check, so enforce that lower bound here.\n // XOFs under this arc are identified by an OID that fixes their output length:\n // FIPS 204 \u00A75.4.1 (SHAKE128) and FIPS 205 \u00A710.2.2 (both SHAKEs), matching RFC 8702, pair\n // id-shake128 with SHAKE128(M, 256) and id-shake256 with SHAKE256(M, 512). getMessagePrehash embeds\n // hash.oid beside hash(msg), so a shorter digest signs an M' that claims a length\n // it does not have: noble-hashes' bare shake256 defaults to 32 bytes and cleared\n // the collision bound at the 128-bit level, producing signatures a conformant\n // verifier rejects because it recomputes 512 bits. Check the length the OID\n // denotes rather than the generic bound.\n const xofLen = XOF_OID_OUTPUT_LEN[bytesToHex(oid)];\n if (xofLen !== undefined && hash.outputLen !== xofLen) {\n throw new Error('Pre-hash XOF output length must be ' + xofLen + ' bytes for this OID, got: ' + hash.outputLen);\n }\n const collisionResistance = (hash.outputLen * 8) / 2;\n if (requiredStrength > collisionResistance) {\n throw new Error('Pre-hash security strength too low: ' +\n collisionResistance +\n ', required: ' +\n requiredStrength);\n }\n}\n/**\n * Builds the domain-separated prehash payload for the prehash sign/verify paths.\n * Callers are expected to vet `hash.oid` first, e.g. via `checkHash(...)`; calling this helper\n * directly with a hash object that lacks `oid` currently throws later inside `concatBytes(...)`.\n * Context length `255` is valid; only `ctx.length > 255` is rejected.\n * @param hash - Prehash function.\n * @param msg - Message bytes.\n * @param ctx - Optional context bytes.\n * @returns Domain-separated prehash payload.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Build the domain-separated prehash payload for external hashing.\n * ```ts\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { getMessagePrehash } from '@noble/post-quantum/utils.js';\n * getMessagePrehash(sha256, new Uint8Array([1, 2]));\n * ```\n */\nexport function getMessagePrehash(hash, msg, ctx = EMPTY) {\n checkHash(hash);\n abytes_(msg, undefined, 'msg');\n abytes_(ctx, undefined, 'ctx');\n if (ctx.length > 255)\n throw new RangeError('context should be 255 bytes or less');\n const hashed = hash(msg);\n return concatBytes(new Uint8Array([1, ctx.length]), ctx, hash.oid, hashed);\n}\n/**\n * Asserts something is a string.\n * @param value - Value to validate.\n * @param title - Label included in thrown errors.\n * @returns The validated string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a label string.\n *\n * ```ts\n * astring('example', 'label');\n * ```\n */\nexport function astring(value, title = '') {\n if (typeof value !== 'string') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(prefix + 'expected string, got type=' + typeof value);\n }\n return value;\n}\n", "/**\n * Internal methods for lattice-based ML-KEM and ML-DSA.\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { FFTCore, reverseBits } from '@noble/curves/abstract/fft.js';\nimport { shake128, shake256 } from '@noble/hashes/sha3.js';\nimport { cleanBytes, getMask, } from \"./utils.js\";\n/**\n * Creates shared modular arithmetic, NTT, and packing helpers for CRYSTALS schemes.\n * @param opts - Polynomial and transform parameters. See {@link CrystalOpts}.\n * @returns CRYSTALS arithmetic and encoding helpers.\n * @example\n * Create shared modular arithmetic and NTT helpers for a CRYSTALS parameter set.\n * ```ts\n * const crystals = genCrystals({\n * newPoly: (n) => new Uint16Array(n),\n * N: 256,\n * Q: 3329,\n * F: 3303,\n * ROOT_OF_UNITY: 17,\n * brvBits: 7,\n * isKyber: true,\n * });\n * const reduced = crystals.mod(-1);\n * ```\n */\nexport const genCrystals = (opts) => {\n // isKyber: true means Kyber, false means Dilithium\n const { newPoly, N, Q, F, ROOT_OF_UNITY, brvBits, isKyber } = opts;\n // Normalize JS `%` into the canonical Z_m representative `[0, modulo-1]` expected by\n // FIPS 203 \u00A72.3 / FIPS 204 \u00A72.3 before downstream mod-q arithmetic.\n const mod = (a, modulo = Q) => {\n const result = (a % modulo) | 0;\n return (result >= 0 ? result | 0 : (modulo + result) | 0) | 0;\n };\n // FIPS 204 \u00A77.4 uses the centered `mod \u00B1` representative for low bits, keeping the\n // positive midpoint when `modulo` is even.\n // Center to `[-floor((modulo-1)/2), floor(modulo/2)]`.\n const smod = (a, modulo = Q) => {\n const r = mod(a, modulo) | 0;\n return (r > modulo >> 1 ? (r - modulo) | 0 : r) | 0;\n };\n // Kyber uses the FIPS 203 Appendix A `BitRev_7` table here via the first 128 entries, while\n // Dilithium uses the FIPS 204 \u00A77.5 / Appendix B `BitRev_8` zetas table over all 256 entries.\n function getZettas() {\n const out = newPoly(N);\n for (let i = 0; i < N; i++) {\n const b = reverseBits(i, brvBits);\n const p = BigInt(ROOT_OF_UNITY) ** BigInt(b) % BigInt(Q);\n out[i] = Number(p) | 0;\n }\n return out;\n }\n const nttZetas = getZettas();\n // Number-Theoretic Transform\n // Explained: https://electricdusk.com/ntt.html\n // Kyber has slightly different params, since there is no 512th primitive root of unity mod q,\n // only 256th primitive root of unity mod. Which also complicates MultiplyNTT.\n const inv = (_a) => {\n throw new Error('not implemented');\n };\n // ML-KEM (Kyber) polynomials always enter the transform reduced to [0, Q), so add/sub only\n // need one conditional correction instead of `%`; measured ~20% faster NTT there.\n // ML-DSA keeps the generic mod() path on purpose: its first forward stage sees centered\n // (negative) coefficients, and `sub(a, t)` can drop below -Q (t is a mul output in [0, Q)),\n // so a single correction is not enough. A guarded fast path with mod() fallback was measured\n // slower than plain `%` for the 23-bit Q (V8 int32 modulo is one div; the branches lose).\n const field = isKyber\n ? {\n add: (a, b) => {\n const r = (a + b) | 0;\n return r >= Q ? (r - Q) | 0 : r;\n },\n sub: (a, b) => {\n const r = (a - b) | 0;\n return r < 0 ? (r + Q) | 0 : r;\n },\n mul: (a, b) => mod((a | 0) * (b | 0)) | 0,\n inv,\n }\n : {\n add: (a, b) => mod((a | 0) + (b | 0)) | 0,\n sub: (a, b) => mod((a | 0) - (b | 0)) | 0,\n mul: (a, b) => mod((a | 0) * (b | 0)) | 0,\n inv,\n };\n const nttOpts = {\n N,\n roots: nttZetas,\n invertButterflies: true,\n skipStages: isKyber ? 1 : 0,\n brp: false,\n };\n const dif = FFTCore(field, { dit: false, ...nttOpts });\n const dit = FFTCore(field, { dit: true, ...nttOpts });\n const NTT = {\n encode: (r) => {\n return dif(r);\n },\n decode: (r) => {\n dit(r);\n // The inverse-NTT normalization factor is family-specific: FIPS 203 Algorithm 10 line 14\n // uses `128^-1 mod q` for Kyber, while FIPS 204 Algorithm 42 lines 21-23 use `256^-1 mod q`.\n // kyber uses 128 here, because brv && stuff\n for (let i = 0; i < r.length; i++)\n r[i] = mod(F * r[i]);\n return r;\n },\n };\n // Pack one little-endian `d`-bit word per coefficient, matching FIPS 203 ByteEncode /\n // ByteDecode and the FIPS 204 BitsToBytes-based polynomial packing helpers.\n const bitsCoder = (d, c) => {\n // Validate the carry shape once: JS bitwise operations silently truncate wider accumulators.\n for (let i = 0, bufLen = 0; i < N; i++) {\n bufLen += d;\n if (bufLen > 32)\n getMask(bufLen);\n bufLen %= 8;\n }\n const mask = getMask(d);\n const bytesLen = d * (N / 8);\n return {\n bytesLen,\n encode: (poly_) => {\n const poly = poly_;\n const r = new Uint8Array(bytesLen);\n for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < poly.length; i++) {\n buf |= (c.encode(poly[i]) & mask) << bufLen;\n bufLen += d;\n // Take the low byte directly: `& 0xff` matches the previous getMask(bufLen) result\n // after Uint8Array truncation, without a validated function call per output byte.\n for (; bufLen >= 8; bufLen -= 8, buf >>= 8)\n r[pos++] = buf & 0xff;\n }\n return r;\n },\n decode: (bytes) => {\n const r = newPoly(N);\n for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < bytes.length; i++) {\n buf |= bytes[i] << bufLen;\n bufLen += 8;\n for (; bufLen >= d; bufLen -= d, buf >>= d)\n r[pos++] = c.decode(buf & mask);\n }\n return r;\n },\n };\n };\n return {\n mod,\n smod,\n nttZetas: nttZetas,\n NTT: {\n encode: (r) => NTT.encode(r),\n decode: (r) => NTT.decode(r),\n },\n bitsCoder: bitsCoder,\n };\n};\nconst createXofShake = (shake) => (seed, blockLen) => {\n if (!blockLen)\n blockLen = shake.blockLen;\n // Optimizations that won't mater:\n // - cached seed update (two .update(), on start and on the end)\n // - another cache which cloned into working copy\n // Faster than multiple updates, since seed less than blockLen\n const _seed = new Uint8Array(seed.length + 2);\n _seed.set(seed);\n const seedLen = seed.length;\n const buf = new Uint8Array(blockLen); // == shake128.blockLen\n let h = shake.create({});\n let calls = 0;\n let xofs = 0;\n return {\n stats: () => ({ calls, xofs }),\n get: (x, y) => {\n // Rebind to `seed || x || y` so callers can implement the spec's per-coordinate\n // SHAKE inputs like `rho || j || i` and `rho || IntegerToBytes(counter, 2)`.\n _seed[seedLen + 0] = x;\n _seed[seedLen + 1] = y;\n h.destroy();\n h = shake.create({}).update(_seed);\n calls++;\n return () => {\n xofs++;\n return h.xofInto(buf);\n };\n },\n clean: () => {\n h.destroy();\n cleanBytes(buf, _seed);\n },\n };\n};\n/**\n * SHAKE128-based extendable-output reader factory used by ML-KEM.\n * `get(x, y)` selects one coordinate pair at a time; calling it again invalidates previously\n * returned readers, and each squeeze reuses one mutable internal output buffer.\n * @param seed - Seed bytes for the reader.\n * @param blockLen - Optional output block length.\n * @returns Stateful XOF reader.\n * @example\n * Build the ML-KEM SHAKE128 matrix expander and read one block.\n * ```ts\n * import { randomBytes } from '@noble/post-quantum/utils.js';\n * import { XOF128 } from '@noble/post-quantum/_crystals.js';\n * const reader = XOF128(randomBytes(32));\n * const block = reader.get(0, 0)();\n * ```\n */\nexport const XOF128 = /* @__PURE__ */ createXofShake(shake128);\n/**\n * SHAKE256-based extendable-output reader factory used by ML-DSA.\n * `get(x, y)` appends raw one-byte coordinates to the seed, invalidates previously returned\n * readers, and reuses one mutable internal output buffer for each squeeze.\n * @param seed - Seed bytes for the reader.\n * @param blockLen - Optional output block length.\n * @returns Stateful XOF reader.\n * @example\n * Build the ML-DSA SHAKE256 coefficient expander and read one block.\n * ```ts\n * import { randomBytes } from '@noble/post-quantum/utils.js';\n * import { XOF256 } from '@noble/post-quantum/_crystals.js';\n * const reader = XOF256(randomBytes(32));\n * const block = reader.get(0, 0)();\n * ```\n */\nexport const XOF256 = /* @__PURE__ */ createXofShake(shake256);\n", "/**\n * ML-KEM: Module Lattice-based Key Encapsulation Mechanism from\n * [FIPS-203](https://csrc.nist.gov/pubs/fips/203/ipd). A.k.a. CRYSTALS-Kyber.\n *\n * Key encapsulation is similar to DH / ECDH (think X25519), with important differences:\n * * Unlike in ECDH, we can't verify if it was \"Bob\" who've sent the shared secret\n * * Unlike ECDH, it is probabalistic and relies on quality of randomness (CSPRNG).\n * * Decapsulation never throws an error, even when shared secret was\n * encrypted by a different public key. It will just return a different shared secret.\n *\n * There are some concerns with regards to security: see\n * [djb blog](https://blog.cr.yp.to/20231003-countcorrectly.html) and\n * [mailing list](https://groups.google.com/a/list.nist.gov/g/pqc-forum/c/W2VOzy0wz_E).\n *\n * Has similar internals to ML-DSA, but their keys and params are different.\n *\n * Check out [official site](https://www.pq-crystals.org/kyber/resources.shtml),\n * [repo](https://github.com/pq-crystals/kyber),\n * [spec](https://datatracker.ietf.org/doc/draft-cfrg-schwabe-kyber/).\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { sha3_256, sha3_512, shake256 } from '@noble/hashes/sha3.js';\nimport { swap32IfBE, u32 } from '@noble/hashes/utils.js';\nimport { genCrystals, XOF128 } from \"./_crystals.js\";\nimport { abytes, cleanBytes, copyBytes, equalBytes, getMask, randomBytes, splitCoder, vecCoder, } from \"./utils.js\";\n/** Key encapsulation mechanism interface */\nconst N = 256; // Kyber (not FIPS-203) supports different lengths, but all std modes were using 256\nconst Q = 3329; // 13*(2**8)+1, modulo prime\nconst F = 3303; // 3303 \u2261 128**(\u22121) mod q (FIPS-203)\nconst ROOT_OF_UNITY = 17; // \u03B6 = 17 \u2208 Zq is a primitive 256-th root of unity modulo Q. \u03B6**128 \u2261\u22121\n// treeshake: keep genCrystals behind the object so PARAMS-only bundles can drop it entirely.\n// Shared CRYSTALS helper in the ML-KEM branch: Kyber mode, 7-bit bit-reversal,\n// and Uint16Array polys because current coefficients stay reduced modulo q.\nconst crystals = /* @__PURE__ */ genCrystals({\n N,\n Q,\n F,\n ROOT_OF_UNITY,\n newPoly: (n) => new Uint16Array(n),\n brvBits: 7,\n isKyber: true,\n});\n/** Internal params of ML-KEM versions */\n// prettier-ignore\n/** Built-in ML-KEM parameter presets keyed by the public export names\n * `ml_kem512` / `ml_kem768` / `ml_kem1024`.\n * `RBGstrength` is Table 2's required randomness-source strength in bits,\n * not a generic security label.\n */\nexport const PARAMS = /* @__PURE__ */ (() => Object.freeze({\n 512: Object.freeze({ N, Q, K: 2, ETA1: 3, ETA2: 2, du: 10, dv: 4, RBGstrength: 128 }),\n 768: Object.freeze({ N, Q, K: 3, ETA1: 2, ETA2: 2, du: 10, dv: 4, RBGstrength: 192 }),\n 1024: Object.freeze({ N, Q, K: 4, ETA1: 2, ETA2: 2, du: 11, dv: 5, RBGstrength: 256 }),\n}))();\n// FIPS-203: compress/decompress\nconst compress = (d) => {\n // d=12 is the ByteEncode12/ByteDecode12 path, not lossy compression.\n // ByteDecode12 interprets each 12-bit word modulo q; without that reduction the public-key\n // modulus check in encapsulate() becomes a no-op for malformed coefficients like 4095.\n if (d >= 12)\n return { encode: (i) => i, decode: (i) => (i >= Q ? i - Q : i) };\n // Comments map to python implementation in RFC (draft-cfrg-schwabe-kyber)\n // const round = (i: number) => Math.floor(i + 0.5) | 0;\n const a = 2 ** (d - 1);\n return {\n // This only matches standalone Compress_d after bitsCoder masks the result into Z_(2^d).\n encode: (i) => ((i << d) + Q / 2) / Q,\n // const decompress = (i: number) => round((Q / 2 ** d) * i);\n decode: (i) => (i * Q + a) >>> d,\n };\n};\n// Raw ByteEncode_d / ByteDecode_d from FIPS 203 operate on d-bit words directly.\n// That differs from `polyCoder(d)` for d<12, where noble folds packing together with the lossy\n// ciphertext compression step used by u/v. Tests that exercise the spec's raw packing surface need\n// this exact non-lossy variant instead.\nconst byteCoder = (d) => crystals.bitsCoder(d, d === 12\n ? { encode: (i) => i, decode: (i) => (i >= Q ? i - Q : i) }\n : { encode: (i) => i, decode: (i) => i });\n// NOTE: we merge encoding and compress because it is faster, also both require same d param\n// d=12 is the ByteEncode12/ByteDecode12 path rather than compression, and caller-side\n// public-key modulus checks route through this helper's decode/encode roundtrip.\n// Converts between bytes and d-bits compressed representation.\n// Kinda like convertRadix2 from @scure/base.\n// decode(encode(t)) == t, but there is loss of information on encode(decode(t))\nconst polyCoder = (d) => (d === 12 ? byteCoder(12) : crystals.bitsCoder(d, compress(d)));\n// Coefficients always stay reduced in [0, Q) here (samplers, NTT and coders all reduce),\n// so one conditional correction replaces the generic mod().\nfunction polyAdd(a_, b_) {\n const a = a_;\n const b = b_;\n // Mutates `a` in place; callers must pass two N=256 polynomials.\n for (let i = 0; i < N; i++) {\n const r = a[i] + b[i]; // a += b\n a[i] = r >= Q ? r - Q : r;\n }\n}\nfunction polySub(a_, b_) {\n const a = a_;\n const b = b_;\n // Mutates `a` in place; callers must pass two N=256 polynomials.\n for (let i = 0; i < N; i++) {\n const r = a[i] - b[i]; // a -= b\n a[i] = r < 0 ? r + Q : r;\n }\n}\n// FIPS-203: Computes the product of two degree-one polynomials with respect to a quadratic modulus\nfunction BaseCaseMultiply(a0, a1, b0, b1, zeta) {\n // `zeta` here is Algorithm 11's \u03B3 = \u03B6^(2BitRev_7(i)+1).\n // Reduce a1*b1 before multiplying by zeta: a1*b1*zeta would reach ~2^35, forcing JS engines\n // into slow float fmod; with the extra reduction every intermediate fits int32.\n const c0 = crystals.mod(crystals.mod(a1 * b1) * zeta + a0 * b0);\n const c1 = crystals.mod(a0 * b1 + a1 * b0);\n return { c0, c1 };\n}\n// FIPS-203: Computes the product (in the ring Tq) of two NTT representations.\n// Works in place on `f`; `g` is read-only and both inputs must already be in NTT form.\nfunction MultiplyNTTs(f_, g_) {\n const f = f_;\n const g = g_;\n for (let i = 0; i < N / 2; i++) {\n let z = crystals.nttZetas[64 + (i >> 1)];\n if (i & 1)\n z = -z;\n const { c0, c1 } = BaseCaseMultiply(f[2 * i + 0], f[2 * i + 1], g[2 * i + 0], g[2 * i + 1], z);\n f[2 * i + 0] = c0;\n f[2 * i + 1] = c1;\n }\n return f;\n}\n// Return poly in NTT representation\nfunction SampleNTT(xof_) {\n const xof = xof_;\n // The reader must already bind the Algorithm 7 seed||j||i bytes\n // and return block lengths divisible by 3.\n const r = new Uint16Array(N);\n for (let j = 0; j < N;) {\n const b = xof();\n if (b.length % 3)\n throw new Error('SampleNTT: unaligned block');\n for (let i = 0; j < N && i + 3 <= b.length; i += 3) {\n const d1 = ((b[i + 0] >> 0) | (b[i + 1] << 8)) & 0xfff;\n const d2 = ((b[i + 1] >> 4) | (b[i + 2] << 4)) & 0xfff;\n if (d1 < Q)\n r[j++] = d1;\n if (j < N && d2 < Q)\n r[j++] = d2;\n }\n }\n return r;\n}\n// Sampling from the centered binomial distribution\n// Returns poly with small coefficients (noise/errors) stored modulo q in ordinary coefficient form.\n// Current callers only use Table 2 eta values {2,3} and PRF outputs of exactly 64*eta bytes.\nconst sampleCBDBytes = (buf, eta) => {\n const r = new Uint16Array(N);\n // CBD consumes the PRF bitstream in little-endian byte order; normalize the word view on BE,\n // then swap it back so callers still observe `buf` as read-only.\n const b32 = u32(buf);\n swap32IfBE(b32);\n let len = 0;\n for (let i = 0, p = 0, bb = 0, t0 = 0; i < b32.length; i++) {\n let b = b32[i];\n for (let j = 0; j < 32; j++) {\n bb += b & 1;\n b >>= 1;\n len += 1;\n if (len === eta) {\n t0 = bb;\n bb = 0;\n }\n else if (len === 2 * eta) {\n r[p++] = crystals.mod(t0 - bb);\n bb = 0;\n len = 0;\n }\n }\n }\n swap32IfBE(b32);\n if (len)\n throw new Error(`sampleCBD: leftover bits: ${len}`);\n return r;\n};\nfunction sampleCBD(PRF_, seed, nonce, eta) {\n const PRF = PRF_;\n return sampleCBDBytes(PRF((eta * N) / 4, seed, nonce), eta);\n}\n// K-PKE\n// Internal ML-KEM subroutine only: exact 32-byte `seed` / `msg` inputs\n// come from Algorithms 13-15, and the helper mutates decoded temporary\n// polynomials in place while leaving caller byte arrays unchanged.\nconst genKPKE = (opts_) => {\n const opts = opts_;\n const { K, PRF, XOF, HASH512, ETA1, ETA2, du, dv } = opts;\n const poly1 = polyCoder(1);\n const polyV = polyCoder(dv);\n const polyU = polyCoder(du);\n const publicCoder = splitCoder('publicKey', vecCoder(polyCoder(12), K), 32);\n const secretCoder = vecCoder(polyCoder(12), K);\n const cipherCoder = splitCoder('ciphertext', vecCoder(polyU, K), polyV);\n const seedCoder = splitCoder('seed', 32, 32);\n // Algorithm 14 (K-PKE.Encrypt) core, after ek parsing. `tHat` and every poly returned by\n // `getA(i, j)` are treated as disposable scratch: they are mutated in place and wiped/dropped,\n // so callers holding cached copies must pass fresh copies.\n const encryptCore = (tHat, getA, msg, seed) => {\n const rHat = [];\n for (let i = 0; i < K; i++)\n rHat.push(crystals.NTT.encode(sampleCBD(PRF, seed, i, ETA1)));\n const tmp2 = new Uint16Array(N);\n const u = [];\n for (let i = 0; i < K; i++) {\n const e1 = sampleCBD(PRF, seed, K + i, ETA2);\n const tmp = new Uint16Array(N);\n for (let j = 0; j < K; j++) {\n const aij = getA(i, j); // A[j][i], inplace transpose access\n polyAdd(tmp, MultiplyNTTs(aij, rHat[j])); // t += aij * rHat[j]\n }\n polyAdd(e1, crystals.NTT.decode(tmp)); // e1 += tmp\n u.push(e1);\n polyAdd(tmp2, MultiplyNTTs(tHat[i], rHat[i])); // t2 += tHat[i] * rHat[i]\n cleanBytes(tmp);\n }\n const e2 = sampleCBD(PRF, seed, 2 * K, ETA2);\n polyAdd(e2, crystals.NTT.decode(tmp2)); // e2 += tmp2\n const v = poly1.decode(msg); // encode plaintext m into polynomial v\n polyAdd(v, e2); // v += e2\n cleanBytes(tHat, rHat, tmp2, e2);\n return cipherCoder.encode([u, v]);\n };\n return {\n secretCoder,\n lengths: {\n secretKey: secretCoder.bytesLen,\n publicKey: publicCoder.bytesLen,\n cipherText: cipherCoder.bytesLen,\n },\n keygen: (seed) => {\n abytes(seed, 32, 'seed');\n const seedDst = new Uint8Array(33);\n seedDst.set(seed);\n // FIPS 203 Algorithm 13 appends the parameter-set byte `k`\n // before `G(d || k)`, so expanding the same 32-byte seed\n // under a different ML-KEM parameter set yields unrelated keys.\n seedDst[32] = K;\n const seedHash = HASH512(seedDst);\n const [rho, sigma] = seedCoder.decode(seedHash);\n const sHat = [];\n const tHat = [];\n for (let i = 0; i < K; i++)\n sHat.push(crystals.NTT.encode(sampleCBD(PRF, sigma, i, ETA1)));\n const x = XOF(rho);\n for (let i = 0; i < K; i++) {\n const e = crystals.NTT.encode(sampleCBD(PRF, sigma, K + i, ETA1));\n for (let j = 0; j < K; j++) {\n const aji = SampleNTT(x.get(j, i)); // A[i][j], inplace\n polyAdd(e, MultiplyNTTs(aji, sHat[j]));\n }\n tHat.push(e); // t \u2190 A \u25E6 s + e\n }\n x.clean();\n const res = {\n publicKey: publicCoder.encode([tHat, rho]),\n secretKey: secretCoder.encode(sHat),\n };\n cleanBytes(rho, sigma, sHat, tHat, seedDst, seedHash);\n return res;\n },\n encrypt: (publicKey, msg, seed) => {\n const [tHat, rho] = publicCoder.decode(publicKey);\n const x = XOF(rho);\n const res = encryptCore(tHat, (i, j) => SampleNTT(x.get(i, j)), msg, seed);\n x.clean();\n return res;\n },\n // Expands the full \u00C2 matrix (public data derived from rho) once, so repeated encryptions\n // against the same ek skip the K\u00B2 SampleNTT XOF expansions. Cached polys are copied per\n // call because encryptCore mutates its inputs in place.\n prepare: (publicKey) => {\n const [tHat, rho] = publicCoder.decode(publicKey);\n const x = XOF(rho);\n const A = [];\n for (let i = 0; i < K; i++)\n for (let j = 0; j < K; j++)\n A.push(SampleNTT(x.get(i, j)));\n x.clean();\n return {\n encrypt: (msg, seed) => encryptCore(tHat.map((p) => p.slice()), (i, j) => A[i * K + j].slice(), msg, seed),\n clean: () => cleanBytes(tHat, A),\n };\n },\n decrypt: (cipherText, privateKey) => {\n const [u, v] = cipherCoder.decode(cipherText);\n const sk = secretCoder.decode(privateKey); // s \u2190 ByteDecode_12(dkPKE)\n const tmp = new Uint16Array(N);\n // tmp += sk[i] * u[i]\n for (let i = 0; i < K; i++)\n polyAdd(tmp, MultiplyNTTs(sk[i], crystals.NTT.encode(u[i])));\n polySub(v, crystals.NTT.decode(tmp)); // w = v' - tmp\n // `v` now holds w, from which the plaintext is just a 1-bit threshold away, so wipe it too.\n // encode() allocates its own buffer, so the returned bytes do not alias `v`.\n const res = poly1.encode(v);\n cleanBytes(tmp, sk, u, v);\n return res;\n },\n };\n};\n/**\n * Public ML-KEM wrapper over the internal K-PKE subroutine.\n * `keygen(seed)` and `encapsulate(publicKey, msg)` are deterministic/test-oriented hooks that map\n * more directly to Algorithms 16-17 than to the pure no-input / random-internal Algorithms 19-20.\n * `encapsulate`'s optional `msg` is the 32-byte message randomness `m` of Algorithm 17, the\n * pre-image the shared secret is derived from, NOT a plaintext to encrypt: ML-KEM is a key\n * encapsulation mechanism, not a cipher. Omit it to draw fresh randomness; pass it only to\n * reproduce a known-answer vector, and only as 32 uniformly random bytes, since a low-entropy or\n * reused value makes the shared secret predictable. The same holds for `keygen`'s optional `seed`.\n * decapsulate() tries to follow the Algorithms 18/21 implicit-reject structure as closely as\n * practical here by re-encrypting, comparing ciphertexts, returning `Khat` on match or `Kbar` on\n * mismatch, and zeroizing the non-returned shared-secret candidate; JS/JIT still provides no\n * constant-time guarantees for that path.\n */\nfunction createKyber(opts) {\n const rawOpts = opts;\n const KPKE = genKPKE(rawOpts);\n const { HASH256, HASH512, KDF } = rawOpts;\n const { secretCoder: KPKESecretCoder, lengths } = KPKE;\n const secretCoder = splitCoder('secretKey', lengths.secretKey, lengths.publicKey, 32, 32);\n const msgLen = 32;\n const seedLen = 64;\n // FIPS-203 includes additional verification check for modulus\n const validateModulus = (publicKey, fn) => {\n const eke = publicKey.subarray(0, 384 * rawOpts.K);\n // Copy because of inplace encoding\n const ek = KPKESecretCoder.encode(KPKESecretCoder.decode(copyBytes(eke)));\n // (Modulus check.) Perform the computation ek \u2190 ByteEncode12(ByteDecode12(eke)).\n // If ek = \u0338 eke, the input is invalid. (See Section 4.2.1.)\n const ok = equalBytes(ek, eke);\n cleanBytes(ek);\n if (!ok)\n throw new Error(`ML-KEM.${fn}: wrong publicKey modulus`);\n };\n const kemLengths = Object.freeze({\n ...lengths,\n seed: 64,\n msg: msgLen,\n msgRand: msgLen,\n secretKey: secretCoder.bytesLen,\n });\n return Object.freeze({\n info: Object.freeze({ type: 'ml-kem' }),\n lengths: kemLengths,\n keygen: (seed) => {\n // A generated seed carries z (the implicit-rejection secret) and must be wiped once the\n // secret key holds a copy, matching ml-dsa / slh-dsa / falcon keygen. A caller-supplied\n // seed is the caller's to manage (and the immutability test requires it stay untouched).\n const ownSeed = seed === undefined;\n const s = ownSeed ? randomBytes(seedLen) : seed;\n let sk;\n let publicKeyHash;\n try {\n abytes(s, seedLen, 'seed');\n const keys = KPKE.keygen(s.subarray(0, 32));\n const publicKey = keys.publicKey;\n sk = keys.secretKey;\n publicKeyHash = HASH256(publicKey);\n // (dkPKE||ek||H(ek)||z)\n const secretKey = secretCoder.encode([sk, publicKey, publicKeyHash, s.subarray(32)]);\n return {\n publicKey: publicKey,\n secretKey: secretKey,\n };\n }\n finally {\n if (sk !== undefined)\n cleanBytes(sk);\n if (publicKeyHash !== undefined)\n cleanBytes(publicKeyHash);\n if (ownSeed)\n cleanBytes(s);\n }\n },\n getPublicKey: (secretKey) => {\n const [_sk, publicKey, _publicKeyHash, _z] = secretCoder.decode(secretKey);\n return Uint8Array.from(publicKey);\n },\n encapsulate: (publicKey, msg) => {\n // A generated message is the preimage of the shared secret (K = G(m || H(ek))[0:32]) and\n // must be wiped. A caller-supplied message is the deterministic-randomness hook and the\n // caller's to manage (the immutability test requires it stay untouched).\n const ownMsg = msg === undefined;\n const m = ownMsg ? randomBytes(msgLen) : msg;\n let kr;\n try {\n abytes(publicKey, lengths.publicKey, 'publicKey');\n abytes(m, msgLen, 'message');\n validateModulus(publicKey, 'encapsulate');\n // derive randomness\n kr = HASH512.create().update(m).update(HASH256(publicKey)).digest();\n const cipherText = KPKE.encrypt(publicKey, m, kr.subarray(32, 64));\n return {\n cipherText: cipherText,\n sharedSecret: kr.subarray(0, 32),\n };\n }\n finally {\n if (kr !== undefined)\n cleanBytes(kr.subarray(32));\n if (ownMsg)\n cleanBytes(m);\n }\n },\n decapsulate: (cipherText, secretKey) => {\n abytes(secretKey, secretCoder.bytesLen, 'secretKey'); // 768*k + 96\n abytes(cipherText, lengths.cipherText, 'cipherText'); // 32(du*k + dv)\n // test \u2190 H(dk[384\uD835\uDC58 \u2236 768\uD835\uDC58 + 32])) .\n const k768 = secretCoder.bytesLen - 96;\n const start = k768 + 32;\n const test = HASH256(secretKey.subarray(k768 / 2, start));\n // If test \u2260 dk[768\uD835\uDC58 + 32 \u2236 768\uD835\uDC58 + 64], then input checking has failed.\n if (!equalBytes(test, secretKey.subarray(start, start + 32)))\n throw new Error('invalid secretKey: hash check failed');\n const [sk, publicKey, publicKeyHash, z] = secretCoder.decode(secretKey);\n const msg = KPKE.decrypt(cipherText, sk);\n // derive randomness, Khat, rHat = G(mHat || h)\n const kr = HASH512.create().update(msg).update(publicKeyHash).digest();\n const Khat = kr.subarray(0, 32);\n // re-encrypt using the derived randomness\n const cipherText2 = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));\n // if ciphertexts do not match, \u201Cimplicitly reject\u201D\n const isValid = equalBytes(cipherText, cipherText2);\n const Kbar = KDF.create({ dkLen: 32 }).update(z).update(cipherText).digest();\n // kr[32:64] is the derived K-PKE encryption randomness: wipe it like encapsulate() does.\n cleanBytes(msg, cipherText2, kr.subarray(32), !isValid ? Khat : Kbar);\n return (isValid ? Khat : Kbar);\n },\n /**\n * Experimental prototype: pre-expand a public key so repeated encapsulate/decapsulate\n * against the same key skip re-validation, H(ek), t\u0302 decoding and the K\u00B2 SampleNTT\n * XOF expansions of \u00C2. Only public data is cached; see {@link KEMPrepared}.\n */\n prepare: (publicKey) => {\n abytes(publicKey, lengths.publicKey, 'publicKey');\n validateModulus(publicKey, 'prepare');\n const ek = copyBytes(publicKey); // detach from the caller before caching\n const publicKeyHash = HASH256(ek);\n const cached = KPKE.prepare(ek);\n return Object.freeze({\n publicKey: ek,\n encapsulate: (msg) => {\n // As in the non-prepared encapsulate: a generated message is the shared-secret\n // preimage and is wiped; a caller-supplied one is left untouched.\n const ownMsg = msg === undefined;\n const m = ownMsg ? randomBytes(msgLen) : msg;\n let kr;\n try {\n abytes(m, msgLen, 'message');\n kr = HASH512.create().update(m).update(publicKeyHash).digest();\n const cipherText = cached.encrypt(m, kr.subarray(32, 64));\n return {\n cipherText: cipherText,\n sharedSecret: kr.subarray(0, 32),\n };\n }\n finally {\n if (kr !== undefined)\n cleanBytes(kr.subarray(32));\n if (ownMsg)\n cleanBytes(m);\n }\n },\n decapsulate: (cipherText, secretKey) => {\n abytes(secretKey, secretCoder.bytesLen, 'secretKey');\n abytes(cipherText, lengths.cipherText, 'cipherText');\n const [sk, ekEmbedded, storedHash, z] = secretCoder.decode(secretKey);\n // Under KEMPrepared's read-only publicKey contract, bind dk to the prepared key.\n // Together with publicKeyHash = H(ek) computed in prepare(), this is equivalent to (and\n // stronger than) FIPS 203 \u00A77.3's `H(dk[384k : 768k+32]) == dk[768k+32 : 768k+64]`.\n if (!equalBytes(ekEmbedded, ek) || !equalBytes(storedHash, publicKeyHash))\n throw new Error('ML-KEM.decapsulate: secretKey does not match prepared publicKey');\n const msg = KPKE.decrypt(cipherText, sk);\n // derive randomness, Khat, rHat = G(mHat || h)\n const kr = HASH512.create().update(msg).update(publicKeyHash).digest();\n const Khat = kr.subarray(0, 32);\n // re-encrypt using the derived randomness and cached \u00C2/t\u0302\n const cipherText2 = cached.encrypt(msg, kr.subarray(32, 64));\n // if ciphertexts do not match, \u201Cimplicitly reject\u201D\n const isValid = equalBytes(cipherText, cipherText2);\n const Kbar = KDF.create({ dkLen: 32 }).update(z).update(cipherText).digest();\n cleanBytes(msg, cipherText2, kr.subarray(32), !isValid ? Khat : Kbar);\n return (isValid ? Khat : Kbar);\n },\n clean: cached.clean,\n });\n },\n });\n}\n// FIPS 203's PRF_eta binding: current callers use only 32-byte keys, one-byte nonces,\n// and dkLen values {128, 192}; out-of-range nonce numbers still wrap modulo 256 here.\nfunction shakePRF(dkLen, key, nonce) {\n return shake256\n .create({ dkLen })\n .update(key)\n .update(new Uint8Array([nonce]))\n .digest();\n}\n// Fixed ML-KEM hash/XOF bindings. `KDF` here is the spec's fixed 32-byte `J` call,\n// and swapping any field changes the scheme rather than tuning an internal dependency.\nconst opts = /* @__PURE__ */ (() => ({\n HASH256: sha3_256,\n HASH512: sha3_512,\n KDF: shake256,\n XOF: XOF128,\n PRF: shakePRF,\n}))();\n// Parameter-set instantiation step for the spec's \"ML-KEM-x\" names; current correctness relies\n// on the internal PARAMS rows rather than local validation of arbitrary KEMParam objects.\nconst mk = (params) => createKyber({\n ...opts,\n ...params,\n});\n/**\n * ML-KEM-512: Table 2 row `k=2, \u03B71=3, \u03B72=2, du=10, dv=4`; Table 3 sizes `800/1632/768/32`.\n * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement.\n * @example\n * Generate deterministic ML-KEM-512 keys, encapsulate a shared secret, and decapsulate it.\n * ```ts\n * import { ml_kem512 } from '@noble/post-quantum/ml-kem.js';\n * const seed = new Uint8Array(ml_kem512.lengths.seed!);\n * const { secretKey, publicKey } = ml_kem512.keygen(seed);\n * const msg = new Uint8Array(ml_kem512.lengths.msgRand!);\n * const { cipherText, sharedSecret } = ml_kem512.encapsulate(publicKey, msg);\n * const recovered = ml_kem512.decapsulate(cipherText, secretKey);\n * const publicKey2 = ml_kem512.getPublicKey(secretKey);\n * ```\n */\nexport const ml_kem512 = /* @__PURE__ */ (() => mk(PARAMS[512]))();\n/**\n * ML-KEM-768: Table 2 row `k=3, \u03B71=2, \u03B72=2, du=10, dv=4`; Table 3 sizes `1184/2400/1088/32`.\n * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement.\n */\nexport const ml_kem768 = /* @__PURE__ */ (() => mk(PARAMS[768]))();\n/**\n * ML-KEM-1024: Table 2 row `k=4, \u03B71=2, \u03B72=2, du=11, dv=5`; Table 3 sizes `1568/3168/1568/32`.\n * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement.\n */\nexport const ml_kem1024 = /* @__PURE__ */ (() => mk(PARAMS[1024]))();\n// NOTE: for tests only, don't use. This keeps the exact internal ML-KEM math surfaces available\n// without re-implementing them in separate test code.\nexport const __tests = /* @__PURE__ */ (() => Object.freeze({\n Compress_d: (x, d) => {\n if (d < 1 || d > 11)\n throw new Error(`Compress_d: expected d in [1..11], got ${d}`);\n return compress(d).encode(x) & getMask(d);\n },\n Decompress_d: (y, d) => {\n if (d < 1 || d > 11)\n throw new Error(`Decompress_d: expected d in [1..11], got ${d}`);\n return compress(d).decode(y);\n },\n ByteEncode_d: (F, d) => {\n if (d < 1 || d > 12)\n throw new Error(`ByteEncode_d: expected d in [1..12], got ${d}`);\n return byteCoder(d).encode(F);\n },\n ByteDecode_d: (B, d) => {\n if (d < 1 || d > 12)\n throw new Error(`ByteDecode_d: expected d in [1..12], got ${d}`);\n return byteCoder(d).decode(B);\n },\n NTT: (f) => crystals.NTT.encode(Uint16Array.from(f)),\n NTT_inv: (fHat) => crystals.NTT.decode(Uint16Array.from(fHat)),\n MultiplyNTTs: (fHat, gHat) => MultiplyNTTs(Uint16Array.from(fHat), Uint16Array.from(gHat)),\n SamplePolyCBD: (B, eta) => {\n abytes(B, 64 * eta, 'B');\n return sampleCBDBytes(B, eta);\n },\n SampleNTT: (B) => {\n abytes(B, 34, 'B');\n const xof = XOF128(B.subarray(0, 32));\n try {\n return SampleNTT(xof.get(B[32], B[33]));\n }\n finally {\n xof.clean();\n }\n },\n}))();\n", "/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF-based ScalarMultiplier, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { aarray, abool, afunction, aobject, bitLen, bitMask, bytesToNumberBE, inRange, isBytes, isPosBig, validateObject, } from \"../utils.js\";\nimport { Field, FpInvertBatch, validateField } from \"./modular.js\";\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _4n = /* @__PURE__ */ BigInt(4);\nconst BLIND_BYTES = 16;\nconst BLIND_BITS = 128;\n// Fixed-window width for the constant-time multiply of un-precomputed points (W===1).\n// A flat 2^FW_WINDOW table has a small, scalar-independent build cost that amortizes over a single\n// multiply, unlike the larger per-point wNAF tables that only pay off when cached.\nconst FW_WINDOW = 5;\n// Precompute tables are capped at ~2 GiB of estimated heap. Rejecting larger windows up front\n// turns a typo'd window size into an immediate error instead of a multi-GB allocation (or an\n// effective hang) when the lazy table is built on first multiply.\nconst TABLE_BYTES_MAX = /* @__PURE__ */ (() => 2 ** 31)();\n/**\n * Validates the static surface of a point constructor.\n * This is only a cheap sanity check for the constructor hooks and fields consumed by generic\n * factories; it does not certify `BASE`/`ZERO` semantics or prove the curve implementation itself.\n * @param Point - Runtime point constructor.\n * @throws On missing constructor hooks or malformed field metadata. {@link TypeError}\n * @example\n * Check that one point constructor exposes the static hooks generic helpers need.\n *\n * ```ts\n * import { ed25519 } from '@noble/curves/ed25519.js';\n * import { validatePointCons } from '@noble/curves/abstract/curve.js';\n * validatePointCons(ed25519.Point);\n * ```\n */\nexport function validatePointCons(Point) {\n const pc = Point;\n if (typeof pc !== 'function')\n throw new TypeError('\"Point\" expected constructor, got type=' + typeof Point);\n afunction(pc.fromAffine, 'Point.fromAffine');\n afunction(pc.fromBytes, 'Point.fromBytes');\n afunction(pc.fromHex, 'Point.fromHex');\n // Generic helpers (ScalarMultiplier, normalizeZ, MSM) dereference BASE / ZERO:\n // fail here with a typed error instead of an `undefined` access later.\n aobject(pc.BASE, 'Point.BASE');\n aobject(pc.ZERO, 'Point.ZERO');\n validateField(pc.Fp);\n validateField(pc.Fn);\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 * Input points are left unchanged; the normalized points are returned as fresh instances.\n * @param c - Point constructor.\n * @param points - Projective points.\n * @returns Fresh projective points reconstructed from normalized affine coordinates.\n * @example\n * Batch-normalize projective points with a single shared inversion.\n *\n * ```ts\n * import { normalizeZ } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const points = normalizeZ(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()]);\n * ```\n */\nexport function normalizeZ(c, points) {\n // Match MSM helpers: reject malformed public inputs before reading projective internals.\n validatePointCons(c);\n validateMSMPoints(points, c);\n // Identity points (Z=0) rely on an implicit contract: FpInvertBatch without `passZero`\n // yields `undefined` for zero inputs, and `toAffine(undefined)` falls back to its internal\n // is0 handling instead of using the batch inverse.\n const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\n}\nfunction validateW(W, bits, min = 1) {\n if (!Number.isSafeInteger(W) || W < min || W > bits)\n throw new Error('invalid window size, expected [' + min + '..' + bits + '], got W=' + W);\n}\n// Rough per-point heap estimate for the {@link TABLE_BYTES_MAX} cap: up to 4 projective/extended\n// coordinates of Fp.BYTES each, plus bigint/object overhead. Callers pass the point count of the\n// largest table the checked parameters can produce.\nfunction validateTableBytes(numPoints, fpBytes) {\n const bytes = numPoints * (4 * fpBytes + 128);\n if (bytes > TABLE_BYTES_MAX)\n throw new Error('invalid window size: table would need ~' +\n Math.ceil(bytes / 2 ** 20) +\n ' MiB, max ' +\n TABLE_BYTES_MAX / 2 ** 20 +\n ' MiB');\n}\n/**\n * Probes an RNG once, at construction time: returns `undefined` when it is unavailable \u2014\n * throws or returns malformed bytes \u2014 so callers can downgrade to their unblinded /\n * deterministic constant-time fallback. Blinding is defense-in-depth (DPA/template\n * hardening), not a correctness or key-secrecy requirement, so availability-based\n * downgrade is acceptable.\n *\n * The downgrade decision is deliberately static. After a successful probe the RNG becomes\n * part of the trusted contract: later misbehavior must fail closed in per-call validation\n * (throw), never downgrade \u2014 a dynamic fallback would let a tampered RNG silently strip\n * blinding on demand. A probe can only ever classify broken environments, not adversarial\n * RNGs: a stateful RNG can always behave while probed and misbehave later.\n * @param randomBytes - RNG to probe, or `undefined` when the environment provides none.\n * @param length - Byte length requested from the probe call.\n * @returns The RNG when the probe produced `length` valid bytes; `undefined` otherwise.\n * @example\n * Probe an RNG once before enabling scalar blinding.\n *\n * ```ts\n * import { probeRandomBytes } from '@noble/curves/abstract/curve.js';\n * import { randomBytes } from '@noble/hashes/utils.js';\n * const rng = probeRandomBytes(randomBytes, 16);\n * ```\n */\nexport function probeRandomBytes(randomBytes, length) {\n if (randomBytes === undefined)\n return undefined;\n afunction(randomBytes, 'randomBytes');\n try {\n const probe = randomBytes(length);\n if (!isBytes(probe) || probe.length !== length)\n return undefined;\n }\n catch {\n return undefined;\n }\n return randomBytes;\n}\nfunction validateMSMPoints(points, c) {\n aarray(points, 'points');\n points.forEach((p, i) => {\n if (!(p instanceof c))\n throw new Error('invalid point at index ' + i);\n });\n}\n// Default bound is field membership (0 <= s < field.ORDER); a `maxScalar` override widens it\n// to 0 <= s < maxScalar for callers that accept oversized scalars.\nfunction validateMSMScalars(scalars, field, maxScalar) {\n if (!Array.isArray(scalars))\n throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n const ok = maxScalar === undefined ? field.isValid(s) : isPosBig(s) && s < maxScalar;\n if (!ok)\n throw new Error('invalid scalar at index ' + i);\n });\n}\nconst pointWindowSizes = new WeakMap();\nfunction getWindowSize(P) {\n // `1` is the uncached sentinel: use the non-precomputed (wNAF / fixed-window) path.\n return pointWindowSizes.get(P) || 1;\n}\n/** Table of odd multiples [1P, 3P, ..., (2\u22C5size\u22121)P]; width-W wNAF uses size = 2^(W\u22122). */\nfunction oddMultiples(p, size) {\n const dbl = p.double();\n const t = [p];\n for (let j = 1; j < size; j++)\n t.push(t[j - 1].add(dbl));\n return t;\n}\n/**\n * Width-W wNAF signed-digit recoding (W >= 2), LSB-first: digits are 0 or odd with\n * |digit| < 2^(W\u22121); nonzero density ~1/(W+1) (a nonzero digit is followed by W\u22121 zeros).\n */\nfunction wnafDigits(n, W) {\n const size = 2 ** W;\n const half = size / 2;\n const mask = BigInt(size - 1);\n const d = [];\n while (n > _0n) {\n let w = 0;\n if (n & _1n) {\n w = Number(n & mask); // n mod 2^W, odd\n if (w >= half)\n w -= size; // signed residue\n n -= BigInt(w); // n - w \u2261 0 mod 2^W: next W\u22121 digits are zero\n }\n d.push(w);\n n >>= _1n;\n }\n return d;\n}\n/**\n * Fixed-position signed-window recoding for precomputed wNAF: `n = \u03A3 digits[w]\u22C52^(w\u22C5W)` with\n * digits in `[\u22122^(W\u22121)+1, 2^(W\u22121)]`. Digit count is fixed by `windows` (callers reserve one\n * extra window for the final carry), so recoding length does not depend on the scalar.\n */\nfunction signedWindowDigits(n, W, windows) {\n const size = 2 ** W;\n const half = size / 2;\n const mask = BigInt(size - 1);\n const shiftBy = BigInt(W);\n const d = [];\n for (let w = 0; w < windows; w++) {\n let v = Number(n & mask);\n n >>= shiftBy;\n if (v > half) {\n v -= size; // negative digit, carry into the next window\n n += _1n;\n }\n d.push(v);\n }\n // Internal invariant: leftover bits mean the window count did not cover the scalar.\n if (n !== _0n)\n throw new Error('invalid wnaf');\n return d;\n}\n/**\n * Shared vartime walk over per-scalar wNAF digit streams: one doubling of a single shared\n * accumulator per bit position of the longest recoding, one signed table addition per\n * nonzero digit. `tables[i]` must hold the odd multiples of the i-th point.\n */\nfunction wnafWalk(zero, tables, digits) {\n let max = 0;\n for (const d of digits)\n max = Math.max(max, d.length);\n let acc = zero;\n for (let bit = max - 1; bit >= 0; bit--) {\n if (bit !== max - 1)\n acc = acc.double();\n for (let i = 0; i < digits.length; i++) {\n const w = digits[i][bit]; // reads past shorter recodings yield undefined, skipped below\n if (w) {\n const item = tables[i][(Math.abs(w) - 1) >> 1];\n acc = acc.add(w < 0 ? item.negate() : item);\n }\n }\n }\n return acc;\n}\n/**\n * Elliptic curve multiplication of Point by scalar.\n * Routes between cached-table, fixed-window, and one-shot wNAF paths; entry points validate\n * their own scalars (`mulCT`/`mulCTBlinded`: `1 <= s < Fn.ORDER`; `mulUnsafe`: up to the\n * `Fn.ORDER^4` DoS cap via {@link mulAddUnsafe}).\n * Table generation is expensive and happens on first call of `multiply()`\n * (or eagerly via `precompute(W, false)`). By default, `BASE` point is precomputed.\n *\n * Cached algorithm is signed fixed-window wNAF:\n * - table stores, for every window w, the multiples `[1..2^(W\u22121)]\u22C52^(w\u22C5W)\u22C5P` \u2014 all doublings\n * are baked in, so a multiplication is exactly one table addition per window\n * - window count is fixed (`ceil(bits/W) + 1`), so the point-operation count is scalar-independent\n * (basis of the constant-time path)\n * - for a 256-bit curve and W=6: 44\u22C532 = 1408 table points, 44 additions per multiply\n * - secret scalars are additionally blinded (see {@link ScalarMultiplier.mulCTBlinded}), which\n * widens tables by 128 bits\n * @param Point - Point constructor.\n * @param randomBytes - RNG used for scalar blinding; required by the blinded secret path.\n * @example\n * Elliptic curve multiplication of Point by scalar.\n *\n * ```ts\n * import { ScalarMultiplier } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const mul = new ScalarMultiplier(p256.Point);\n * ```\n */\nexport class ScalarMultiplier {\n Point;\n BASE;\n ZERO;\n randomBytes;\n wnafPrecomputes = new WeakMap();\n baseCanBeBlinded;\n bits;\n // Parametrized with a given Point class (not individual point)\n constructor(Point, randomBytes) {\n validatePointCons(Point);\n // Probe the RNG once (see {@link probeRandomBytes}): in environments without working\n // randomness (e.g. no WebCrypto), shouldBlind() then routes secret multiplication to the\n // unblinded constant-time path instead of throwing on every multiply(). The shape of\n // returned bytes is still validated on every blinded call, where breakage fails closed.\n this.randomBytes = probeRandomBytes(randomBytes, BLIND_BYTES);\n this.Point = Point;\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.bits = Point.Fn.BITS;\n }\n /**\n * Creates a signed fixed-window wNAF precomputation table: for every window w, the\n * multiples `[1..2^(W\u22121)]\u22C52^(w\u22C5W)\u22C5P`, flattened. All doublings are baked into the table,\n * so cached multiplication is additions-only. `windows = ceil(bits/W) + 1`: the extra\n * window absorbs the final carry of signed-digit recoding.\n * For a 256-bit curve and W=6, the table is 44\u22C532 = 1408 points.\n * @param point - Point instance\n * @param W - window size\n * @param bits - scalar bitlength the table must cover\n */\n buildWnafTable(point, W, bits) {\n // W needs no re-validation: its only source is setWindowSize(), which enforces\n // 1 <= W <= Fn.BITS <= bits (the blinded path only ever widens bits) and caps the\n // resulting table at ~2 GiB (sized against the wider blinded layout).\n const windows = Math.ceil(bits / W) + 1;\n const half = 2 ** (W - 1);\n const comp = [];\n let base = point;\n for (let w = 0; w < windows; w++) {\n let acc = base;\n for (let i = 0; i < half; i++) {\n comp.push(acc);\n acc = acc.add(base);\n }\n base = comp[comp.length - 1].double(); // 2\u22C5(2^(W\u22121)\u22C5base) = next window's base\n }\n return { W, bits, windows, comp };\n }\n /**\n * Implements ec multiplication using precomputed signed fixed-window wNAF tables.\n * Constant-time: fixed window count with one table addition per window \u2014 zero digits feed\n * the fake accumulator \u2014 and no doublings; the lookup scans the whole window slice.\n * Scalar bounds are validated by the public entry points ({@link ScalarMultiplier.mulCT},\n * {@link ScalarMultiplier.mulCTBlinded}, {@link ScalarMultiplier.mulUnsafe});\n * signedWindowDigits throws if `n` exceeds the table.\n * @returns real and fake (for const-time) points\n */\n wnafCachedCT(precomputes, n) {\n const { W, windows, comp } = precomputes;\n const half = 2 ** (W - 1);\n const digits = signedWindowDigits(n, W, windows);\n let p = this.ZERO;\n let f = this.BASE;\n for (let w = 0; w < windows; w++) {\n const digit = digits[w];\n const start = w * half;\n // Data-oblivious select: touch every entry of the window before the digit branch.\n const idx = Math.abs(digit) - 1; // -1 for zero digits: matches nothing, `sel` unused\n let sel = comp[start];\n for (let i = 1; i < half; i++)\n sel = i === idx ? comp[start + i] : sel;\n const neg = sel.negate(); // compute both signs; the digit only picks one\n if (digit === 0)\n f = f.add(comp[start]);\n else\n p = p.add(digit < 0 ? neg : sel);\n }\n return { p, f };\n }\n // Cache key is point identity plus (W, bits); at most two entries exist per point (public-width\n // `Fn.BITS` and blinded `Fn.BITS + BLIND_BITS`). Callers must not reuse the same point with\n // incompatible `transform(...)` layouts and expect a separate cache entry.\n getWnafPrecomputes(W, point, bits, transform) {\n let entries = this.wnafPrecomputes.get(point);\n let comp = entries?.find((entry) => entry.W === W && entry.bits === bits);\n if (!comp) {\n comp = this.buildWnafTable(point, W, bits);\n if (typeof transform === 'function')\n comp = { ...comp, comp: transform(comp.comp) };\n if (!entries) {\n entries = [];\n this.wnafPrecomputes.set(point, entries);\n }\n entries.push(comp);\n }\n return comp;\n }\n assertPoint(point) {\n if (!(point instanceof this.Point))\n throw new TypeError('\"point\" expected Point instance, got type=' + typeof point);\n }\n // Shared prologue of the constant-time entry points. Rejects scalar 0: in key/signature-style\n // callers a zero scalar means broken upstream plumbing, and concrete Points already reject it.\n // Uses inRange instead of Fn.isValidNot0: validateField() only certifies the arithmetic subset.\n validateMulInput(point, scalar) {\n this.assertPoint(point);\n if (!inRange(scalar, _1n, this.Point.Fn.ORDER))\n throw new Error('invalid scalar');\n }\n // Constant-time dispatch shared by mulCT / mulCTBlinded. Un-precomputed points (W===1, e.g.\n // ECDH peer keys) skip building a throwaway cached table in favor of a small fixed-window\n // multiply. `n` must be < 2^bits.\n runCT(point, n, bits, transform) {\n const W = getWindowSize(point);\n if (W === 1)\n return this.fixedWindowCT(point, n, bits);\n return this.wnafCachedCT(this.getWnafPrecomputes(W, point, bits, transform), n);\n }\n mulCT(point, scalar, transform) {\n this.validateMulInput(point, scalar);\n return this.runCT(point, scalar, this.bits, transform);\n }\n mulCTBlinded(point, scalar, transform) {\n this.validateMulInput(point, scalar);\n // Blinding computes n = scalar + blind*Fn.ORDER, then n*P via a constant-time multiply. This\n // equals scalar*P only when Fn.ORDER*P == O; callers guarantee that via shouldBlind() (always\n // for cofactor-1 curves; for cofactored curves only BASE, and only after checking BASE*n == O).\n // Fail before building the (large) precompute table if randomness is unavailable.\n if (this.randomBytes === undefined)\n throw new Error('randomBytes is required for scalar blinding');\n const bits = this.Point.Fn.BITS + BLIND_BITS;\n const blind = this.randomBytes(BLIND_BYTES);\n if (!isBytes(blind) || blind.length !== BLIND_BYTES)\n throw new Error('randomBytes returned invalid byte array');\n // Force the top two bits of the 128-bit blind to 10xxxxxx, so blind is in [2^127, 1.5*2^127):\n // * `| 0x80` (bit 127 = 1) is the load-bearing part: it guarantees blind >= 2^127, so the blind\n // is always a full-width, nonzero factor and the scalar is masked even with a degenerate RNG.\n // * `& 0x3f` (bit 126 = 0) is a safety margin: it caps blind < 1.5*2^127, keeping\n // blind*Fn.ORDER + scalar < 0.75*2^(nBits+128), i.e. ~half a window below the 2^(nBits+128)\n // ceiling. Not strictly required for the bound (see below), but it reserves headroom so the\n // guarantee does not rest on the tight `Fn.ORDER < 2^Fn.BITS` fact and the final carry window\n // only ever holds a small carry, never a full digit.\n blind[0] = (blind[0] & 0x3f) | 0x80;\n // Even at the extreme (blind < 2^128, scalar < Fn.ORDER < 2^nBits): n <= 2^128*Fn.ORDER - 1 <\n // 2^(nBits+128), so n stays below 2^bits and within the blinded table's\n // window count. Both cached CT kernels run a fixed number of windows/rows with one point-add\n // each, so the add count is independent of scalar (constant-time).\n const n = scalar + bytesToNumberBE(blind) * this.Point.Fn.ORDER;\n return this.runCT(point, n, bits, transform);\n }\n /**\n * Constant-time multiplication `n*point` for an un-precomputed point, via a small fixed window.\n * A cached wNAF table only pays off when reused; a flat 2^FW_WINDOW table (`size-1` adds) is\n * far cheaper to build for a single use. The point-operation sequence is independent of `n`:\n * build the table, then per window exactly FW_WINDOW doublings, a data-oblivious scan over\n * every table entry, and one addition (adds the identity when the window digit is 0 \u2014 never\n * skipped).\n *\n * `n` must be `< 2^bits`. Assumes complete addition (adding the identity costs the same as any\n * add), which holds for the Weierstrass/Edwards point types used here. The table is left in\n * projective form (no normalizeZ): normalizing this small a table costs more than the\n * mixed-add savings it would buy for a single multiply.\n * @returns real point `p`; `f` duplicates it only to match {@link wnafCachedCT}'s return shape\n * (this path needs no fake accumulator \u2014 its op-count is already scalar-independent).\n */\n fixedWindowCT(point, n, bits) {\n const W = FW_WINDOW;\n const size = 1 << W;\n const mask = bitMask(W);\n // Flat table [O, point, 2*point, ..., (size-1)*point].\n const table = new Array(size);\n table[0] = this.ZERO;\n for (let i = 1; i < size; i++)\n table[i] = table[i - 1].add(point);\n // Horner MSB->LSB. windows*W >= bits and n < 2^bits, so every bit of n is consumed.\n const windows = Math.ceil(bits / W);\n let acc = this.ZERO;\n for (let window = windows - 1; window >= 0; window--) {\n // W doublings per window; skipped for the first (topmost) window, where acc is still the\n // identity. The skip is scalar-independent: it depends only on the loop index.\n if (window !== windows - 1)\n for (let d = 0; d < W; d++)\n acc = acc.double();\n const digit = Number((n >> BigInt(window * W)) & mask);\n // Data-oblivious select: touch every entry, same as wnafCachedCT.\n let sel = table[0];\n for (let i = 1; i < size; i++)\n sel = i === digit ? table[i] : sel;\n acc = acc.add(sel); // one add per window, even for digit 0\n }\n return { p: acc, f: acc };\n }\n shouldBlind(point, cofactor) {\n // No usable RNG (probed in the constructor): blinding is impossible, use the plain CT path.\n if (this.randomBytes === undefined)\n return false;\n if (cofactor === _1n)\n return true;\n if (point !== this.BASE)\n return false;\n if (this.baseCanBeBlinded === undefined)\n this.baseCanBeBlinded = this.mulUnsafe(this.BASE, this.Point.Fn.ORDER).is0();\n return this.baseCanBeBlinded;\n }\n mulSecret(point, scalar, cofactor, transform) {\n return this.shouldBlind(point, cofactor)\n ? this.mulCTBlinded(point, scalar, transform)\n : this.mulCT(point, scalar, transform);\n }\n mulUnsafe(point, scalar, transform) {\n this.assertPoint(point);\n if (!isPosBig(scalar))\n throw new Error('invalid scalar');\n const W = getWindowSize(point);\n // W === 1 (un-precomputed): one-shot width-4 wNAF via {@link mulAddUnsafe} with L=1 \u2014\n // a cached table would be thrown away after one use. `allowOversized` swaps the\n // `s < Fn.ORDER` check for mulAddUnsafe's `Fn.ORDER^4` DoS cap.\n //\n // Oversized scalar could happen when:\n // a) user passes large scalar on their own (rare)\n // b) `assertValidity()` calls `isTorsionFree()`, which multiplies point by `Fn.ORDER`\n if (W === 1 || scalar >= this.Point.Fn.ORDER)\n return mulAddUnsafe(this.Point, [point], [scalar], true);\n // Precomputed points reuse the CT kernel (fake accumulator discarded): with W=6 only\n // ~1/64 of window-adds are skippable, so a dedicated vartime kernel saved just ~6% on\n // this path while doubling the cached-table code surface.\n const precomputes = this.getWnafPrecomputes(W, point, this.bits, transform);\n return this.wnafCachedCT(precomputes, scalar).p;\n }\n // Remembers the window size used for precomputed wNAF multiplication of the given point\n // and drops any previously built tables. Usually only the base point is precomputed.\n // W=1 resets the point to the un-precomputed (table-less) paths.\n // W is additionally capped so tables stay under ~2 GiB ({@link TABLE_BYTES_MAX}).\n setWindowSize(point, W) {\n this.assertPoint(point);\n validateW(W, this.bits);\n // Size against the widest table this W can produce: the blinded path adds BLIND_BITS.\n const windows = Math.ceil((this.bits + BLIND_BITS) / W) + 1;\n validateTableBytes(windows * 2 ** (W - 1), this.Point.Fp.BYTES);\n pointWindowSizes.set(point, W);\n this.wnafPrecomputes.delete(point);\n }\n // True when a window size is set: tables themselves are built lazily on first multiply.\n hasWindowSize(point) {\n return getWindowSize(point) !== 1;\n }\n}\n/**\n * Combined multi-scalar multiplication `\u03A3 scalars[i]\u22C5points[i]` via interleaved width-4 wNAF\n * (Strauss\u2013Shamir). Every input gets its own table of odd multiples `[1P, 3P, 5P, 7P]` and\n * signed-digit recoding, but all walks share one doubling chain, so total cost is\n * `~bits` doublings + `L\u22C5bits/5` additions instead of `L\u22C5bits` doublings for separate\n * multiplications. Intended for the 2-4 point shapes of signature verification\n * (`R = u1\u22C5G + u2\u22C5P`); use {@link pippenger} for larger batches.\n *\n * Not constant-time: only for public inputs. Scalars must satisfy `0 <= s < Fn.ORDER`;\n * fold negative signs into the points before calling.\n * @param c - Point constructor.\n * @param points - Array of curve points.\n * @param scalars - Array of non-negative scalars, same length as points.\n * @param allowOversized - Replace the `s < Fn.ORDER` scalar check with a `Fn.ORDER^4` DoS cap.\n * Off by default. For scalars that must NOT be reduced mod ORDER: torsion checks\n * (`Fn.ORDER\u22C5P \u225F O`) and cofactor-clearing multiples. Walk length grows with `bitLen(s)`.\n * @returns Combined multiplication result; identity for empty input.\n * @throws If the point set or scalar set is invalid. {@link Error}\n * @example\n * Combined multi-scalar multiplication via Strauss\u2013Shamir.\n *\n * ```ts\n * import { mulAddUnsafe } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const G = p256.Point.BASE;\n * const R = mulAddUnsafe(p256.Point, [G, G.double()], [2n, 3n]); // 2\u22C5G + 3\u22C5(2\u22C5G)\n * ```\n */\nexport function mulAddUnsafe(c, points, scalars, allowOversized = false) {\n validatePointCons(c);\n validateMSMPoints(points, c);\n abool(allowOversized, 'allowOversized');\n // Oversized cap is ORDER^4: hard bound to mitigate DoS, walk length grows with bitLen(s).\n validateMSMScalars(scalars, c.Fn, allowOversized ? c.Fn.ORDER ** _4n : undefined);\n if (points.length !== scalars.length)\n throw new Error('arrays of points and scalars must have equal length');\n const tables = points.map((p) => oddMultiples(p, 4));\n const digits = scalars.map((n) => wnafDigits(n, 4));\n return wnafWalk(c.ZERO, tables, digits);\n}\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Point-operation count is scalar-independent (for same L), even when 1 point + scalar, or when\n * scalar = 0 \u2014 but bucket indices are scalar windows, so the memory-access pattern is\n * scalar-dependent: do not rely on this for secret scalars.\n *\n * A repaired LFG bucket-set variant from ePrint 2024/750 was benchmarked on BLS12-381 G1\n * against this implementation: ~1.4x faster at 2048 points and ~1.1-1.25x faster at\n * 4096-32768 points, at the cost of extra recoding and multiplier-table complexity.\n * @param c - Curve Point constructor\n * @param points - array of L curve points\n * @param scalars - array of L scalars (aka secret keys / bigints)\n * @returns MSM result point. Empty input is accepted and returns the identity.\n * @throws If the point set, scalar set, or MSM sizing is invalid. {@link Error}\n * @example\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n *\n * ```ts\n * import { pippenger } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const point = pippenger(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()], [2n, 3n]);\n * ```\n */\nexport function pippenger(c, points, scalars) {\n // 0 is accepted in scalars\n validatePointCons(c);\n const fieldN = c.Fn;\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength)\n throw new Error('arrays of points and scalars must have equal length');\n const zero = c.ZERO;\n // Without this, the window loop below would still run ~Fn.BITS doublings of ZERO.\n if (plength === 0)\n return zero;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12)\n windowSize = wbits - 3;\n else if (wbits > 4)\n windowSize = wbits - 2;\n else if (wbits > 0)\n windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array\n const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n let sum = zero;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(zero);\n for (let j = 0; j < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & MASK);\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = zero; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0)\n for (let j = 0; j < windowSize; j++)\n sum = sum.double();\n }\n return sum;\n}\n/**\n * Interleaved wNAF multi-scalar multiplication (MSM, Pa + Qb + Rc + ...) over a FIXED set\n * of points: each point gets a one-time table of odd multiples\n * `[1P, 3P, ..., (2^(W\u22121)\u22121)P]`, and the returned closure evaluates MSMs against those\n * tables. All scalars share one doubling chain (Straus 1964) \u2014 one doubling per scalar bit\n * plus one signed table addition per nonzero width-W wNAF digit (density ~1/(W+1)) \u2014 the\n * \"interleaving\" method of M\u00F6ller, \"Algorithms for multi-exponentiation\" (SAC 2001).\n *\n * Table memory is `L\u22C52^(W\u22122)` points, capped at ~2 GiB. Prefer this over {@link pippenger}\n * when the same points are reused across many MSMs (fixed-base commitments etc.) and up to a\n * few hundred points; prefer pippenger for one-shot MSMs or thousands of points, where\n * bucketing beats per-point tables.\n *\n * Not constant-time (zero digits are skipped): public inputs only.\n * @param c - Curve Point constructor\n * @param points - array of L curve points, captured by the returned closure\n * @param windowSize - window width W in bits, from 2 to Fn.BITS; also capped so the\n * per-closure tables stay under ~2 GiB\n * @returns Function which multiplies points with scalars. The closure accepts at most\n * `points.length` scalars, and omitted trailing scalars are treated as zero.\n * @throws If the point set or precompute window is invalid. {@link Error}\n * @example\n * Interleaved wNAF multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n *\n * ```ts\n * import { interleavedMSMUnsafe } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const msm = interleavedMSMUnsafe(p256.Point, [p256.Point.BASE], 4);\n * const point = msm([3n]);\n * ```\n */\nexport function interleavedMSMUnsafe(c, points, windowSize) {\n validatePointCons(c);\n const fieldN = c.Fn;\n // Signed odd digits need at least width 2 (W=2 is plain NAF with a single-entry table).\n validateW(windowSize, fieldN.BITS, 2);\n validateMSMPoints(points, c);\n validateTableBytes(points.length * 2 ** (windowSize - 2), c.Fp.BYTES);\n const tables = points.map((p) => oddMultiples(p, 2 ** (windowSize - 2)));\n return (scalars) => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must not be larger than array of points');\n return wnafWalk(c.ZERO, tables, scalars.map((n) => wnafDigits(n, windowSize)));\n };\n}\nfunction createField(order, field, isLE) {\n if (field) {\n // Reuse supplied field overrides as-is; `isLE` only affects freshly constructed fallback\n // fields, and validateField() below only checks the arithmetic subset, not full byte/cmov\n // behavior.\n if (field.ORDER !== order)\n throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field;\n }\n else {\n return Field(order, { isLE });\n }\n}\n/**\n * Validates basic CURVE shape and field membership, then creates fields.\n * This does not prove that the generator is on-curve, that subgroup/order data are consistent, or\n * that the curve equation itself is otherwise sane.\n * @param type - Curve family.\n * @param CURVE - Curve parameters.\n * @param curveOpts - Optional field overrides. See {@link FpFn}:\n * - `Fp` (optional): Optional base-field override.\n * - `Fn` (optional): Optional scalar-field override.\n * @param FpFnLE - Whether field encoding is little-endian.\n * @returns Frozen curve parameters and fields.\n * @throws If the curve parameters or field overrides are invalid. {@link Error}\n * @example\n * Build curve fields from raw constants before constructing a curve instance.\n *\n * ```ts\n * const curve = createCurveFields('weierstrass', {\n * p: 17n,\n * n: 19n,\n * h: 1n,\n * a: 2n,\n * b: 2n,\n * Gx: 5n,\n * Gy: 1n,\n * });\n * ```\n */\nexport function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {\n if (type !== 'weierstrass' && type !== 'edwards')\n throw new Error('expected curve type \"weierstrass\" or \"edwards\"');\n if (FpFnLE === undefined)\n FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object')\n throw new Error(`expected valid ${type} CURVE object`);\n // Validate before reading Fp/Fn so explicit null fails with an options-object error.\n validateObject(curveOpts);\n for (const p of ['p', 'n', 'h']) {\n const val = CURVE[p];\n if (!(isPosBig(val) && val !== _0n))\n throw new Error(`CURVE.${p} must be positive bigint`);\n }\n const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n const _b = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b];\n for (const p of params) {\n // @ts-ignore\n if (!Fp.isValid(CURVE[p]))\n throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n }\n CURVE = Object.freeze(Object.assign({}, CURVE));\n return { CURVE, Fp, Fn };\n}\n/**\n * @param randomSecretKey - Secret-key generator.\n * @param getPublicKey - Public-key derivation helper.\n * @returns Keypair generator.\n * @example\n * Build a `keygen()` helper from existing secret-key and public-key primitives.\n *\n * ```ts\n * import { createKeygen } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const keygen = createKeygen(p256.utils.randomSecretKey, p256.getPublicKey);\n * const pair = keygen();\n * ```\n */\nexport function createKeygen(randomSecretKey, getPublicKey) {\n return function keygen(seed) {\n const secretKey = randomSecretKey(seed);\n return { secretKey, publicKey: getPublicKey(secretKey) };\n };\n}\n", "/**\n * Twisted Edwards curve. The formula is: ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2.\n * For design rationale of types / exports, see weierstrass module documentation.\n * Untwisted Edwards curves exist, but they aren't used in real-world protocols.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abool, abytes, aInRange, asafenumber, bytesToHex, bytesToNumberLE, concatBytes, copyBytes, hexToBytes, isBytes, notImplemented, validateObject, randomBytes as wcRandomBytes, } from \"../utils.js\";\nimport { createCurveFields, createKeygen, normalizeZ, ScalarMultiplier, validatePointCons, } from \"./curve.js\";\nimport { FpLegendre } from \"./modular.js\";\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _4n = /* @__PURE__ */ BigInt(4), _8n = /* @__PURE__ */ BigInt(8);\n// Affine Edwards-equation check only; this does not prove subgroup membership, canonical\n// encoding, prime-order base-point requirements, or identity exclusion.\nfunction isEdValidXY(Fp, CURVE, x, y) {\n const x2 = Fp.sqr(x);\n const y2 = Fp.sqr(y);\n const left = Fp.add(Fp.mul(CURVE.a, x2), y2);\n const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));\n return Fp.eql(left, right);\n}\n/**\n * @param params - Curve parameters. See {@link EdwardsOpts}.\n * @param extraOpts - Optional helpers and overrides. See {@link EdwardsExtraOpts}.\n * @returns Edwards point constructor. Generator validation here only checks\n * that `(Gx, Gy)` satisfies the affine Edwards equation.\n * RFC 8032 base-point constraints like `B != (0,1)` and `[L]B = 0`\n * are left to the caller's chosen parameters, since eager subgroup\n * validation here adds about 10-15ms to heavyweight imports like ed448.\n * The returned constructor also eagerly marks `Point.BASE` for W=6\n * precompute caching. Some code paths still assume\n * `Fp.BYTES === Fn.BYTES`, so mismatched byte lengths are not fully audited here.\n * @throws If the curve parameters or Edwards overrides are invalid. {@link Error}\n * @example\n * ```ts\n * import { edwards } from '@noble/curves/abstract/edwards.js';\n * import { jubjub } from '@noble/curves/misc.js';\n * // Build a point constructor from explicit curve parameters, then use its base point.\n * const Point = edwards(jubjub.Point.CURVE());\n * Point.BASE.toHex();\n * ```\n */\nexport function edwards(params, extraOpts = {}) {\n validateObject(extraOpts, {}, {}, 'extraOpts');\n const opts = extraOpts;\n const validated = createCurveFields('edwards', params, opts, opts.FpFnLE);\n const { Fp, Fn } = validated;\n let CURVE = validated.CURVE;\n const { h: cofactor } = CURVE;\n // The unified add-2008-hwcd formulas (see EdwardsPoint.add/double) are complete \u2014\n // exception-free for every input pair \u2014 only when a is a square and d a non-square in Fp\n // (Bernstein\u2013Birkner\u2013Joye\u2013Lange\u2013Peters, \"Twisted Edwards curves\", thm 3.3). The constant-time\n // kernels in curve.ts assume completeness, so an incomplete curve could silently produce\n // wrong results on exceptional inputs. Fail construction instead.\n if (FpLegendre(Fp, CURVE.a) !== 1)\n throw new Error('edwards: CURVE.a must be a square in Fp for complete addition formulas');\n if (FpLegendre(Fp, CURVE.d) !== -1)\n throw new Error('edwards: CURVE.d must be a non-square in Fp for complete addition formulas');\n validateObject(opts, {}, { uvRatio: 'function', randomBytes: 'function' });\n const randomBytes = opts.randomBytes === undefined ? wcRandomBytes : opts.randomBytes;\n // Coordinate and ZIP-215 bounds follow the base-field byte container, not scalar bytes.\n const MASK = _2n << (BigInt(Fp.BYTES * 8) - _1n);\n function isOdd(n) {\n if (!Fp.isOdd)\n throw new Error('Field does not have .isOdd()');\n return Fp.isOdd(n);\n }\n // sqrt(u/v)\n const uvRatio = opts.uvRatio === undefined\n ? (u, v) => {\n try {\n return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };\n }\n catch (e) {\n return { isValid: false, value: _0n };\n }\n }\n : opts.uvRatio;\n // Validate whether the passed curve params are valid.\n // equation ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2 should work for generator point.\n if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))\n throw new Error('bad curve params: generator point');\n // Multiplication by param `a` sits on the double() / add() hot paths. For the common twists\n // a=-1 (ed25519, jubjub) and a=1 (ed448) the full field multiplication is replaced with\n // negation / identity. Selection depends only on public curve constants.\n const mulA = Fp.eql(CURVE.a, Fp.neg(Fp.ONE)) ? (x) => Fp.neg(x)\n : Fp.eql(CURVE.a, Fp.ONE) ? (x) => x\n : (x) => Fp.mul(CURVE.a, x); // prettier-ignore\n /**\n * Asserts coordinate is valid: 0 <= n < MASK.\n * Coordinates >= Fp.ORDER are allowed for zip215.\n */\n function acoord(title, n, banZero = false) {\n const min = banZero ? _1n : _0n;\n aInRange('coordinate ' + title, n, min, MASK);\n return n;\n }\n function aedpoint(other) {\n if (!(other instanceof Point))\n throw new Error('EdwardsPoint 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 {\n static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE, Fp.mul(CURVE.Gx, CURVE.Gy));\n static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ONE, Fp.ZERO);\n static Fp = Fp;\n static Fn = Fn;\n X;\n Y;\n Z;\n T;\n constructor(X, Y, Z, T) {\n this.X = acoord('x', X);\n this.Y = acoord('y', Y);\n this.Z = acoord('z', Z, true);\n this.T = acoord('t', T);\n Object.freeze(this);\n }\n static CURVE() {\n return CURVE;\n }\n /**\n * Create one extended Edwards point from affine coordinates.\n * Does NOT validate that the point is on-curve or torsion-free.\n * Use `.assertValidity()` on adversarial inputs.\n */\n static fromAffine(p) {\n if (p instanceof Point)\n throw new Error('extended point not allowed');\n const { x, y } = p || {};\n acoord('x', x);\n acoord('y', y);\n return new Point(x, y, Fp.ONE, Fp.mul(x, y));\n }\n // Uses algo from RFC8032 5.1.3.\n static fromBytes(bytes, zip215 = false) {\n const len = Fp.BYTES;\n const { a, d } = CURVE;\n bytes = copyBytes(abytes(bytes, len, 'point'));\n abool(zip215, 'zip215');\n const normed = copyBytes(bytes); // copy again, we'll manipulate it\n const lastByte = bytes[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = bytesToNumberLE(normed);\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n const max = zip215 ? MASK : Fp.ORDER;\n aInRange('point.y', y, _0n, max);\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 = Fp.sqr(y); // denominator is always non-0 mod p.\n const u = Fp.sub(y2, Fp.ONE); // u = y\u00B2 - 1\n const v = Fp.sub(Fp.mulN(d, y2), a); // v = d y\u00B2 - a.\n let { isValid, value: x } = uvRatio(u, v); // \u221A(u/v)\n if (!isValid)\n throw new Error('bad point: invalid y coordinate');\n const isXOdd = isOdd(x); // 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 && Fp.is0(x) && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('bad point: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd)\n x = Fp.neg(x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromHex(hex, zip215 = false) {\n return Point.fromBytes(hexToBytes(hex), zip215);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n precompute(windowSize = 6, isLazy = true) {\n wnaf.setWindowSize(this, windowSize);\n if (!isLazy)\n this.multiply(_2n); // random number\n return this;\n }\n // Useful in fromAffine() - not for fromBytes(), which always created valid points.\n assertValidity() {\n const p = this;\n const { a, d } = CURVE;\n // Keep generic Edwards validation fail-closed on the neutral point.\n // Even though ZERO is algebraically valid and can roundtrip through encodings, higher-level\n // callers often reach it only through broken hash/scalar plumbing; rejecting it here avoids\n // silently treating that degenerate state as an ordinary public point.\n if (p.is0())\n 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 { X, Y, Z, T } = p;\n const X2 = Fp.sqr(X); // X\u00B2\n const Y2 = Fp.sqr(Y); // Y\u00B2\n const Z2 = Fp.sqr(Z); // Z\u00B2\n const Z4 = Fp.sqr(Z2); // Z\u2074\n const aX2 = Fp.mul(X2, a); // aX\u00B2\n const left = Fp.mul(Fp.add(aX2, Y2), Z2); // (aX\u00B2 + Y\u00B2)Z\u00B2\n const right = Fp.add(Z4, Fp.mul(d, Fp.mul(X2, Y2))); // Z\u2074 + dX\u00B2Y\u00B2\n if (!Fp.eql(left, right))\n 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 = Fp.mul(X, Y);\n const ZT = Fp.mul(Z, T);\n if (!Fp.eql(XY, ZT))\n throw new Error('bad point: equation left != right (2)');\n }\n // Compare one point to another.\n equals(other) {\n aedpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n const X1Z2 = Fp.mul(X1, Z2);\n const X2Z1 = Fp.mul(X2, Z1);\n const Y1Z2 = Fp.mul(Y1, Z2);\n const Y2Z1 = Fp.mul(Y2, Z1);\n return Fp.eql(X1Z2, X2Z1) && Fp.eql(Y1Z2, Y2Z1);\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n negate() {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(Fp.neg(this.X), this.Y, this.Z, Fp.neg(this.T));\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() {\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const A = Fp.sqr(X1); // A = X12\n const B = Fp.sqr(Y1); // B = Y12\n const C = Fp.mul(Fp.sqr(Z1), _2n); // C = 2*Z12\n const D = mulA(A); // D = a*A\n const x1y1 = Fp.addN(X1, Y1);\n const E = Fp.sub(Fp.subN(Fp.sqr(x1y1), A), B); // E = (X1+Y1)2-A-B\n const G = Fp.addN(D, B); // G = D+B\n const F = Fp.subN(G, C); // F = G-C\n const H = Fp.subN(D, B); // H = D-B\n const X3 = Fp.mul(E, F); // X3 = E*F\n const Y3 = Fp.mul(G, H); // Y3 = G*H\n const T3 = Fp.mul(E, H); // T3 = E*H\n const Z3 = Fp.mul(F, G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\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) {\n aedpoint(other);\n const { d } = CURVE;\n const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;\n const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;\n const A = Fp.mul(X1, X2); // A = X1*X2\n const B = Fp.mul(Y1, Y2); // B = Y1*Y2\n const C = Fp.mul(Fp.mulN(T1, d), T2); // C = T1*d*T2\n const D = Fp.mul(Z1, Z2); // D = Z1*Z2\n // E = (X1+Y1)*(X2+Y2)-A-B\n const E = Fp.sub(Fp.subN(Fp.mulN(Fp.addN(X1, Y1), Fp.addN(X2, Y2)), A), B);\n const F = Fp.subN(D, C); // F = D-C\n const G = Fp.addN(D, C); // G = D+C\n const H = Fp.sub(B, mulA(A)); // H = B-a*A\n const X3 = Fp.mul(E, F); // X3 = E*F\n const Y3 = Fp.mul(G, H); // Y3 = G*H\n const T3 = Fp.mul(E, H); // T3 = E*H\n const Z3 = Fp.mul(F, G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n subtract(other) {\n // Validate before calling `negate()` so wrong inputs fail with the point guard\n // instead of leaking a foreign `negate()` error.\n aedpoint(other);\n return this.add(other.negate());\n }\n // Constant-time multiplication.\n multiply(scalar) {\n // 1 <= scalar < L\n // Keep the subgroup-scalar contract strict instead of reducing 0 / n to ZERO.\n // In keygen/signing-style callers, those values usually mean broken hash/scalar plumbing,\n // and failing closed is safer than silently producing the identity point.\n if (!Fn.isValidNot0(scalar))\n throw new RangeError('invalid scalar: expected 1 <= sc < curve.n');\n const { p, f } = wnaf.mulSecret(this, scalar, cofactor, normalize);\n return normalize([p, f])[0];\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 // Keeps the same subgroup-scalar contract: 0 is allowed for public-scalar callers, but\n // n and larger values are rejected instead of being reduced mod n to the identity point.\n multiplyUnsafe(scalar) {\n // 0 <= scalar < L\n if (!Fn.isValid(scalar))\n throw new RangeError('invalid scalar: expected 0 <= sc < curve.n');\n if (scalar === _0n)\n return Point.ZERO;\n if (this.is0() || scalar === _1n)\n return this;\n return wnaf.mulUnsafe(this, scalar, normalize);\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 // Clears cofactor and checks if the result is 0.\n isSmallOrder() {\n return this.clearCofactor().is0();\n }\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree() {\n return wnaf.mulUnsafe(this, CURVE.n).is0();\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(invertedZ) {\n const p = this;\n let iz = invertedZ;\n if (iz != null && typeof iz !== 'bigint')\n throw new TypeError('\"invertedZ\" expected bigint, got type=' + typeof iz);\n const { X, Y, Z } = p;\n const is0 = p.is0();\n if (iz == null)\n iz = is0 ? Fp.create(_8n) : Fp.inv(Z);\n const x = Fp.mul(X, iz);\n const y = Fp.mul(Y, iz);\n const zz = Fp.mul(Z, iz);\n if (is0)\n return { x: Fp.ZERO, y: Fp.ONE };\n if (!Fp.eql(zz, Fp.ONE))\n throw new Error('invZ was invalid');\n return { x, y };\n }\n clearCofactor() {\n if (cofactor === _1n)\n return this;\n // 2.8-3.8x speed-up vs naive\n if (cofactor === _2n)\n return this.double();\n if (cofactor === _4n)\n return this.double().double();\n if (cofactor === _8n)\n return this.double().double().double();\n return this.multiplyUnsafe(cofactor);\n }\n toBytes() {\n const { x, y } = this.toAffine();\n // Fp.toBytes() allows non-canonical encoding of y (>= p).\n const bytes = Fp.toBytes(y);\n // Each y has 2 valid points: (x, y), (x,-y).\n // When compressing, it's enough to store y and use the last byte to encode sign of x\n bytes[bytes.length - 1] |= isOdd(x) ? 0x80 : 0;\n return bytes;\n }\n toHex() {\n return bytesToHex(this.toBytes());\n }\n toString() {\n return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n }\n }\n // Keep constructor work cheap: subgroup/generator validation belongs to the caller's curve\n // parameters, and doing the extra checks here adds about 10-15ms to heavy module imports.\n // Callers that construct custom curves are responsible for supplying the correct base point.\n // try {\n // Point.BASE.assertValidity();\n // if (!Point.BASE.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');\n // } catch {\n // throw new Error('bad curve params: generator point');\n // }\n const normalize = (points) => normalizeZ(Point, points);\n const wnaf = new ScalarMultiplier(Point, randomBytes);\n // Enable W=6 wNAF precomputes. Slows down first publicKey computation.\n // Disable for tiny toy curves, with scalar fields < 6 bits.\n if (wnaf.bits >= 6)\n Point.BASE.precompute(6);\n Object.freeze(Point.prototype);\n Object.freeze(Point);\n return Point;\n}\n/**\n * Base class for prime-order points like Ristretto255 and Decaf448.\n * These points eliminate cofactor issues by representing equivalence classes\n * of Edwards curve points. Multiple Edwards representatives can describe the\n * same abstract wrapper element, so wrapper validity is not the same thing as\n * the hidden representative being torsion-free.\n * @param ep - Backing Edwards point.\n * @example\n * Base class for prime-order points like Ristretto255 and Decaf448.\n *\n * ```ts\n * import { ristretto255 } from '@noble/curves/ed25519.js';\n * const point = ristretto255.Point.BASE.multiply(2n);\n * ```\n */\nexport class PrimeEdwardsPoint {\n static BASE;\n static ZERO;\n static Fp;\n static Fn;\n ep;\n /**\n * Wrap one internal Edwards representative directly.\n * This is not a canonical encoding boundary: alternate Edwards\n * representatives may still describe the same abstract wrapper element.\n */\n constructor(ep) {\n this.ep = ep;\n }\n // Static methods that must be implemented by subclasses\n static fromBytes(_bytes) {\n notImplemented();\n }\n static fromHex(_hex) {\n notImplemented();\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n // Common implementations\n clearCofactor() {\n // no-op for the abstract prime-order wrapper group; this is about the\n // wrapper element, not the hidden Edwards representative.\n return this;\n }\n assertValidity() {\n // Keep wrapper validity at the abstract-group boundary. Canonical decode\n // may choose Edwards representatives that differ by small torsion, so\n // checking `this.ep.isTorsionFree()` here would reject valid wrapper points.\n this.ep.assertValidity();\n }\n /**\n * Return affine coordinates of the current internal Edwards representative.\n * This is a convenience helper, not a canonical Ristretto/Decaf encoding.\n * Equal abstract elements may expose different `x` / `y`; use\n * `toBytes()` / `fromBytes()` for canonical roundtrips.\n */\n toAffine(invertedZ) {\n return this.ep.toAffine(invertedZ);\n }\n toHex() {\n return bytesToHex(this.toBytes());\n }\n toString() {\n return this.toHex();\n }\n isTorsionFree() {\n // Abstract Ristretto/Decaf elements are already prime-order even when the\n // hidden Edwards representative is not torsion-free.\n return true;\n }\n isSmallOrder() {\n return false;\n }\n add(other) {\n this.assertSame(other);\n return this.init(this.ep.add(other.ep));\n }\n subtract(other) {\n this.assertSame(other);\n return this.init(this.ep.subtract(other.ep));\n }\n multiply(scalar) {\n return this.init(this.ep.multiply(scalar));\n }\n multiplyUnsafe(scalar) {\n return this.init(this.ep.multiplyUnsafe(scalar));\n }\n double() {\n return this.init(this.ep.double());\n }\n negate() {\n return this.init(this.ep.negate());\n }\n precompute(windowSize, isLazy) {\n this.ep.precompute(windowSize, isLazy);\n // Keep the wrapper identity stable like the backing Edwards API instead of\n // allocating a fresh wrapper around the same cached point.\n return this;\n }\n}\n/**\n * Initializes EdDSA signatures over given Edwards curve.\n * @param Point - Edwards point constructor.\n * @param cHash - Hash function.\n * @param eddsaOpts - Optional signature helpers. See {@link EdDSAOpts}.\n * @returns EdDSA helper namespace.\n * @throws If the hash function, options, or derived point operations are invalid. {@link Error}\n * @example\n * Initializes EdDSA signatures over given Edwards curve.\n *\n * ```ts\n * import { eddsa } from '@noble/curves/abstract/edwards.js';\n * import { jubjub } from '@noble/curves/misc.js';\n * import { sha512 } from '@noble/hashes/sha2.js';\n * const sigs = eddsa(jubjub.Point, sha512);\n * const { secretKey, publicKey } = sigs.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = sigs.sign(msg, secretKey);\n * const isValid = sigs.verify(sig, msg, publicKey);\n * ```\n */\nexport function eddsa(Point, cHash, eddsaOpts = {}) {\n validatePointCons(Point);\n if (typeof cHash !== 'function')\n throw new Error('\"hash\" function param is required');\n const hash = cHash;\n const opts = eddsaOpts;\n validateObject(opts, {}, {\n adjustScalarBytes: 'function',\n randomBytes: 'function',\n domain: 'function',\n prehash: 'function',\n zip215: 'boolean',\n mapToCurve: 'function',\n toMontgomery: 'function',\n toMontgomerySecret: 'function',\n });\n const { prehash } = opts;\n const { BASE, Fp, Fn } = Point;\n const outputLen = hash.outputLen;\n const expectedLen = 2 * Fp.BYTES;\n // When hash metadata is available, reject incompatible EdDSA wrappers at construction time\n // instead of deferring the mismatch until the first keygen/sign call.\n if (outputLen !== undefined) {\n asafenumber(outputLen, 'hash.outputLen');\n if (outputLen !== expectedLen)\n throw new Error(`hash.outputLen must be ${expectedLen}, got ${outputLen}`);\n }\n const randomBytes = opts.randomBytes === undefined ? wcRandomBytes : opts.randomBytes;\n const toMontgomery = opts.toMontgomery;\n const toMontgomerySecret = opts.toMontgomerySecret;\n const adjustScalarBytes = opts.adjustScalarBytes === undefined\n ? (bytes) => bytes\n : opts.adjustScalarBytes;\n const domain = opts.domain === undefined\n ? (data, ctx, phflag) => {\n abool(phflag, 'phflag');\n if (ctx.length || phflag)\n throw new Error('Contexts/pre-hash are not supported');\n return data;\n }\n : opts.domain; // NOOP\n // Parse an EdDSA digest as a little-endian integer and reduce it modulo the scalar field order.\n function modN_LE(hash) {\n return Fn.create(bytesToNumberLE(hash)); // Not Fn.fromBytes: it has length limit\n }\n // Get the hashed private scalar per RFC8032 5.1.5\n function getPrivateScalar(key) {\n const len = lengths.secretKey;\n abytes(key, lengths.secretKey, 'secretKey');\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 = abytes(hash(key), 2 * len, 'hashedSecretKey');\n // Slice before clamping so in-place adjustors don't corrupt the prefix half.\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 return { head, prefix, scalar };\n }\n /** Convenience method that creates public key from scalar. RFC8032 5.1.5\n * Also exposes the derived scalar/prefix tuple and point form reused by sign().\n */\n function getExtendedPublicKey(secretKey) {\n const { head, prefix, scalar } = getPrivateScalar(secretKey);\n const point = BASE.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toBytes();\n return { head, prefix, scalar, point, pointBytes };\n }\n /** Calculates EdDSA pub key. RFC8032 5.1.5. */\n function getPublicKey(secretKey) {\n return getExtendedPublicKey(secretKey).pointBytes;\n }\n // Hash domain-separated chunks into a little-endian scalar modulo the group order.\n function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {\n const msg = concatBytes(...msgs);\n return modN_LE(hash(domain(msg, abytes(context, undefined, 'context'), !!prehash)));\n }\n /** Signs message with secret key. RFC8032 5.1.6 */\n function sign(msg, secretKey, options = {}) {\n validateObject(options, {}, {}, 'options');\n // Snapshot once: nonce and challenge must use the same invocation-time message bytes.\n msg = copyBytes(abytes(msg, undefined, 'message'));\n if (prehash)\n msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n // RFC 8032 5.1.6 allows r mod L = 0, and SUPERCOP ref10 accepts the resulting identity-point\n // signature.\n // We intentionally keep the safe multiply() rejection here so a miswired all-zero hash provider\n // fails loudly instead of silently producing a degenerate signature.\n const R = BASE.multiply(r).toBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = Fn.create(r + k * scalar); // S = (r + k * s) mod L\n if (!Fn.isValid(s))\n throw new Error('sign failed: invalid s'); // 0 <= s < L\n const rs = concatBytes(R, Fn.toBytes(s));\n return abytes(rs, lengths.signature, 'result');\n }\n // Keep the shared helper strict by default: RFC 8032 / NIST-style wrappers should reject\n // non-canonical encodings unless they explicitly opt into ZIP-215's more permissive decode rules.\n const verifyOpts = {\n zip215: opts.zip215,\n };\n /**\n * Verifies EdDSA signature against message and public key. RFC 8032 \u00A7\u00A75.1.7 and 5.2.7.\n * A cofactored verification equation is checked.\n */\n function verify(sig, msg, publicKey, options = verifyOpts) {\n // Validate before destructuring so explicit null follows the standard options error.\n validateObject(options);\n // Preserve the wrapper-selected default for `{}` / `{ zip215: undefined }`, not just omitted opts.\n const { context } = options;\n const zip215 = options.zip215 === undefined ? !!verifyOpts.zip215 : options.zip215;\n const len = lengths.signature;\n sig = abytes(sig, len, 'signature');\n msg = abytes(msg, undefined, 'message');\n publicKey = abytes(publicKey, lengths.publicKey, 'publicKey');\n if (zip215 !== undefined)\n abool(zip215, 'zip215');\n if (prehash)\n msg = prehash(msg); // for ed25519ph, etc\n const mid = len / 2;\n const r = sig.subarray(0, mid);\n const s = bytesToNumberLE(sig.subarray(mid, len));\n let A, R, SB;\n try {\n // ZIP-215 is more permissive than RFC 8032 / NIST186-5. Use it only for wrappers that\n // explicitly want consensus-style unreduced encoding acceptance.\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n A = Point.fromBytes(publicKey, zip215);\n R = Point.fromBytes(r, zip215);\n SB = BASE.multiplyUnsafe(s); // 0 <= s < l is done inside\n }\n catch (error) {\n return false;\n }\n // RFC 8032 \u00A7\u00A75.1.7/5.2.7 and FIPS 186-5 \u00A7\u00A77.7.2/7.8.2 only decode A' and check the cofactored\n // verification equation; they do not add a separate low-order-public-key rejection here.\n // Strict mode still rejects small-order A' intentionally for SBS-style non-repudiation and to\n // avoid ambiguous verification outcomes where unusual low-order keys can make distinct\n // key/signature/message combinations verify.\n if (!zip215 && A.isSmallOrder())\n return false;\n // ZIP-215 accepts noncanonical / unreduced point encodings, so the challenge hash must use the\n // exact signature/public-key bytes rather than canonicalized re-encodings of the decoded points.\n const k = hashDomainToScalar(context, r, publicKey, msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // Check the cofactored verification equation via the curve cofactor h.\n // [h][S]B = [h]R + [h][k]A'\n return RkA.subtract(SB).clearCofactor().is0();\n }\n const _size = Fp.BYTES; // 32 for ed25519, 57 for ed448\n const lengths = {\n secretKey: _size,\n publicKey: _size,\n signature: 2 * _size,\n seed: _size,\n };\n function randomSecretKey(seed) {\n seed = seed === undefined ? randomBytes(lengths.seed) : seed;\n return abytes(seed, lengths.seed, 'seed');\n }\n function isValidSecretKey(key) {\n return isBytes(key) && key.length === lengths.secretKey;\n }\n function isValidPublicKey(key, zip215) {\n try {\n // Preserve the wrapper-selected default for omitted / `undefined` ZIP-215 flags here too.\n return !!Point.fromBytes(key, zip215 === undefined ? verifyOpts.zip215 : zip215);\n }\n catch (error) {\n return false;\n }\n }\n const utils = {\n getExtendedPublicKey,\n randomSecretKey,\n isValidSecretKey,\n isValidPublicKey,\n /** Converts an Edwards public key to a companion Montgomery public key. */\n toMontgomery(publicKey) {\n if (toMontgomery === undefined)\n throw new Error('Montgomery conversion is not supported for this curve');\n return toMontgomery(Point.fromBytes(publicKey));\n },\n toMontgomerySecret(secretKey) {\n if (toMontgomerySecret === undefined)\n throw new Error('Montgomery conversion is not supported for this curve');\n return toMontgomerySecret(secretKey);\n },\n };\n Object.freeze(lengths);\n Object.freeze(utils);\n return Object.freeze({\n keygen: createKeygen(randomSecretKey, getPublicKey),\n getPublicKey,\n sign,\n verify,\n utils,\n Point,\n lengths,\n });\n}\n", "/**\n * Montgomery curve methods. It's not really whole montgomery curve,\n * just bunch of very specific methods for X25519 / X448 from\n * [RFC 7748](https://www.rfc-editor.org/rfc/rfc7748)\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abytes, aInRange, bytesToNumberLE, copyBytes, numberToBytesLE, randomBytes, validateObject, } from \"../utils.js\";\nimport { createKeygen } from \"./curve.js\";\nimport { mod } from \"./modular.js\";\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\n// cswap from RFC7748 \"example code\", adapted to BigInt.\n//\n// RFC: \"dummy = mask(swap) AND (x_2 XOR x_3), where mask(swap) is the all-1 or all-0 word of the\n// same length as x_2 and x_3\". On fixed-width machine words both cases cost the same. BigInt has\n// no fixed width, so a {0n, 1n} selector does not: V8 short-circuits `0n * v` - and, identically,\n// `0n & v`, `v + 0n`, `v - 0n` - to a no-op, while `1n * v` is a real multiply. The ladder calls\n// this with swap = k_t XOR k_(t+1), which would make total running time a linear function of how\n// often adjacent bits of the secret scalar differ: remotely measurable, and worth ~4 bits of a\n// long-term key.\n//\n// So select with a full-width mask instead, and interpolate rather than mask off a dummy.\n/**\n * Selector for cswap(): `P` to keep, `P + 1` to swap, chosen by the low bit of `swap`.\n * Higher bits are ignored, and `swap` is passed in whole rather than as a {0n, 1n} bit on\n * purpose: `P + (swap & _1n)` would short-circuit the addition whenever the bit is clear, which\n * is the very leak this construction avoids, one round-trip further down. Subtracting `swap`\n * with its low bit cleared keeps every operand full-width instead.\n * @param P - Field modulus.\n * @param swap - Value whose low bit selects; ignored above that bit.\n * @returns `P` when the low bit is clear, `P + 1` when it is set.\n */\nfunction cmask(P, swap) {\n return P + swap - ((swap >> _1n) << _1n);\n}\n/**\n * Swap two field elements when `mask` is `P + 1`, keep them when it is `P`:\n *\n * d = 6P + x_3 - x_2\n * x_2' = d * mask + x_2 (mod P) x_3' = (x_2 + x_3) - x_2'\n *\n * The extra `6P * mask` vanishes modulo P, so `mask === P` leaves x_2 and `mask === P + 1`\n * leaves x_3. Without the offset, the reduction dividend changes sign with input order and crosses\n * BigInt limb boundaries; those classes measured differently on the tested Node/V8 build. For\n * canonical inputs, the deliberately left-associative `offset + x_3 - x_2` is between 5P and 7P,\n * keeping the dividend positive and in one word-count band for both RFC fields and masks. Six is\n * the smallest coefficient `c` for which the shared offset `cP` has that property.\n *\n * This reduced the tested sign/size timing ratios, but JavaScript BigInt has no constant-time\n * contract and the contents of the multiply and remainder still vary. Valid ladder states can\n * contain genuine zero coordinates; this construction does not mask those value-shape effects.\n * Computing `x_3'` independently as `((6P + x_2 - x_3) * mask + x_3) % P` is more symmetric.\n * On the tested Node/V8 build, it reduced the timing difference between keeping `(0, v)` and\n * swapping `(v, 0)`\u2014both return `(0, v)`\u2014from about 10%/13% for X25519/X448 to about 3%.\n * Successful calls cannot reach that zero-in-the-first-output case. For the case they can reach,\n * swapping `(0, v)` and keeping `(v, 0)` both return `(v, 0)`; the difference instead grew from\n * about 0.7%/1.1% to 2.7%/2.8%. The extra multiply/remainder also made public\n * `getSharedSecret()` about 16% slower. The retained one-remainder form measured about 2.5%\n * slower than the prior helper for public X25519 `getSharedSecret()` in the same environment.\n * x_3' falls out of the sum, which a swap leaves invariant: no second multiply or reduction is\n * needed. Bind `6P` once per field so production and the timing regression exercise the same\n * configured helper without paying for the multiplication in every ladder round.\n *\n * The returned function is called twice per ladder round, so it validates nothing. Both elements\n * MUST already be reduced mod P; unreduced input silently corrupts the kept-side output.\n * @param P - Field modulus.\n * @returns A field-bound swap function taking mask, x_2, and x_3.\n */\nfunction cswap(P) {\n const offset = BigInt(6) * P;\n return (mask, x_2, x_3) => {\n const sum = x_2 + x_3;\n const d = offset + x_3 - x_2;\n const a = (d * mask + x_2) % P;\n return { x_2: a, x_3: sum - a };\n };\n}\n/** Internal helpers, exported for tests only. Not part of the public API. */\nexport const __TEST = /* @__PURE__ */ Object.freeze({\n cmask,\n cswap,\n});\nfunction validateOpts(curve) {\n // Validate constructor config eagerly, but do not call user-provided hooks here:\n // `randomBytes` may be transcript-backed or otherwise contextual. Runtime type checks are\n // enough to fail fast on malformed configs without consuming user state.\n validateObject(curve, {\n P: 'bigint',\n type: 'string',\n adjustScalarBytes: 'function',\n powPminus2: 'function',\n }, {\n randomBytes: 'function',\n scalarMultBase: 'function',\n });\n return Object.freeze({ ...curve });\n}\n/**\n * @param curveDef - Montgomery curve definition.\n * @returns ECDH helper namespace.\n * @throws If the curve definition or derived shared point is invalid. {@link Error}\n * @example\n * Build an X25519 helper from curve parameters, then derive one public key.\n *\n * ```ts\n * import { montgomery } from '@noble/curves/abstract/montgomery.js';\n * const P = 2n ** 255n - 19n;\n * const mod = (num: bigint) => {\n * const out = num % P;\n * return out >= 0n ? out : out + P;\n * };\n * const pow = (num: bigint, power: bigint) => {\n * let res = 1n;\n * for (; power > 0n; power >>= 1n) {\n * if (power & 1n) res = mod(res * num);\n * num = mod(num * num);\n * }\n * return res;\n * };\n * const x25519 = montgomery({\n * P,\n * type: 'x25519',\n * adjustScalarBytes(bytes: Uint8Array) {\n * bytes[0] &= 248;\n * bytes[31] &= 127;\n * bytes[31] |= 64;\n * return bytes;\n * },\n * powPminus2(x) {\n * return pow(x, P - 2n);\n * },\n * });\n * const publicKey = x25519.getPublicKey(new Uint8Array(32).fill(1));\n * ```\n */\nexport function montgomery(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { P, type, adjustScalarBytes, powPminus2, randomBytes: rand } = CURVE;\n const mulBaseHook = CURVE.scalarMultBase;\n const is25519 = type === 'x25519';\n if (!is25519 && type !== 'x448')\n throw new Error('invalid type');\n const randomBytes_ = rand === undefined ? randomBytes : rand;\n const montgomeryBits = is25519 ? 255 : 448;\n const swap = cswap(P);\n const fieldLen = is25519 ? 32 : 56;\n const Gu = is25519 ? BigInt(9) : BigInt(5);\n // RFC 7748 #5:\n // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 and\n // (156326 - 2) / 4 = 39081 for curve448/X448\n // const a = is25519 ? 486662n : 156326n;\n const a24 = is25519 ? BigInt(121665) : BigInt(39081);\n // RFC: x25519 \"the resulting integer is of the form 2^254 plus\n // eight times a value between 0 and 2^251 - 1 (inclusive)\"\n // x448: \"2^447 plus four times a value between 0 and 2^445 - 1 (inclusive)\"\n const minScalar = is25519 ? _2n ** BigInt(254) : _2n ** BigInt(447);\n const maxAdded = is25519\n ? BigInt(8) * (_2n ** BigInt(251) - _1n)\n : BigInt(4) * (_2n ** BigInt(445) - _1n);\n const maxScalar = minScalar + maxAdded + _1n; // (inclusive)\n const modP = (n) => mod(n, P);\n const GuBytes = encodeU(Gu);\n function encodeU(u) {\n return numberToBytesLE(modP(u), fieldLen);\n }\n function decodeU(u) {\n const _u = copyBytes(abytes(u, fieldLen, 'uCoordinate'));\n // RFC: When receiving such an array, implementations of X25519\n // (but not X448) MUST mask the most significant bit in the final byte.\n if (is25519)\n _u[31] &= 127; // 0b0111_1111\n // RFC: Implementations MUST accept non-canonical values and process them as\n // if they had been reduced modulo the field prime. The non-canonical\n // values are 2^255 - 19 through 2^255 - 1 for X25519 and 2^448 - 2^224\n // - 1 through 2^448 - 1 for X448.\n return modP(bytesToNumberLE(_u));\n }\n function decodeScalar(scalar) {\n return bytesToNumberLE(adjustScalarBytes(copyBytes(abytes(scalar, fieldLen, 'scalar'))));\n }\n /**\n * u coordinates whose order divides the cofactor, on the curve and on its quadratic twist -\n * the ladder sends every one of them to zero. Same blocklist libsodium and post-CVE-2017-0379\n * Libgcrypt carry. decodeU() reduces mod P first, so the non-canonical encodings P and P + 1\n * collapse onto 0 and 1, and `type` admits no curve beyond these two, so both lists are total.\n *\n * Complete by construction: x-only doubling sends u to (u^2 - 1)^2 / 4u(u^2 + a*u + 1). Order 4\n * therefore needs (u^2 - 1)^2 === 0, i.e. u = +-1; order 2 needs u(u^2 + a*u + 1) === 0, and\n * a^2 - 4 is a non-residue on both curves, leaving u = 0. curve448 stops there (cofactor 4);\n * curve25519 (cofactor 8) adds the two order-8 roots below. Cross-checked by clearing the\n * cofactor with those same doublings over 200k random u: no sixth value exists.\n */\n const lowOrderU = new Set(is25519\n ? [\n _0n,\n _1n,\n P - _1n,\n BigInt('325606250916557431795983626356110631294008115727848805560023387167927233504'),\n BigInt('39382357235489614581723060781553021112529911719440698176882885853963445705823'),\n ]\n : [_0n, _1n, P - _1n]);\n function scalarMult(scalar, u) {\n // Some public keys are useless, of low-order. Curve author doesn't think\n // it needs to be validated, but we do it nonetheless.\n // https://cr.yp.to/ecdh.html#validate\n //\n // Reject them BEFORE the ladder. RFC 7748 #6.1 also permits detecting them from the\n // all-zero output, but that first runs all 255 rounds against the long-term secret,\n // handing an unauthenticated attacker a free timing oracle. Low-order inputs also drive\n // the ladder into a degenerate state (x_2 + z_2 === 0) whose extra zero-operand\n // multiplications amplify any residual key-dependent timing.\n const pointU = decodeU(u);\n if (lowOrderU.has(pointU))\n throw new Error('invalid private or public key received');\n const pu = montgomeryLadder(pointU, decodeScalar(scalar));\n // Unreachable for RFC 7748 clamped scalars, which are cofactor multiples smaller than the\n // group order; kept because adjustScalarBytes is caller-supplied.\n if (pu === _0n)\n throw new Error('invalid private or public key received');\n return encodeU(pu);\n }\n // Computes public key from private. By doing scalar multiplication of base point.\n // With a curve-provided fixed-base hook (Edwards tables), the ladder is skipped, but the\n // contract \u2014 scalar validation, low-order rejection, encoding \u2014 stays identical.\n function scalarMultBase(scalar) {\n if (mulBaseHook === undefined)\n return scalarMult(scalar, GuBytes);\n const k = decodeScalar(scalar);\n aInRange('scalar', k, minScalar, maxScalar);\n const pu = modP(mulBaseHook(k));\n if (pu === _0n)\n throw new Error('invalid private or public key received');\n return encodeU(pu);\n }\n const getPublicKey = scalarMultBase;\n const getSharedSecret = scalarMult;\n /**\n * Montgomery x-only multiplication ladder for the selected X25519/X448 curve.\n * @param pointU - decoded Montgomery u coordinate for the selected curve\n * @param scalar - decoded clamped scalar by which the point is multiplied\n * @returns resulting Montgomery u coordinate for the selected curve\n */\n function montgomeryLadder(u, scalar) {\n aInRange('u', u, _0n, P);\n aInRange('scalar', scalar, minScalar, maxScalar);\n const k = 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 // The RFC tracks `swap` across rounds to hold k_t XOR k_(t+1); the low bit of `kx >> t` is\n // the same value, without the carried state. aInRange above pins bit (montgomeryBits - 1)\n // of k set and everything above it clear, so `kx >> t` is never zero and its width is a\n // function of t alone - never of a secret bit.\n const kx = k ^ (k >> _1n);\n for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {\n const mask = cmask(P, kx >> t);\n ({ x_2, x_3 } = swap(mask, x_2, x_3));\n ({ x_2: z_2, x_3: z_3 } = swap(mask, z_2, z_3));\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 // trailing cswap: the RFC's `swap` holds k_0 here, which is the low bit of k\n const mask = cmask(P, k);\n ({ x_2, x_3 } = swap(mask, x_2, x_3));\n ({ x_2: z_2, x_3: z_3 } = swap(mask, z_2, z_3));\n const z2 = powPminus2(z_2); // `Fp.pow(x, P - _2n)` is much slower equivalent\n return modP(x_2 * z2); // Return x_2 * (z_2^(p - 2))\n }\n const lengths = {\n secretKey: fieldLen,\n publicKey: fieldLen,\n seed: fieldLen,\n };\n const randomSecretKey = (seed) => {\n seed = seed === undefined ? randomBytes_(fieldLen) : seed;\n abytes(seed, lengths.seed, 'seed');\n // Reuse caller-supplied seed bytes verbatim; clamping is deferred until\n // decodeScalar(...) when the secret key is actually used.\n return seed;\n };\n const utils = { randomSecretKey };\n Object.freeze(lengths);\n Object.freeze(utils);\n return Object.freeze({\n keygen: createKeygen(randomSecretKey, getPublicKey),\n getSharedSecret,\n getPublicKey,\n scalarMult,\n scalarMultBase,\n utils,\n GuBytes: GuBytes.slice(),\n lengths,\n });\n}\n", "/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, aoutput, clean, } from \"./utils.js\";\n/**\n * Internal class for HMAC.\n * Accepts any byte key, although RFC 2104 \u00A73 recommends keys at least\n * `HashLen` bytes long.\n */\nexport class _HMAC {\n oHash;\n iHash;\n blockLen;\n outputLen;\n canXOF = false;\n finished = false;\n destroyed = false;\n constructor(hash, key) {\n ahash(hash);\n abytes(key, undefined, 'key');\n this.iHash = hash.create();\n if (typeof this.iHash.update !== 'function')\n throw new Error('expected Hash instance');\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++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of the first block) of the outer hash here,\n // we can re-use it between multiple calls via clone.\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n clean(pad);\n }\n update(buf) {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const buf = out.subarray(0, this.outputLen);\n // Reuse the first outputLen bytes for the inner digest; the outer hash consumes them before\n // overwriting that same prefix with the final tag, leaving any oversized tail untouched.\n this.iHash.digestInto(buf);\n this.oHash.update(buf);\n this.oHash.digestInto(buf);\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) {\n // Create new instance without calling constructor since the key\n // is already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen, canXOF } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.canXOF = canXOF;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\nexport const hmac = /* @__PURE__ */ (() => {\n const hmac_ = ((hash, key, message) => new _HMAC(hash, key).update(message).digest());\n hmac_.create = (hash, key) => new _HMAC(hash, key);\n return hmac_;\n})();\n", "/**\n * ASN.1 DER (Distinguished Encoding Rules) helpers for ECDSA signatures.\n * Only implements the tiny subset needed for `SEQUENCE(INTEGER r, INTEGER s)`.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abignumber, abytes, asafenumber, astring, bytesToNumberBE, numberToHexUnpadded, validateObject, } from \"../utils.js\";\nconst _0n = /* @__PURE__ */ BigInt(0);\n/**\n * @param m - Error message.\n * @example\n * Throw a DER-specific error when signature parsing encounters invalid bytes.\n *\n * ```ts\n * new DERErr('bad der');\n * ```\n */\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\n// Plain const so the freezes can live inside the pure initializer of the `DER` export below:\n// bare top-level `Object.freeze(...)` calls would defeat tree-shaking for every importer.\nconst _DER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag, data) => {\n const { Err: E } = _DER;\n asafenumber(tag, 'tag');\n if (tag < 0 || tag > 255)\n throw new E('tlv.encode: wrong tag');\n astring(data, 'data');\n // Internal helper: callers hand this already-validated hex payload, so we only enforce\n // byte alignment here instead of re-validating every nibble.\n if (data.length & 1)\n throw new E('tlv.encode: unpadded data');\n const dataLen = data.length / 2;\n const len = numberToHexUnpadded(dataLen);\n if ((len.length / 2) & 0b1000_0000)\n throw new E('tlv.encode: long form length too big');\n // length of length with long form flag\n const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';\n const t = numberToHexUnpadded(tag);\n return t + lenLen + len + data;\n },\n // v - value, l - left bytes (unparsed)\n decode(tag, data) {\n const { Err: E } = _DER;\n data = abytes(data, undefined, 'DER data');\n let pos = 0;\n if (tag < 0 || tag > 255)\n throw new E('tlv.decode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag)\n throw new E('tlv.decode: wrong tlv');\n const first = data[pos++];\n // First bit of first length byte is the short/long form flag.\n const isLong = !!(first & 0b1000_0000);\n let length = 0;\n if (!isLong)\n length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 0b0111_1111;\n if (!lenLen)\n throw new E('tlv.decode(long): indefinite length not supported');\n // This would overflow u32 in JS.\n if (lenLen > 4)\n throw new E('tlv.decode(long): byte length is too big');\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen)\n throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0)\n throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes)\n length = (length << 8) | b;\n pos += lenLen;\n if (length < 128)\n throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length)\n throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) };\n },\n },\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 _int: {\n encode(num) {\n const { Err: E } = _DER;\n abignumber(num);\n if (num < _0n)\n throw new E('integer: negative integers are not allowed');\n let hex = numberToHexUnpadded(num);\n // Pad with zero byte if negative flag is present\n if (Number.parseInt(hex[0], 16) & 0b1000)\n hex = '00' + hex;\n if (hex.length & 1)\n throw new E('unexpected DER parsing assertion: unpadded hex');\n return hex;\n },\n decode(data) {\n const { Err: E } = _DER;\n if (data.length < 1)\n throw new E('invalid signature integer: empty');\n if (data[0] & 0b1000_0000)\n throw new E('invalid signature integer: negative');\n // Single-byte zero `00` is the canonical DER INTEGER encoding for zero.\n if (data.length > 1 && data[0] === 0x00 && !(data[1] & 0b1000_0000))\n throw new E('invalid signature integer: unnecessary leading zero');\n return bytesToNumberBE(data);\n },\n },\n toSig(bytes, maxScalarBytes) {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = _DER;\n if (maxScalarBytes !== undefined) {\n asafenumber(maxScalarBytes, 'maxScalarBytes');\n if (maxScalarBytes < 1)\n throw new E('invalid signature: maxScalarBytes must be positive');\n }\n const data = abytes(bytes, undefined, 'signature');\n const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n if (seqLeftBytes.length)\n throw new E('invalid signature: left bytes after parsing');\n const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n if (sLeftBytes.length)\n throw new E('invalid signature: left bytes after parsing');\n // Enforce curve-provided bounds before bytes-to-hex-to-BigInt conversion can amplify memory.\n if (maxScalarBytes !== undefined &&\n (rBytes.length > maxScalarBytes || sBytes.length > maxScalarBytes))\n throw new E('invalid signature: integer too large');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig) {\n const { _tlv: tlv, _int: int } = _DER;\n validateObject(sig, { r: 'bigint', s: 'bigint' }, {}, 'sig');\n const rs = tlv.encode(0x02, int.encode(sig.r));\n const ss = tlv.encode(0x02, int.encode(sig.s));\n const seq = rs + ss;\n return tlv.encode(0x30, seq);\n },\n};\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: {@link https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/ | Let's Encrypt ASN.1 guide} and\n * {@link https://luca.ntop.org/Teaching/Appunti/asn1.html | Luca Deri's ASN.1 notes}.\n * @example\n * ASN.1 DER encoding utilities.\n *\n * ```ts\n * const der = DER.hexFromSig({ r: 1n, s: 2n });\n * ```\n */\nexport const DER = /* @__PURE__ */ (() => {\n Object.freeze(_DER._tlv);\n Object.freeze(_DER._int);\n return Object.freeze(_DER);\n})();\n", "/**\n * Short Weierstrass curve methods. The formula is: y\u00B2 = x\u00B3 + ax + b.\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\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * 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 * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac as nobleHmac } from '@noble/hashes/hmac.js';\nimport { ahash } from '@noble/hashes/utils.js';\nimport { abool, abytes, aInRange, bitLen, bitMask, bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, hexToBytes, isBytes, validateObject, randomBytes as wcRandomBytes, } from \"../utils.js\";\nimport { createCurveFields, createKeygen, mulAddUnsafe, normalizeZ, probeRandomBytes, ScalarMultiplier, validatePointCons, } from \"./curve.js\";\nimport { DER } from \"./der.js\";\nimport { getMinHashLength, invertCt, mapHashToField } from \"./modular.js\";\n// DER codec lives in der.ts; re-exported here because ECDSA signatures are its main consumer.\nexport { DER, DERErr } from \"./der.js\";\n// We construct the basis so `den` is always positive and equals `n`,\n// but the `num` sign depends on the basis, not on the secret value.\n// Exact half-way cases round away from zero, which keeps the split symmetric\n// around the reduced-basis boundaries used by endomorphism decomposition.\nconst divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n) / den;\n/** Splits scalar for GLV endomorphism. */\nexport function _splitEndoScalar(k, basis, n) {\n // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`\n // Since part can be negative, we need to do this on point.\n // Callers must provide a reduced GLV basis whose vectors satisfy\n // `a + b * lambda \u2261 0 (mod n)`; this helper only sees the basis and `n`.\n // Reject unreduced scalars instead of silently treating them mod n.\n aInRange('scalar', k, _0n, n);\n // TODO: verifyScalar function which consumes lambda\n const [[a1, b1], [a2, b2]] = basis;\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n // |k1|/|k2| is < sqrt(N), but can be negative.\n // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.\n let k1 = k - c1 * a1 - c2 * a2;\n let k2 = -c1 * b1 - c2 * b2;\n const k1neg = k1 < _0n;\n const k2neg = k2 < _0n;\n if (k1neg)\n k1 = -k1;\n if (k2neg)\n k2 = -k2;\n // Double check that resulting scalar is less than half bits of N: the wNAF pair walk\n // relies on the halves being short. This should only happen on wrong bases.\n // Also, the math inside is complex enough that this guard is worth keeping.\n const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N\n if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {\n throw new Error('splitScalar (endomorphism): failed for k');\n }\n return { k1neg, k1, k2neg, k2 };\n}\nfunction validateSigFormat(format) {\n if (!['compact', 'recovered', 'der'].includes(format))\n throw new Error('Signature format must be \"compact\", \"recovered\", or \"der\"');\n return format;\n}\nfunction validateSigOpts(opts, def) {\n validateObject(opts);\n const optsn = {};\n // Normalize only the declared option subset from `def`; unknown keys are\n // intentionally ignored so shared / superset option bags stay valid here too.\n // `extraEntropy` stays an opaque payload until the signing path consumes it.\n for (let optName of Object.keys(def)) {\n // @ts-ignore\n optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];\n }\n abool(optsn.lowS, 'lowS');\n abool(optsn.prehash, 'prehash');\n if (optsn.format !== undefined)\n validateSigFormat(optsn.format);\n return optsn;\n}\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4);\n/**\n * Creates weierstrass Point constructor, based on specified curve options.\n *\n * See {@link WeierstrassOpts}.\n * @param params - Curve parameters. See {@link WeierstrassOpts}.\n * @param extraOpts - Optional helpers and overrides. See {@link WeierstrassExtraOpts}.\n * @returns Weierstrass point constructor.\n * @throws If the curve parameters, overrides, or point codecs are invalid. {@link Error}\n *\n * @example\n * Construct a point type from explicit Weierstrass curve parameters.\n *\n * ```js\n * const opts = {\n * p: 0xfffffffffffffffffffffffffffffffeffffac73n,\n * n: 0x100000000000000000001b8fa16dfab9aca16b6b3n,\n * h: 1n,\n * a: 0n,\n * b: 7n,\n * Gx: 0x3b4c382ce37aa192a4019e763036f4f5dd4d7ebbn,\n * Gy: 0x938cf935318fdced6bc28286531733c3f03c4feen,\n * };\n * const secp160k1_Point = weierstrass(opts);\n * ```\n */\nexport function weierstrass(params, extraOpts = {}) {\n const validated = createCurveFields('weierstrass', params, extraOpts);\n const Fp = validated.Fp;\n const Fn = validated.Fn;\n let CURVE = validated.CURVE;\n const { h: cofactor, n: CURVE_ORDER } = CURVE;\n validateObject(extraOpts, {}, {\n allowInfinityPoint: 'boolean',\n clearCofactor: 'function',\n isTorsionFree: 'function',\n fromBytes: 'function',\n toBytes: 'function',\n endo: 'object',\n randomBytes: 'function',\n });\n // Snapshot every hook and take an owned copy of nested GLV configuration. Later mutations of\n // the caller's options must not change arithmetic, subgroup, or codec policy.\n const { endo: endoOpts, allowInfinityPoint, clearCofactor, isTorsionFree, fromBytes, toBytes, } = extraOpts;\n const randomBytes = extraOpts.randomBytes === undefined ? wcRandomBytes : extraOpts.randomBytes;\n if (endoOpts) {\n if (!Fp.is0(CURVE.a) || typeof endoOpts.beta !== 'bigint' || !Array.isArray(endoOpts.basises)) {\n throw new Error('invalid endo: expected \"beta\": bigint and \"basises\": array');\n }\n }\n const endo = endoOpts\n ? {\n beta: endoOpts.beta,\n basises: endoOpts.basises.map((basis) => [...basis]),\n }\n : undefined;\n const lengths = getWLengths(Fp, Fn);\n function assertCompressionIsSupported() {\n if (!Fp.isOdd)\n throw new Error('compression is not supported: Field does not have .isOdd()');\n }\n // Implements IEEE P1363 point encoding\n function pointToBytes(_c, point, isCompressed) {\n // Handle infinity before toAffine(), which maps ZERO to (0, 0) silently: without this the\n // encoder would emit an all-zero byte string that decodes back as a different point. Only\n // curves that opt into infinity as a public point value get the SEC 1 byte form.\n if (point.is0()) {\n if (!allowInfinityPoint)\n throw new Error('bad point: ZERO');\n return Uint8Array.of(0); // SEC 1 v2.0 \u00A72.3.3\n }\n const { x, y } = point.toAffine();\n const bx = Fp.toBytes(x);\n abool(isCompressed, 'isCompressed');\n if (isCompressed) {\n assertCompressionIsSupported();\n const hasEvenY = !Fp.isOdd(y);\n return concatBytes(pprefix(hasEvenY), bx);\n }\n else {\n return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));\n }\n }\n function pointFromBytes(bytes) {\n abytes(bytes, undefined, 'Point');\n const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65\n const length = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // SEC 1 v2.0 \u00A72.3.4 decodes 0x00 as infinity, but \u00A73.2.2 rejects infinity as a public key.\n // Leaving 0x00 undecodable by default makes that rejection structural rather than a check:\n // callers reuse this parser as the strict key boundary, and infinity is simply not\n // expressible. Curves where infinity is a real wire value opt into the codec instead.\n // secp256k1 crosstests show OpenSSL raw point codecs accept 0x00 too.\n if (allowInfinityPoint && length === 1 && head === 0x00)\n return { x: Fp.ZERO, y: Fp.ZERO };\n // No actual validation is done here: use .assertValidity()\n if (length === comp && (head === 0x02 || head === 0x03)) {\n const x = Fp.fromBytes(tail);\n if (!Fp.isValid(x))\n throw new Error('bad point: is not on curve, wrong x');\n const y2 = weierstrassEquation(x); // y\u00B2 = x\u00B3 + ax + b\n let y;\n try {\n y = Fp.sqrt(y2); // y = y\u00B2 ^ (p+1)/4\n }\n catch (sqrtError) {\n const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('bad point: is not on curve, sqrt error' + err);\n }\n assertCompressionIsSupported();\n const evenY = Fp.isOdd(y);\n const evenH = (head & 1) === 1; // ECDSA-specific\n if (evenH !== evenY)\n y = Fp.neg(y);\n return { x, y };\n }\n else if (length === uncomp && head === 0x04) {\n // TODO: more checks\n const L = Fp.BYTES;\n const x = Fp.fromBytes(tail.subarray(0, L));\n const y = Fp.fromBytes(tail.subarray(L, L * 2));\n if (!isValidXY(x, y))\n throw new Error('bad point: is not on curve');\n return { x, y };\n }\n else {\n throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);\n }\n }\n const encodePoint = toBytes === undefined ? pointToBytes : toBytes;\n const decodePoint = fromBytes === undefined ? pointFromBytes : fromBytes;\n // Hoisted from double() / add(): curve params never change after construction.\n // Koblitz curves (a=0, e.g. secp256k1) skip the three a-multiplications per operation;\n // the selection depends only on public curve constants.\n const b3 = Fp.mul(CURVE.b, _3n);\n const mulA = Fp.is0(CURVE.a) ? (_) => Fp.ZERO : (x) => Fp.mul(CURVE.a, x);\n function weierstrassEquation(x) {\n const x2 = Fp.sqr(x);\n const x3 = Fp.mul(x2, x);\n return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x\u00B3 + a * x + b\n }\n // TODO: move top-level\n /** Checks whether equation holds for given x, y: y\u00B2 == x\u00B3 + ax + b */\n function isValidXY(x, y) {\n const left = Fp.sqr(y);\n const right = weierstrassEquation(x); // x\u00B3 + ax + b\n return Fp.eql(left, right);\n }\n // Keep constructor-time generator validation cheap: callers are responsible for supplying the\n // correct prime-order base point, while eager subgroup checks here would slow heavy module imports.\n // Test 1: equation y\u00B2 = x\u00B3 + ax + b should work for generator point.\n if (!isValidXY(CURVE.Gx, CURVE.Gy))\n throw new Error('bad curve params: generator point');\n // Test 2: discriminant \u0394 part should be non-zero: 4a\u00B3 + 27b\u00B2 != 0.\n // Guarantees curve is genus-1, smooth (non-singular).\n const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n if (Fp.is0(Fp.add(_4a3, _27b2)))\n throw new Error('bad curve params: a or b');\n /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */\n function acoord(title, n, banZero = false) {\n if (!Fp.isValid(n) || (banZero && Fp.is0(n)))\n throw new Error(`bad point coordinate ${title}`);\n // Extension-field elements are objects. Keep point coordinates detached from caller-owned\n // objects so their mutation cannot invalidate cached on-curve / subgroup checks. Primitive\n // field elements (bigints in shipped prime fields) are already immutable values.\n return typeof n === 'object' && n !== null ? Fp.create(n) : n;\n }\n function aprjpoint(other) {\n if (!(other instanceof Point))\n throw new Error('Weierstrass Point expected');\n }\n function splitEndoScalarN(k) {\n if (!endo || !endo.basises)\n throw new Error('no endo');\n return _splitEndoScalar(k, endo.basises, Fn.ORDER);\n }\n /**\n * Appends a (point, scalar) pair to the inputs of a vartime wNAF walk\n * ({@link mulAddUnsafe}). With GLV endomorphism the scalar is split into two half-width\n * pairs against P and \u03C8(P) = (\u03B2\u22C5x, y), halving the walk's shared doubling chain;\n * split signs fold into the points.\n */\n function pushWnafPair(points, scalars, p, k) {\n if (!Fn.isValid(k))\n throw new RangeError('invalid scalar: out of range'); // 0 is valid\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(k);\n const psi = new Point(Fp.mul(p.X, endo.beta), p.Y, p.Z);\n points.push(k1neg ? p.negate() : p, k2neg ? psi.negate() : psi);\n scalars.push(k1, k2);\n }\n else {\n points.push(p);\n scalars.push(k);\n }\n }\n // Successful assertValidity() results are cached: Point instances are frozen at construction,\n // so on-curve + subgroup facts cannot change afterwards. Only success is cached \u2014 invalid\n // points re-throw on every call. This matters most for pairing curves, where subgroup checks\n // cost a scalar multiplication and the same instance is re-validated across layers\n // (signature fromBytes, pairingBatch) or across repeated verifies with a cached public key.\n const validityCache = new WeakSet();\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 {\n static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n static Fp = Fp;\n static Fn = Fn;\n X;\n Y;\n Z;\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n constructor(X, Y, Z) {\n this.X = acoord('x', X);\n // This is not just about ZERO / infinity: ambient curves can have real\n // finite points with y=0. Those points are 2-torsion, so they cannot lie\n // in the odd prime-order subgroups this point type is meant to represent.\n this.Y = acoord('y', Y, true);\n this.Z = acoord('z', Z);\n Object.freeze(this);\n }\n static CURVE() {\n return CURVE;\n }\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n static fromAffine(p) {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('invalid affine point');\n if (p instanceof Point)\n throw new Error('projective point not allowed');\n // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)\n if (Fp.is0(x) && Fp.is0(y))\n return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n static fromBytes(bytes) {\n const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));\n P.assertValidity();\n return P;\n }\n static fromHex(hex) {\n return Point.fromBytes(hexToBytes(hex));\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n /**\n * @param isLazy - true will defer table computation until the first multiplication\n */\n precompute(windowSize = 6, isLazy = true) {\n wnaf.setWindowSize(this, windowSize);\n if (!isLazy)\n this.multiply(_3n); // random number\n return this;\n }\n // TODO: return `this`\n /** A point on curve is valid if it conforms to equation. */\n assertValidity() {\n const p = this;\n if (p.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // Keep the accepted infinity encoding canonical: projective-equivalent (X, Y, 0) points\n // like (1, 1, 0) compare equal to ZERO, but only (0, 1, 0) should pass this guard.\n if (allowInfinityPoint && Fp.is0(p.X) && Fp.eql(p.Y, Fp.ONE) && Fp.is0(p.Z))\n return;\n throw new Error('bad point: ZERO');\n }\n if (validityCache.has(p))\n return;\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = p.toAffine();\n if (!Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('bad point: x or y not field elements');\n if (!isValidXY(x, y))\n throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree())\n throw new Error('bad point: not in prime-order subgroup');\n validityCache.add(p);\n }\n hasEvenY() {\n const { y } = this.toAffine();\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't support isOdd\");\n return !Fp.isOdd(y);\n }\n /** Compare one point to another. */\n equals(other) {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: 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 /** Flips point to one corresponding to (x, -y) in Affine coordinates. */\n negate() {\n return new Point(this.X, Fp.neg(this.Y), this.Z);\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 { X: X1, Y: Y1, Z: 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 = mulA(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 = mulA(t2);\n t3 = Fp.sub(t0, t2);\n t3 = mulA(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 // 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) {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\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 = mulA(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 = mulA(t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = mulA(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 subtract(other) {\n // Validate before calling `negate()` so wrong inputs fail with the point guard\n // instead of leaking a foreign `negate()` error.\n aprjpoint(other);\n return this.add(other.negate());\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n /**\n * Constant time multiplication.\n * Uses precomputed tables (signed fixed-window wNAF) when available.\n * Uses scalar blinding and avoids endomorphism splitting in the secret-scalar path.\n * @param scalar - by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar) {\n // Keep the subgroup-scalar contract strict instead of reducing 0 / n to ZERO.\n // In key/signature-style callers, those values usually mean broken hash/scalar plumbing,\n // and failing closed is safer than silently producing the identity point.\n if (!Fn.isValidNot0(scalar))\n throw new RangeError('invalid scalar: out of range'); // 0 is invalid\n const { p, f } = wnaf.mulSecret(this, scalar, cofactor, normalize);\n return normalize([p, f])[0];\n }\n /**\n * Non-constant-time multiplication. Uses width-4 wNAF with GLV endomorphism splitting\n * when available (two half-width scalars sharing one halved doubling chain).\n * It's faster, but should only be used when you don't care about\n * an exposed secret key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(scalar) {\n const p = this;\n const sc = scalar;\n // Public-scalar callers may need 0, but n and larger values stay rejected here too.\n // Reducing them mod n would turn bad caller input into an accidental identity point.\n if (!Fn.isValid(sc))\n throw new RangeError('invalid scalar: out of range'); // 0 is valid\n if (sc === _0n || p.is0())\n return Point.ZERO;\n if (sc === _1n)\n return p;\n if (wnaf.hasWindowSize(this))\n return wnaf.mulUnsafe(p, sc, normalize); // precomputes\n const points = [];\n const scalars = [];\n pushWnafPair(points, scalars, p, sc);\n return mulAddUnsafe(Point, points, scalars);\n }\n /**\n * Non-constant-time double-scalar multiplication `a\u22C5this + b\u22C5other` (Strauss\u2013Shamir).\n * Both walks share one doubling chain via {@link mulAddUnsafe}, and GLV endomorphism\n * (when available) halves the chain again by splitting each scalar into two half-width\n * parts. Used by ECDSA verification and public-key recovery for `R = u1\u22C5G + u2\u22C5P`.\n * Only for public scalars.\n */\n mulAddUnsafe(a, other, b) {\n aprjpoint(other);\n const points = [];\n const scalars = [];\n pushWnafPair(points, scalars, this, a);\n pushWnafPair(points, scalars, other, b);\n return mulAddUnsafe(Point, points, scalars);\n }\n /**\n * Converts Projective point to affine (x, y) coordinates.\n * (X, Y, Z) \u220B (x=X/Z, y=Y/Z).\n * @param invertedZ - Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch\n */\n toAffine(invertedZ) {\n const p = this;\n let iz = invertedZ;\n if (iz != null && !Fp.isValid(iz))\n throw new RangeError('\"invertedZ\" expected valid field element');\n const { X, Y, Z } = p;\n // Fast-path for normalized points\n if (Fp.eql(Z, Fp.ONE))\n return { x: X, y: Y };\n const is0 = p.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)\n iz = is0 ? Fp.ONE : Fp.inv(Z);\n const x = Fp.mul(X, iz);\n const y = Fp.mul(Y, iz);\n const zz = Fp.mul(Z, iz);\n if (is0)\n return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE))\n throw new Error('invZ was invalid');\n return { x, y };\n }\n /**\n * Checks whether Point is free of torsion elements (is in prime subgroup).\n * Always torsion-free for cofactor=1 curves.\n */\n isTorsionFree() {\n if (cofactor === _1n)\n return true;\n if (isTorsionFree)\n return isTorsionFree(Point, this);\n // unsafe() will use the uncached wNAF path internally, since CURVE_ORDER >= Fn.ORDER\n return wnaf.mulUnsafe(this, CURVE_ORDER).is0();\n }\n clearCofactor() {\n if (cofactor === _1n)\n return this; // Fast-path\n if (clearCofactor)\n return clearCofactor(Point, this);\n // Default fallback assumes the cofactor fits the usual subgroup-scalar\n // multiplyUnsafe() contract. Curves with larger / structured cofactors\n // should define a clearCofactor override anyway (e.g. psi/Frobenius maps).\n return this.multiplyUnsafe(cofactor);\n }\n isSmallOrder() {\n if (cofactor === _1n)\n return this.is0(); // Fast-path\n return this.clearCofactor().is0();\n }\n toBytes(isCompressed = true) {\n abool(isCompressed, 'isCompressed');\n // assertValidity() covers on-curve and subgroup membership. The encoder below repeats the\n // infinity check rather than relying on this call, so it stays correct for any caller.\n this.assertValidity();\n return encodePoint(Point, this, isCompressed);\n }\n toHex(isCompressed = true) {\n return bytesToHex(this.toBytes(isCompressed));\n }\n toString() {\n return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n }\n }\n const normalize = (points) => normalizeZ(Point, points);\n const wnaf = new ScalarMultiplier(Point, randomBytes);\n // Enable W=6 wNAF precomputes. Slows down first publicKey computation.\n // Disable for tiny toy curves, with scalar fields < 6 bits.\n if (wnaf.bits >= 6)\n Point.BASE.precompute(6);\n Object.freeze(Point.prototype);\n Object.freeze(Point);\n return Point;\n}\n// Points start with byte 0x02 when y is even; otherwise 0x03\nfunction pprefix(hasEvenY) {\n return Uint8Array.of(hasEvenY ? 0x02 : 0x03);\n}\nfunction getWLengths(Fp, Fn) {\n return {\n secretKey: Fn.BYTES,\n publicKey: 1 + Fp.BYTES,\n publicKeyUncompressed: 1 + 2 * Fp.BYTES,\n publicKeyHasPrefix: true,\n // Raw compact `(r || s)` signature width; DER and recovered signatures use\n // different lengths outside this helper.\n signature: 2 * Fn.BYTES,\n };\n}\n/**\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n * This helper ensures no signature functionality is present. Less code, smaller bundle size.\n * @param Point - Weierstrass point constructor.\n * @param ecdhOpts - Optional randomness helpers:\n * - `randomBytes` (optional): Optional RNG override.\n * @returns ECDH helper namespace.\n * @example\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n *\n * ```ts\n * import { ecdh } from '@noble/curves/abstract/weierstrass.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const dh = ecdh(p256.Point);\n * const alice = dh.keygen();\n * const shared = dh.getSharedSecret(alice.secretKey, alice.publicKey);\n * ```\n */\nexport function ecdh(Point, ecdhOpts = {}) {\n validatePointCons(Point);\n const { Fn } = Point;\n const randomBytes_ = ecdhOpts.randomBytes === undefined ? wcRandomBytes : ecdhOpts.randomBytes;\n // Keep the advertised seed length aligned with mapHashToField(), which keeps a hard 16-byte\n // minimum even on toy curves.\n const lengths = Object.assign(getWLengths(Point.Fp, Fn), {\n seed: Math.max(getMinHashLength(Fn.ORDER), 16),\n });\n function isValidSecretKey(secretKey) {\n try {\n const num = Fn.fromBytes(secretKey);\n return Fn.isValidNot0(num);\n }\n catch (error) {\n return false;\n }\n }\n function isValidPublicKey(publicKey, isCompressed) {\n const { publicKey: comp, publicKeyUncompressed } = lengths;\n try {\n const l = publicKey.length;\n if (isCompressed === true && l !== comp)\n return false;\n if (isCompressed === false && l !== publicKeyUncompressed)\n return false;\n // SEC 1 \u00A73.2.2: the identity is never a valid public key, even on curves whose codec\n // can decode it.\n return !Point.fromBytes(publicKey).is0();\n }\n catch (error) {\n return false;\n }\n }\n /**\n * Produces cryptographically secure secret key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n function randomSecretKey(seed) {\n seed = seed === undefined ? randomBytes_(lengths.seed) : seed;\n return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);\n }\n /**\n * Computes public key for a secret key. Checks for validity of the secret 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(secretKey, isCompressed = true) {\n return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);\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) {\n const { secretKey, publicKey, publicKeyUncompressed } = lengths;\n const allowedLengths = Fn._lengths;\n if (!isBytes(item))\n return undefined;\n const l = abytes(item, undefined, 'key').length;\n const isPub = l === publicKey || l === publicKeyUncompressed;\n const isSec = l === secretKey || !!allowedLengths?.includes(l);\n // P-521 accepts both 65- and 66-byte secret keys, so overlapping lengths stay ambiguous.\n if (isPub && isSec)\n return undefined;\n return isPub;\n }\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes encoded shared point from secret key A and public key B.\n * Checks: 1) secret key validity 2) shared key is on-curve.\n * Does NOT hash the result or expose the SEC 1 x-coordinate-only `z`.\n * Returns the encoded shared point on purpose: callers that need `x_P`\n * can derive it from the encoded point, but `x_P` alone cannot recover the\n * point/parity back.\n * This helper only exposes the fully validated public-key path, not cofactor DH.\n * @param isCompressed - whether to return compact (default), or full key\n * @returns shared point encoding\n */\n function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {\n if (isProbPub(secretKeyA) === true)\n throw new Error('first arg must be private key');\n if (isProbPub(publicKeyB) === false)\n throw new Error('second arg must be public key');\n const s = Fn.fromBytes(secretKeyA);\n const b = Point.fromBytes(publicKeyB); // checks for being on-curve\n if (b.is0())\n throw new Error('invalid public key: point at infinity');\n return b.multiply(s).toBytes(isCompressed);\n }\n const utils = {\n isValidSecretKey,\n isValidPublicKey,\n randomSecretKey,\n };\n const keygen = createKeygen(randomSecretKey, getPublicKey);\n Object.freeze(utils);\n Object.freeze(lengths);\n return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });\n}\n/**\n * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.\n *\n * @param Point - created using {@link weierstrass} function\n * @param hash - used for 1) message prehash-ing 2) k generation in `sign`, using hmac_drbg(hash)\n * @param ecdsaOpts - rarely needed, see {@link ECDSAOpts}:\n * - `lowS`: Default low-S policy.\n * - `hmac`: HMAC implementation used by RFC6979 DRBG.\n * - `randomBytes`: Optional RNG override.\n * - `bits2int`: Optional hash-to-int conversion override.\n * - `bits2int_modN`: Optional hash-to-int-mod-n conversion override.\n *\n * @returns ECDSA helper namespace.\n * @example\n * Create an ECDSA signer/verifier bundle for one curve implementation.\n *\n * ```ts\n * import { ecdsa } from '@noble/curves/abstract/weierstrass.js';\n * import { p256 } from '@noble/curves/nist.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const p256ecdsa = ecdsa(p256.Point, sha256);\n * const { secretKey, publicKey } = p256ecdsa.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = p256ecdsa.sign(msg, secretKey);\n * const isValid = p256ecdsa.verify(sig, msg, publicKey);\n * ```\n */\nexport function ecdsa(Point, hash, ecdsaOpts = {}) {\n validatePointCons(Point);\n // Custom hash / bits2int hooks are treated as pure functions over validated caller-owned bytes.\n const hash_ = hash;\n ahash(hash_);\n validateObject(ecdsaOpts, {}, {\n hmac: 'function',\n lowS: 'boolean',\n randomBytes: 'function',\n bits2int: 'function',\n bits2int_modN: 'function',\n });\n const opts = Object.assign({}, ecdsaOpts);\n const randomBytes = opts.randomBytes === undefined ? wcRandomBytes : opts.randomBytes;\n const hmac = opts.hmac === undefined\n ? (key, msg) => nobleHmac(hash_, key, msg)\n : opts.hmac;\n const { Fp, Fn } = Point;\n const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;\n // Nonce-inversion blinding in k2sig draws `getMinHashLength(n)` bytes per sign. Probe the RNG\n // once (see {@link probeRandomBytes}, shared with ScalarMultiplier): in environments without\n // working randomness, signing downgrades to Fermat inversion (invertCt) instead of throwing on\n // every sign(). The shape of returned bytes is still validated (by mapHashToField) on every\n // blinded call, where breakage fails closed.\n const blindLength = getMinHashLength(CURVE_ORDER);\n const csprng = probeRandomBytes(randomBytes, blindLength);\n const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, opts);\n const defaultSigOpts = {\n prehash: true,\n lowS: typeof opts.lowS === 'boolean' ? opts.lowS : true,\n format: 'compact',\n extraEntropy: false,\n };\n // SEC 1 4.1.6 public-key recovery tries x = r + jn for j = 0..h. Our recovered-signature\n // format only stores one overflow bit, so it can only distinguish q.x = r from q.x = r + n.\n // A third lift would have the form q.x = r + 2n. Since valid ECDSA r is in 1..n-1, the\n // smallest such lift is 1 + 2n, not 2n.\n const hasLargeRecoveryLifts = CURVE_ORDER * _2n + _1n < Fp.ORDER;\n function isBiggerThanHalfOrder(number) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function validateRS(title, num) {\n if (!Fn.isValidNot0(num))\n throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);\n return num;\n }\n function assertFieldSignIsSupported() {\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't support isOdd\");\n }\n // Recovery id of an affine point (x, y) whose x reduces to signature `r` mod n:\n // bit 0 = y parity, bit 1 = x overflowed the group order (x = r + n).\n function getRecoveryBit(x, y, r) {\n assertFieldSignIsSupported();\n return (x === r ? 0 : 2) | Number(Fp.isOdd(y));\n }\n function assertRecoverableCurve() {\n // ECDSA recovery only supports curves where the current recovery id can distinguish\n // q.x = r and q.x = r + n; larger lifts may need additional `r + n*i` branches.\n // SEC 1 4.1.6 recovers candidates via x = r + jn, but this format only encodes j = 0 or 1.\n // The next possible candidate is q.x = r + 2n, and its smallest valid value is 1 + 2n.\n // To easily get i, we either need to:\n // a. increase amount of valid recid values (4, 5...); OR\n // b. prohibit recovered signatures for those curves.\n if (hasLargeRecoveryLifts)\n throw new Error('\"recovered\" sig type is not supported for cofactor >2 curves');\n }\n function validateSigLength(bytes, format) {\n validateSigFormat(format);\n const size = lengths.signature;\n const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;\n return abytes(bytes, sizer);\n }\n /**\n * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.\n */\n class Signature {\n r;\n s;\n recovery;\n constructor(r, s, recovery) {\n this.r = validateRS('r', r); // r in [1..N-1];\n this.s = validateRS('s', s); // s in [1..N-1];\n if (recovery != null) {\n assertRecoverableCurve();\n if (![0, 1, 2, 3].includes(recovery))\n throw new Error('invalid recovery id');\n this.recovery = recovery;\n }\n Object.freeze(this);\n }\n static fromBytes(bytes, format = defaultSigOpts.format) {\n validateSigLength(bytes, format);\n let recid;\n if (format === 'der') {\n // Valid scalar INTEGERs use at most Fn.BYTES plus one DER sign-padding byte. Keep the\n // total bound conservative so malformed inputs are rejected before parsing any INTEGER.\n if (bytes.length > 2 * Fn.BYTES + 16)\n throw new DER.Err('invalid signature: DER signature too long');\n const { r, s } = DER.toSig(abytes(bytes), Fn.BYTES + 1);\n return new Signature(r, s);\n }\n if (format === 'recovered') {\n recid = bytes[0];\n format = 'compact';\n bytes = bytes.subarray(1);\n }\n const L = lengths.signature / 2;\n const r = bytes.subarray(0, L);\n const s = bytes.subarray(L, L * 2);\n return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);\n }\n static fromHex(hex, format) {\n return this.fromBytes(hexToBytes(hex), format);\n }\n assertRecovery() {\n const { recovery } = this;\n if (recovery == null)\n throw new Error('invalid recovery id: must be present');\n return recovery;\n }\n addRecoveryBit(recovery) {\n return new Signature(this.r, this.s, recovery);\n }\n // Unlike the top-level helper below, this method expects a digest that has\n // already been hashed to the curve's message representative.\n recoverPublicKey(messageHash) {\n const { r, s } = this;\n const recovery = this.assertRecovery();\n const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r;\n if (!Fp.isValid(radj))\n throw new Error('invalid recovery id: sig.r+curve.n != R.x');\n const x = Fp.toBytes(radj);\n const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));\n const ir = Fn.inv(radj); // r^-1\n const h = bits2int_modN(abytes(messageHash, undefined, 'msgHash')); // Truncate hash\n const u1 = Fn.create(-h * ir); // -hr^-1\n const u2 = Fn.create(s * ir); // sr^-1\n // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.\n const Q = Point.BASE.mulAddUnsafe(u1, R, u2);\n if (Q.is0())\n throw new Error('invalid recovery: point at infinify');\n Q.assertValidity();\n return Q;\n }\n // Signatures should be low-s, to prevent malleability.\n hasHighS() {\n return isBiggerThanHalfOrder(this.s);\n }\n toBytes(format = defaultSigOpts.format) {\n validateSigFormat(format);\n if (format === 'der')\n return hexToBytes(DER.hexFromSig(this));\n const { r, s } = this;\n const rb = Fn.toBytes(r);\n const sb = Fn.toBytes(s);\n if (format === 'recovered') {\n assertRecoverableCurve();\n return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);\n }\n return concatBytes(rb, sb);\n }\n toHex(format) {\n return bytesToHex(this.toBytes(format));\n }\n }\n Object.freeze(Signature.prototype);\n Object.freeze(Signature);\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 = opts.bits2int === undefined\n ? function bits2int_def(bytes) {\n // Our custom check \"just in case\", for protection against DoS\n if (bytes.length > 8192)\n throw new Error('input is too large');\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 = bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n }\n : opts.bits2int;\n const bits2int_modN = opts.bits2int_modN === undefined\n ? function bits2int_modN_def(bytes) {\n return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here\n }\n : opts.bits2int_modN;\n const ORDER_MASK = bitMask(fnBits);\n // Pads output with zero as per spec.\n /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */\n function int2octets(num) {\n aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);\n return Fn.toBytes(num);\n }\n function validateMsgAndHash(message, prehash) {\n abytes(message, undefined, 'message');\n return (prehash ? abytes(hash_(message), undefined, 'prehashed message') : message);\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 *\n * Warning: we cannot assume here that message has same amount of bytes as curve order,\n * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.\n */\n function prepSig(message, secretKey, opts) {\n const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with fnBits % 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(message);\n const d = Fn.fromBytes(secretKey); // validate secret key, convert to bigint\n if (!Fn.isValidNot0(d))\n throw new Error('invalid private key');\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (extraEntropy != null && extraEntropy !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n // gen random bytes OR pass as-is\n const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;\n seedArgs.push(abytes(e, undefined, 'extraEntropy')); // check for being bytes\n }\n const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // 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 // To transform k => Signature:\n // q = k\u22C5G\n // r = q.x mod n\n // s = k^-1(m + rd) mod n\n // The nonce inversion is blinded: with random b \u2208 [1,n\u22121], s = (bk)^-1(bm + bdr) per\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. Fn.inv()'s extended-Euclidean\n // loop count depends on its input (cf. Minerva), but here it only ever sees b\u00B7k \u2014 uniformly\n // random, independent of k \u2014 so its timing reveals nothing about the nonce; b also masks d in\n // the products. Without a CSPRNG (probed in ecdsa()) we fall back to Fermat inversion\n // (invertCt), whose control flow is data-independent, at ~4x the inversion cost.\n function k2sig(kBytes) {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n // Important: all mod() calls here must be done over N\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!Fn.isValidNot0(k))\n return; // Valid scalars (including k) must be in 1..N-1\n const q = Point.BASE.multiply(k).toAffine(); // q = k\u22C5G\n const r = Fn.create(q.x); // r = q.x mod n\n if (r === _0n)\n return;\n let s;\n if (csprng !== undefined) {\n // mapHashToField maps 1.5x-order-length uniform bytes into [1, n-1], negligible bias.\n const b = bytesToNumberBE(mapHashToField(csprng(blindLength), CURVE_ORDER));\n const ibk = Fn.inv(Fn.mul(b, k)); // (bk)^-1: inversion input is decorrelated from k\n const bm = Fn.mul(b, m);\n const bd = Fn.mul(b, d);\n s = Fn.create(ibk * Fn.create(bm + bd * r)); // s = (bk)^-1(bm + bdr) = k^-1(m + rd) mod n\n }\n else {\n const ik = invertCt(k, CURVE_ORDER); // k^-1 mod n with data-independent control flow\n s = Fn.create(ik * Fn.create(m + r * d)); // s = k^-1(m + rd) mod n\n }\n if (s === _0n)\n return;\n let recovery = getRecoveryBit(q.x, q.y, r); // recovery bit (2 or 3 when q.x>n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = Fn.neg(s); // if lowS was passed, ensure s is always in the bottom half of N\n recovery ^= 1;\n }\n return new Signature(r, normS, hasLargeRecoveryLifts ? undefined : recovery);\n }\n return { seed, k2sig };\n }\n /**\n * Signs a message or message hash with a secret key.\n * With the default `prehash: true`, raw message bytes are hashed internally;\n * only `{ prehash: false }` expects a caller-supplied digest.\n *\n * ```\n * sign(m, d) where\n * k = rfc6979_hmac_drbg(m, d)\n * (x, y) = G \u00D7 k\n * r = x mod n\n * s = (m + dr) / k mod n\n * ```\n */\n function sign(message, secretKey, opts = {}) {\n const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.\n const drbg = createHmacDrbg(hash_.outputLen, Fn.BYTES, hmac);\n const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G\n return sig.toBytes(opts.format);\n }\n /**\n * Verifies a signature against message and public key.\n * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.\n * 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(signature, message, publicKey, opts = {}) {\n const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);\n publicKey = abytes(publicKey, undefined, 'publicKey');\n message = validateMsgAndHash(message, prehash);\n if (!isBytes(signature)) {\n const end = signature instanceof Signature ? ', use sig.toBytes()' : '';\n throw new Error('verify expects Uint8Array signature' + end);\n }\n validateSigLength(signature, format); // execute this twice because we want loud error\n try {\n const sig = Signature.fromBytes(signature, format);\n const P = Point.fromBytes(publicKey);\n // SEC 1 verification keys must not be the identity, even when the generic point decoder\n // permits infinity for another protocol (for example, a pairing curve).\n if (P.is0())\n return false;\n if (lowS && sig.hasHighS())\n return false;\n const { r, s } = sig;\n const h = bits2int_modN(message); // mod n, not mod p\n const is = Fn.inv(s); // s^-1 mod n\n const u1 = Fn.create(h * is); // u1 = hs^-1 mod n\n const u2 = Fn.create(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.mulAddUnsafe(u1, P, u2); // u1\u22C5G + u2\u22C5P, joint Strauss\u2013Shamir\n if (R.is0())\n return false;\n const q = R.toAffine();\n const v = Fn.create(q.x); // v = R.x mod n\n if (v !== r)\n return false;\n // R is the exact point `recoverPublicKey(r, recid)` reconstructs (sR = hG + rP),\n // so binding the signature to its recovery id only needs R's parity/overflow bits.\n if (format === 'recovered' && sig.recovery !== getRecoveryBit(q.x, q.y, r))\n return false;\n return true;\n }\n catch (e) {\n return false;\n }\n }\n function recoverPublicKey(signature, message, opts = {}) {\n // Top-level recovery mirrors `sign()` / `verify()`: it hashes raw message\n // bytes first unless the caller passes `{ prehash: false }`.\n const { prehash } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash);\n return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();\n }\n // utils.isValidPublicKey() already rejects the identity, so ECDSA needs no shadow copy.\n return Object.freeze({\n keygen,\n getPublicKey,\n getSharedSecret,\n utils,\n lengths,\n Point,\n sign,\n verify,\n recoverPublicKey,\n Signature,\n hash: hash_,\n });\n}\n", "/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { setU64FromNum } from \"./_u64.js\";\nimport { abytes, aexists, aoutput, createView } from \"./utils.js\";\n/**\n * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.\n * Returns bits from `b` when `a` is set, otherwise from `c`.\n * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never\n * set the same bit.\n * @param a - selector word\n * @param b - word chosen when selector bit is set\n * @param c - word chosen when selector bit is clear\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit choice primitive.\n * ```ts\n * Chi(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/**\n * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.\n * Returns bits shared by at least two inputs.\n * @param a - first input word\n * @param b - second input word\n * @param c - third input word\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit majority primitive.\n * ```ts\n * Maj(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Maj(a, b, c) {\n return (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 * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit\n * strings with partial-byte tails.\n * @param blockLen - internal block size in bytes\n * @param outputLen - digest size in bytes\n * @param padOffset - trailing length field size in bytes\n * @param isLE - whether length and state words are encoded in little-endian\n * @example\n * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.\n * ```ts\n * import { _SHA1 } from '@noble/hashes/legacy.js';\n * const hash = new _SHA1();\n * hash.update(new Uint8Array([97, 98, 99]));\n * hash.digest();\n * ```\n */\nexport class HashMD {\n blockLen;\n outputLen;\n canXOF = false;\n padOffset;\n isLE;\n // For partial updates less than block size\n buffer;\n view;\n finished = false;\n length = 0;\n pos = 0;\n destroyed = false;\n constructor(blockLen, outputLen, padOffset, isLE) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n let processed = false;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path only when there is no buffered partial block: `take === blockLen` implies\n // `this.pos === 0`, so we can process full blocks directly from the input view.\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n processed = true;\n continue;\n }\n // When the whole input is buffered in one go (common for short messages), passing `data`\n // directly avoids allocating a subarray view.\n buffer.set(pos === 0 && take === len ? data : 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 processed = true;\n }\n }\n this.length += data.length;\n // Shared schedule buffers only pick up input-derived words inside process(); if everything\n // was buffered without processing, there is nothing to zero.\n if (processed)\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(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, then zero-pad the rest of the block\n buffer[pos++] = 0b10000000;\n buffer.fill(0, pos);\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 buffer.fill(0);\n }\n // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from\n // the padding fill above, and JS will overflow before user input can make that half non-zero.\n // So we only need to write the low 64 bits here (`length * 8` only scales the exponent of an\n // integer below 2**53, so the split inside the helper stays exact).\n setU64FromNum(view, blockLen - 8, this.length * 8, isLE);\n this.process(view, 0);\n // The final block above is processed outside update(), so the shared message-schedule\n // buffers (e.g. SHA256_W) would otherwise retain input-derived words after digest().\n this.roundClean();\n // digest() passes our own `buffer` as `out`; reuse its cached view instead of allocating one.\n const oview = out === buffer ? view : createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n const outLen = len / 4;\n const state = this.get();\n // Subclass-misconfiguration invariant: outputLen must be 32-bit aligned and fit the state.\n if (len % 4 || outLen > state.length)\n throw new Error('invalid outputLen');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return\n // fresh bytes to the caller.\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneIntoMeta(to) {\n const { buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and\n // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.\n if (pos)\n to.buffer.set(buffer); // Avoid a hot modulo guard.\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state from RFC 6234 \u00A76.1: the first 32 bits of the fractional parts of the\n * square roots of the first eight prime numbers. Exported as a shared table; callers must treat\n * it as read-only because constructors copy words from it by index. */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state `H(0)` from RFC 6234 \u00A76.1. Exported as a shared table; callers must\n * treat it as read-only because constructors copy words from it by index. */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state from RFC 6234 \u00A76.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth\n * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only\n * because constructors copy halves from it by index. */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state from RFC 6234 \u00A76.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first\n * eight prime numbers. Exported as a shared table; callers must treat it as read-only because\n * constructors copy halves from it by index. */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n", "/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, oidNist, rotr } from \"./utils.js\";\n/**\n * SHA-224 / SHA-256 round constants from RFC 6234 \u00A75.1: the first 32 bits\n * of the cube roots of the first 64 primes (2..311).\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\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/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 \u00A76.2 step 1. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 \u00A76.2. */\nclass SHA2_32B extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // Numeric initializers matter: starting the fields as `undefined` changes\n // V8's field representation and makes sha256 3x slower (measured).\n A = 0;\n B = 0;\n C = 0;\n D = 0;\n E = 0;\n F = 0;\n G = 0;\n H = 0;\n constructor(outputLen, IV) {\n super(64, outputLen, 8, false);\n this.A = IV[0] | 0;\n this.B = IV[1] | 0;\n this.C = IV[2] | 0;\n this.D = IV[3] | 0;\n this.E = IV[4] | 0;\n this.F = IV[5] | 0;\n this.G = IV[6] | 0;\n this.H = IV[7] | 0;\n }\n get() {\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 set(A, B, C, D, E, F, G, H) {\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 _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\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)\n 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 roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/** Internal SHA-256 hash class grounded in RFC 6234 \u00A76.2. */\nexport class _SHA256 extends SHA2_32B {\n constructor() {\n super(32, SHA256_IV);\n }\n}\n/** Internal SHA-224 hash class grounded in RFC 6234 \u00A76.2 and \u00A78.5. */\nexport class _SHA224 extends SHA2_32B {\n constructor() {\n super(28, SHA224_IV);\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// SHA-384 / SHA-512 round constants from RFC 6234 \u00A75.2:\n// 80 full 64-bit words split into high/low halves.\n// prettier-ignore\nconst K512 = /* @__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))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable high-half schedule buffer for the RFC 6234 \u00A76.4 64-bit `W_t` words.\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\n// Reusable low-half schedule buffer for the RFC 6234 \u00A76.4 64-bit `W_t` words.\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 \u00A76.4. */\nclass SHA2_64B extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n // Numeric initializers matter: starting the fields as `undefined` changes\n // V8's field representation and slows hashing down (measured on sha256).\n Ah = 0;\n Al = 0;\n Bh = 0;\n Bl = 0;\n Ch = 0;\n Cl = 0;\n Dh = 0;\n Dl = 0;\n Eh = 0;\n El = 0;\n Fh = 0;\n Fl = 0;\n Gh = 0;\n Gl = 0;\n Hh = 0;\n Hl = 0;\n constructor(outputLen, IV) {\n super(128, outputLen, 16, false);\n this.Ah = IV[0] | 0;\n this.Al = IV[1] | 0;\n this.Bh = IV[2] | 0;\n this.Bl = IV[3] | 0;\n this.Ch = IV[4] | 0;\n this.Cl = IV[5] | 0;\n this.Dh = IV[6] | 0;\n this.Dl = IV[7] | 0;\n this.Eh = IV[8] | 0;\n this.El = IV[9] | 0;\n this.Fh = IV[10] | 0;\n this.Fl = IV[11] | 0;\n this.Gh = IV[12] | 0;\n this.Gl = IV[13] | 0;\n this.Hh = IV[14] | 0;\n this.Hl = IV[15] | 0;\n }\n // prettier-ignore\n get() {\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 set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\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 _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\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 // SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_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 roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n/** Internal SHA-512 hash class grounded in RFC 6234 \u00A76.3 and \u00A76.4. */\nexport class _SHA512 extends SHA2_64B {\n constructor() {\n super(64, SHA512_IV);\n }\n}\n/** Internal SHA-384 hash class grounded in RFC 6234 \u00A76.3 and \u00A76.4. */\nexport class _SHA384 extends SHA2_64B {\n constructor() {\n super(48, SHA384_IV);\n }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See the repo-side derivation recipe in `test/misc/sha2-gen-iv.js`.\n * These IV literals are checked against that script rather than a dedicated\n * local RFC section.\n */\n/** SHA-512/224 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA-512/256 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared\n * RFC 6234 \u00A76.4 compression engine. */\nexport class _SHA512_224 extends SHA2_64B {\n constructor() {\n super(28, T224_IV);\n }\n}\n/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared\n * RFC 6234 \u00A76.4 compression engine. */\nexport class _SHA512_256 extends SHA2_64B {\n constructor() {\n super(32, T256_IV);\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-256.\n * ```ts\n * sha256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(), \n/* @__PURE__ */ oidNist(0x01));\n/**\n * SHA2-224 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-224.\n * ```ts\n * sha224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new _SHA224(), \n/* @__PURE__ */ oidNist(0x04));\n/**\n * SHA2-512 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512.\n * ```ts\n * sha512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new _SHA512(), \n/* @__PURE__ */ oidNist(0x03));\n/**\n * SHA2-384 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-384.\n * ```ts\n * sha384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new _SHA384(), \n/* @__PURE__ */ oidNist(0x02));\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/256.\n * ```ts\n * sha512_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new _SHA512_256(), \n/* @__PURE__ */ oidNist(0x06));\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/224.\n * ```ts\n * sha512_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new _SHA512_224(), \n/* @__PURE__ */ oidNist(0x05));\n", "/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, concatBytes, hexToBytes } from '@noble/hashes/utils.js';\nimport {} from \"./abstract/curve.js\";\nimport { eddsa, edwards, PrimeEdwardsPoint, } from \"./abstract/edwards.js\";\nimport { createFROST } from \"./abstract/frost.js\";\nimport { _DST_scalar, createHasher, expand_message_xmd, } from \"./abstract/hash-to-curve.js\";\nimport { FpInvertBatch, FpSqrtEven, isNegativeLE, mod, pow2, } from \"./abstract/modular.js\";\nimport { montgomery } from \"./abstract/montgomery.js\";\nimport { createOPRF } from \"./abstract/oprf.js\";\nimport { asciiToBytes, bytesToNumberLE, equalBytes } from \"./utils.js\";\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _5n = /* @__PURE__ */ BigInt(5), _8n = /* @__PURE__ */ BigInt(8);\n// P = 2n**255n - 19n\nconst ed25519_CURVE_p = /* @__PURE__ */ BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed');\n// N = 2n**252n + 27742317777372353535851937790883648493n\n// a = Fp.create(BigInt(-1))\n// d = -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666))\nconst ed25519_CURVE = /* @__PURE__ */ (() => ({\n p: ed25519_CURVE_p,\n n: BigInt('0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed'),\n h: _8n,\n a: BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec'),\n d: BigInt('0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3'),\n Gx: BigInt('0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a'),\n Gy: BigInt('0x6666666666666666666666666666666666666666666666666666666666666658'),\n}))();\nfunction ed25519_pow_2_252_3(x) {\n // prettier-ignore\n const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n const P = ed25519_CURVE_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 // ^ This is x^((p-5)/8); multiply by x once more to get x^((p+3)/8).\n return { pow_p_5_8, b2 };\n}\n// Mutates and returns the provided 32-byte buffer in place.\nfunction adjustScalarBytes(bytes) {\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// \u221A(-1) aka \u221A(a) aka 2^((p-1)/4)\n// Fp.sqrt(Fp.neg(1))\nconst ED25519_SQRT_M1 = /* @__PURE__ */ BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');\n// sqrt(u/v). Returns `{ isValid, value }`; on non-squares `value` is still a\n// dummy root-shaped field element so callers can stay constant-time.\nfunction uvRatio(u, v) {\n const P = ed25519_CURVE_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)\n x = root1;\n if (useRoot2 || noRoot)\n x = root2; // We return root2 anyway, for const-time\n if (isNegativeLE(x, P))\n x = mod(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\nconst ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE, { uvRatio });\n// Public field alias stays stricter than the RFC 8032 Appendix A sample code:\n// `Fp.inv(0)` throws instead of returning `0`.\nconst Fp = /* @__PURE__ */ (() => ed25519_Point.Fp)();\nfunction toMontgomery(point) {\n // Birational map from Ed25519 to Curve25519 / X25519:\n // (u, v) = ((1 + y) / (1 - y), sqrt(-486664) * u / x)\n // (x, y) = (sqrt(-486664) * u / v, (u - 1) / (u + 1))\n const { y } = point;\n return Fp.toBytes(Fp.div(_1n + y, _1n - y));\n}\nfunction toMontgomerySecret(secretKey) {\n const size = ed25519_Point.Fp.BYTES;\n abytes(secretKey, size);\n return adjustScalarBytes(sha512(secretKey.subarray(0, size))).subarray(0, size);\n}\nconst Fn = /* @__PURE__ */ (() => ed25519_Point.Fn)();\n// RFC 8032 `dom2` helper for ctx/ph variants only. Plain Ed25519 keeps the\n// empty-domain path in `ed()` and would be wrong if routed through this helper.\nfunction ed25519_domain(data, ctx, phflag) {\n if (ctx.length > 255)\n throw new Error('Context is too big');\n return concatBytes(asciiToBytes('SigEd25519 no Ed25519 collisions'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);\n}\nfunction ed(opts) {\n // Ed25519 keeps ZIP-215 default verification semantics for consensus compatibility.\n return eddsa(ed25519_Point, sha512, Object.assign({ adjustScalarBytes, toMontgomery, toMontgomerySecret, zip215: true }, opts));\n}\n/**\n * ed25519 curve with EdDSA signatures.\n * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided\n * 32-byte seed buffer instead of copying it.\n * @example\n * Generate one Ed25519 keypair, sign a message, and verify it.\n *\n * ```js\n * import { ed25519 } from '@noble/curves/ed25519.js';\n * const { secretKey, publicKey } = ed25519.keygen();\n * // const publicKey = ed25519.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ed25519.sign(msg, secretKey);\n * const isValid = ed25519.verify(sig, msg, publicKey); // ZIP215\n * // RFC8032 / FIPS 186-5\n * const isValid2 = ed25519.verify(sig, msg, publicKey, { zip215: false });\n * ```\n */\nexport const ed25519 = /* @__PURE__ */ ed({});\n/**\n * Context version of ed25519 (ctx for domain separation). See {@link ed25519}\n * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided\n * 32-byte seed buffer instead of copying it.\n * @example\n * Sign and verify with Ed25519ctx under one explicit context.\n *\n * ```ts\n * const context = new TextEncoder().encode('docs');\n * const { secretKey, publicKey } = ed25519ctx.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ed25519ctx.sign(msg, secretKey, { context });\n * const isValid = ed25519ctx.verify(sig, msg, publicKey, { context });\n * ```\n */\nexport const ed25519ctx = /* @__PURE__ */ ed({ domain: ed25519_domain });\n/**\n * Prehashed version of ed25519. See {@link ed25519}\n * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided\n * 32-byte seed buffer instead of copying it.\n * @example\n * Use the prehashed Ed25519 variant for one message.\n *\n * ```ts\n * const { secretKey, publicKey } = ed25519ph.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ed25519ph.sign(msg, secretKey);\n * const isValid = ed25519ph.verify(sig, msg, publicKey);\n * ```\n */\nexport const ed25519ph = /* @__PURE__ */ ed({ domain: ed25519_domain, prehash: sha512 });\n/**\n * FROST threshold signatures over ed25519. RFC 9591.\n * @example\n * Create one trusted-dealer package for 2-of-3 ed25519 signing.\n *\n * ```ts\n * const alice = ed25519_FROST.Identifier.derive('alice@example.com');\n * const bob = ed25519_FROST.Identifier.derive('bob@example.com');\n * const carol = ed25519_FROST.Identifier.derive('carol@example.com');\n * const deal = ed25519_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const ed25519_FROST = /* @__PURE__ */ (() => createFROST({\n name: 'FROST-ED25519-SHA512-v1',\n Point: ed25519_Point,\n validatePoint: (p) => {\n p.assertValidity();\n if (!p.isTorsionFree())\n throw new Error('bad point: not torsion-free');\n },\n hash: sha512,\n // RFC 9591 keeps H2 undecorated here for RFC 8032 compatibility. In createFROST(),\n // `H2: ''` becomes an empty DST prefix; the built-in hashToScalar fallback treats\n // that the same as omitted DST, even though custom hooks can still observe the empty bag.\n H2: '',\n}))();\n/**\n * ECDH using curve25519 aka x25519.\n * `getSharedSecret()` rejects low-order peer inputs by default, and seeded\n * `keygen(seed)` reuses the provided 32-byte seed buffer instead of copying it.\n * @example\n * Derive one shared secret between two X25519 peers.\n *\n * ```js\n * import { x25519 } from '@noble/curves/ed25519.js';\n * const alice = x25519.keygen();\n * const bob = x25519.keygen();\n * const alicePublic = x25519.getPublicKey(alice.secretKey);\n * const shared = x25519.getSharedSecret(alice.secretKey, bob.publicKey);\n * ```\n */\nexport const x25519 = /* @__PURE__ */ (() => {\n const P = ed25519_CURVE_p;\n const powPminus2 = (x) => {\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, _3n, P) * b2, P);\n };\n return montgomery({\n P,\n type: 'x25519',\n powPminus2,\n adjustScalarBytes,\n // ~3x faster fixed-base: [k]B on the birationally-equivalent Edwards curve using cached\n // base tables, mapped back via u = (1+y)/(1-y) = (Z+Y)/(Z-Y) with one Fermat inversion.\n // Same construction as libsodium's crypto_scalarmult_curve25519_base.\n scalarMultBase: (k) => {\n // Clamped k (\u22482^254) exceeds n, but B has prime order n, so [k]B == [k mod n]B.\n const kn = mod(k, ed25519_Point.Fn.ORDER);\n // k \u2261 0 (mod n): [k]B is the point at infinity, whose u is 0 in the x-only ladder;\n // returning 0 makes montgomery() reject it exactly like the ladder path.\n if (kn === _0n)\n return _0n;\n const p = ed25519_Point.BASE.multiply(kn);\n // Z-Y == 0 only at the identity, which kn != 0 excludes.\n return mod((p.Z + p.Y) * powPminus2(mod(p.Z - p.Y, P)), P);\n },\n });\n})();\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// RFC 9380 Appendix G.2.2 / Err4730 requires `sgn0(c1) = 0` for the Edwards\n// map constant below, so use the even root explicitly.\n// 1. c1 = (q + 3) / 8 # Integer arithmetic\nconst ELL2_C1 = /* @__PURE__ */ (() => (ed25519_CURVE_p + _3n) / _8n)();\nconst ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1\nconst ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1)\nconst ELL2_J = /* @__PURE__ */ BigInt(486662);\n/**\n * RFC 9380 method `map_to_curve_elligator2_curve25519`. Experimental name: may be renamed later.\n * @private\n */\n// prettier-ignore\nexport function _map_to_curve_elligator2_curve25519(u) {\n // 4. c4 = (q - 5) / 8: tv2^c4 below reuses the ed25519_pow_2_252_3 addition chain,\n // whose pow_p_5_8 output is exactly x^((p-5)/8).\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let xd = Fp.add(tv1, Fp.ONE);\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 = ed25519_pow_2_252_3(tv2).pow_p_5_8; // 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 // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let y1 = Fp.cmov(y12, y11, e1);\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 // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n let y2 = Fp.cmov(y22, y21, e2);\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// sgn0(c1) MUST equal 0\nconst ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))();\nfunction map_to_curve_elligator2_edwards25519(u) {\n // 1. (xMn, xMd, yMn, yMd) = map_to_curve_elligator2_curve25519(u)\n const { xMn, xMd, yMn, yMd } = _map_to_curve_elligator2_curve25519(u);\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 // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let yd = Fp.add(xMn, xMd);\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 const [xd_inv, yd_inv] = FpInvertBatch(Fp, [xd, yd], true); // batch division\n // Noble normalizes the RFC rational representation to affine `{ x, y }`\n // before returning from the internal helper.\n return { x: Fp.mul(xn, xd_inv), y: Fp.mul(yn, yd_inv) }; // 13. return (xn, xd, yn, yd)\n}\n/**\n * Hashing to ed25519 points / field. RFC 9380 methods.\n * Public `mapToCurve()` returns the cofactor-cleared subgroup point; the\n * internal map callback below consumes one field element bigint, not `[bigint]`.\n * @example\n * Hash one message onto the ed25519 curve.\n *\n * ```ts\n * const point = ed25519_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const ed25519_hasher = /* @__PURE__ */ (() => createHasher(ed25519_Point, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: ed25519_CURVE_p,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\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 = /* @__PURE__ */ BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235');\n// 1 / \u221A(a-d)\nconst INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578');\n// 1-d\u00B2\nconst ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838');\n// (d-1)\u00B2\nconst D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952');\n// `SQRT_RATIO_M1(1, number)` specialization. Returns `{ isValid, value }`,\n// where non-squares get the nonnegative `sqrt(SQRT_M1 / number)` branch.\nconst invertSqrt = (number) => uvRatio(_1n, number);\nconst MAX_255B = /* @__PURE__ */ BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\n// RFC 9496 \u00A74.3.4 MAP parser: masks bit 255 and reduces modulo p for element\n// derivation. The decode path has the opposite contract and rejects that bit.\nconst bytes255ToNumberLE = (bytes) => Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n/**\n * Computes Elligator map for Ristretto255.\n * Primary formula source is RFC 9496 \u00A74.3.4 MAP; RFC 9380 Appendix B builds\n * `hash_to_ristretto255` on top of this helper.\n * Returns an internal Edwards representative, not a public `_RistrettoPoint`.\n */\nfunction calcElligatorRistrettoMap(r0) {\n const { d } = ed25519_CURVE;\n const r = Fp.mul(Fp.mulN(SQRT_M1, r0), r0); // 1\n const Ns = Fp.mul(Fp.addN(r, _1n), ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = Fp.mul(Fp.subN(c, Fp.mulN(d, r)), Fp.add(r, d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = Fp.mul(s, r0); // 6\n if (!Fp.isOdd(s_))\n s_ = Fp.neg(s_);\n if (!Ns_D_is_sq)\n s = s_; // 7\n if (!Ns_D_is_sq)\n c = r; // 8\n const Nt = Fp.sub(Fp.mulN(Fp.mulN(c, Fp.subN(r, _1n)), D_MINUS_ONE_SQ), D); // 9\n const s2 = Fp.sqrN(s);\n const W0 = Fp.mul(Fp.addN(s, s), D); // 10\n const W1 = Fp.mul(Nt, SQRT_AD_MINUS_ONE); // 11\n const W2 = Fp.sub(_1n, s2); // 12\n const W3 = Fp.add(_1n, s2); // 13\n return new ed25519_Point(Fp.mul(W0, W3), Fp.mul(W2, W1), Fp.mul(W1, W3), Fp.mul(W0, W2));\n}\n/**\n * Wrapper over Edwards Point for ristretto255.\n *\n * Each ed25519/EdwardsPoint 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 EdwardsPoint,\n * but it should work in its own namespace: do not combine those two.\n * See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496).\n */\nclass _RistrettoPoint extends PrimeEdwardsPoint {\n // Do NOT change syntax: the following gymnastics is done,\n // because typescript strips comments, which makes bundlers disable tree-shaking.\n // prettier-ignore\n static BASE = \n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.BASE))();\n // prettier-ignore\n static ZERO = \n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.ZERO))();\n // prettier-ignore\n static Fp = \n /* @__PURE__ */ (() => Fp)();\n // prettier-ignore\n static Fn = \n /* @__PURE__ */ (() => Fn)();\n constructor(ep) {\n super(ep);\n }\n /**\n * Create one Ristretto255 point from affine Edwards coordinates.\n * This wraps the internal Edwards representative directly and is not a\n * canonical ristretto255 decoding path.\n * Use `toBytes()` / `fromBytes()` if canonical ristretto255 bytes matter.\n */\n static fromAffine(ap) {\n return new _RistrettoPoint(ed25519_Point.fromAffine(ap));\n }\n assertSame(other) {\n if (!(other instanceof _RistrettoPoint))\n throw new Error('RistrettoPoint expected');\n }\n init(ep) {\n return new _RistrettoPoint(ep);\n }\n static fromBytes(bytes) {\n abytes(bytes, 32);\n const { a, d } = ed25519_CURVE;\n const s = bytes255ToNumberLE(bytes);\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(Fp.toBytes(s), bytes) || Fp.isOdd(s))\n throw new Error('invalid ristretto255 encoding 1');\n const s2 = Fp.sqr(s);\n const u1 = Fp.add(_1n, Fp.mulN(a, s2)); // 4 (a is -1)\n const u2 = Fp.sub(_1n, Fp.mulN(a, s2)); // 5\n const u1_2 = Fp.sqr(u1);\n const u2_2 = Fp.sqr(u2);\n const v = Fp.sub(Fp.mulN(Fp.mulN(a, d), u1_2), u2_2); // 6\n const { isValid, value: I } = invertSqrt(Fp.mul(v, u2_2)); // 7\n const Dx = Fp.mul(I, u2); // 8\n const Dy = Fp.mul(Fp.mulN(I, Dx), v); // 9\n let x = Fp.mul(Fp.addN(s, s), Dx); // 10\n if (Fp.isOdd(x))\n x = Fp.neg(x); // 10\n const y = Fp.mul(u1, Dy); // 11\n const t = Fp.mul(x, y); // 12\n if (!isValid || Fp.isOdd(t) || Fp.is0(y))\n throw new Error('invalid ristretto255 encoding 2');\n return new _RistrettoPoint(new ed25519_Point(x, y, Fp.ONE, t));\n }\n /**\n * Converts ristretto-encoded string to ristretto point.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).\n * @param hex - Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex) {\n return _RistrettoPoint.fromBytes(hexToBytes(hex));\n }\n /**\n * Encodes ristretto point to Uint8Array.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).\n */\n toBytes() {\n let { X, Y, Z, T } = this.ep;\n const u1 = Fp.mul(Fp.add(Z, Y), Fp.sub(Z, Y)); // 1\n const u2 = Fp.mul(X, Y); // 2\n // Square root always exists\n const u2sq = Fp.sqr(u2);\n const { value: invsqrt } = invertSqrt(Fp.mul(u1, u2sq)); // 3\n const D1 = Fp.mul(invsqrt, u1); // 4\n const D2 = Fp.mul(invsqrt, u2); // 5\n const zInv = Fp.mul(Fp.mulN(D1, D2), T); // 6\n let D; // 7\n if (Fp.isOdd(Fp.mul(T, zInv))) {\n let _x = Fp.mul(Y, SQRT_M1);\n let _y = Fp.mul(X, SQRT_M1);\n X = _x;\n Y = _y;\n D = Fp.mul(D1, INVSQRT_A_MINUS_D);\n }\n else {\n D = D2; // 8\n }\n if (Fp.isOdd(Fp.mul(X, zInv)))\n Y = Fp.neg(Y); // 9\n let s = Fp.mul(Fp.subN(Z, Y), D); // 10 (check footer's note, no sqrt(-a))\n if (Fp.isOdd(s))\n s = Fp.neg(s);\n return Fp.toBytes(s); // 11\n }\n /**\n * Compares two Ristretto points.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).\n */\n equals(other) {\n this.assertSame(other);\n const { X: X1, Y: Y1 } = this.ep;\n const { X: X2, Y: Y2 } = other.ep;\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = Fp.eql(Fp.mul(X1, Y2), Fp.mul(Y1, X2));\n const two = Fp.eql(Fp.mul(Y1, Y2), Fp.mul(X1, X2));\n return one || two;\n }\n is0() {\n return this.equals(_RistrettoPoint.ZERO);\n }\n}\n/** Prime-order Ristretto255 group bundle. */\nexport const ristretto255 = /* @__PURE__ */ (() => {\n Object.freeze(_RistrettoPoint.BASE);\n Object.freeze(_RistrettoPoint.ZERO);\n Object.freeze(_RistrettoPoint.prototype);\n Object.freeze(_RistrettoPoint);\n return Object.freeze({ Point: _RistrettoPoint });\n})();\n/**\n * Hashing to ristretto255 points / field. RFC 9380 methods.\n * `hashToCurve()` is RFC 9380 Appendix B, `deriveToCurve()` is the RFC 9496\n * \u00A74.3.4 element-derivation building block, and `hashToScalar()` is a\n * library-specific helper for OPRF-style use.\n * @example\n * Hash one message onto ristretto255.\n *\n * ```ts\n * const point = ristretto255_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const ristretto255_hasher = \n/* @__PURE__ */ Object.freeze({\n Point: _RistrettoPoint,\n /**\n * Spec: https://www.rfc-editor.org/rfc/rfc9380.html#name-hashing-to-ristretto255. Caveats:\n * * There are no test vectors\n * * encodeToCurve / mapToCurve is undefined\n * * mapToCurve would be `calcElligatorRistrettoMap(scalars[0])`, not ristretto255_map!\n * * hashToScalar is undefined too, so we just use OPRF implementation\n * * We cannot re-use 'createHasher', because ristretto255_map is different algorithm/RFC\n (os2ip -> bytes255ToNumberLE)\n * * mapToCurve == calcElligatorRistrettoMap, hashToCurve == ristretto255_map\n * * hashToScalar is undefined in RFC9380 for ristretto, so we use the OPRF\n version here. Using `bytes255ToNumblerLE` will create a different result\n if we use `bytes255ToNumberLE` as os2ip\n * * current version is closest to spec.\n */\n hashToCurve(msg, options) {\n // == 'hash_to_ristretto255'\n // Preserve explicit empty/invalid DST overrides so expand_message_xmd() can reject them.\n const DST = options?.DST === undefined ? 'ristretto255_XMD:SHA-512_R255MAP_RO_' : options.DST;\n const xmd = expand_message_xmd(msg, DST, 64, sha512);\n // NOTE: RFC 9380 incorrectly calls this function `ristretto255_map`.\n // In RFC 9496, `map` was the per-point function inside the construction.\n // That also led to confusion that `ristretto255_map` is `mapToCurve`.\n // It is not: it is the older hash-to-curve construction.\n return ristretto255_hasher.deriveToCurve(xmd);\n },\n hashToScalar(msg, options) {\n const DST = options?.DST === undefined ? _DST_scalar : options.DST;\n const xmd = expand_message_xmd(msg, DST, 64, sha512);\n return Fn.create(bytesToNumberLE(xmd));\n },\n /**\n * HashToCurve-like construction based on RFC 9496 (Element Derivation).\n * Converts 64 uniform random bytes into a curve point.\n *\n * WARNING: This represents an older hash-to-curve construction from before\n * RFC 9380 was finalized.\n * It was later reused as a component in the newer\n * `hash_to_ristretto255` function defined in RFC 9380.\n */\n deriveToCurve(bytes) {\n // https://www.rfc-editor.org/rfc/rfc9496.html#name-element-derivation\n abytes(bytes, 64);\n const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new _RistrettoPoint(R1.add(R2));\n },\n});\n/**\n * ristretto255 OPRF/VOPRF/POPRF bundle, defined in RFC 9497.\n * @example\n * Run one blind/evaluate/finalize OPRF round over ristretto255.\n *\n * ```ts\n * const input = new TextEncoder().encode('hello noble');\n * const keys = ristretto255_oprf.oprf.generateKeyPair();\n * const blind = ristretto255_oprf.oprf.blind(input);\n * const evaluated = ristretto255_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded);\n * const output = ristretto255_oprf.oprf.finalize(input, blind.blind, evaluated);\n * ```\n */\nexport const ristretto255_oprf = /* @__PURE__ */ (() => createOPRF({\n name: 'ristretto255-SHA512',\n Point: _RistrettoPoint,\n hash: sha512,\n hashToGroup: ristretto255_hasher.hashToCurve,\n hashToScalar: ristretto255_hasher.hashToScalar,\n}))();\n/**\n * FROST threshold signatures over ristretto255. RFC 9591.\n * @example\n * Create one trusted-dealer package for 2-of-3 ristretto255 signing.\n *\n * ```ts\n * const alice = ristretto255_FROST.Identifier.derive('alice@example.com');\n * const bob = ristretto255_FROST.Identifier.derive('bob@example.com');\n * const carol = ristretto255_FROST.Identifier.derive('carol@example.com');\n * const deal = ristretto255_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const ristretto255_FROST = /* @__PURE__ */ (() => createFROST({\n name: 'FROST-RISTRETTO255-SHA512-v1',\n Point: _RistrettoPoint,\n validatePoint: (p) => {\n // Prime-order wrappers are torsion-free at the abstract-group level.\n p.assertValidity();\n },\n hash: sha512,\n}))();\n/**\n * Weird / bogus points, useful for debugging.\n * All 8 ed25519 points of 8-torsion subgroup can be generated from the point\n * T = `26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05`.\n * The subgroup generated by `T` is `{ O, T, 2T, 3T, 4T, 5T, 6T, 7T }`; the\n * array below is that set, not the powers in that exact index order.\n * @example\n * Decode one known torsion point for debugging.\n *\n * ```ts\n * import { ED25519_TORSION_SUBGROUP, ed25519 } from '@noble/curves/ed25519.js';\n * const point = ed25519.Point.fromHex(ED25519_TORSION_SUBGROUP[1]);\n * ```\n */\nexport const ED25519_TORSION_SUBGROUP = /* @__PURE__ */ Object.freeze([\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n]);\n", "/**\n * NIST P256, P384, P521 curves.\n * https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-256\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256, sha384, sha512 } from '@noble/hashes/sha2.js';\nimport { createFROST } from \"./abstract/frost.js\";\nimport { createHasher, mapToCurveSimpleSWU } from \"./abstract/hash-to-curve.js\";\nimport { createOPRF } from \"./abstract/oprf.js\";\nimport { ecdsa, weierstrass, } from \"./abstract/weierstrass.js\";\nimport {} from \"./utils.js\";\n// p = 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n - 1n\n// a = Fp256.create(BigInt('-3'));\nconst p256_CURVE = /* @__PURE__ */ (() => ({\n p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),\n n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),\n h: BigInt(1),\n a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),\n b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),\n Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),\n Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),\n}))();\n// p = 2n**384n - 2n**128n - 2n**96n + 2n**32n - 1n\nconst p384_CURVE = /* @__PURE__ */ (() => ({\n p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff'),\n n: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'),\n h: BigInt(1),\n a: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc'),\n b: BigInt('0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef'),\n Gx: BigInt('0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'),\n Gy: BigInt('0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'),\n}))();\n// p = 2n**521n - 1n\nconst p521_CURVE = /* @__PURE__ */ (() => ({\n p: BigInt('0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'),\n n: BigInt('0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409'),\n h: BigInt(1),\n a: BigInt('0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc'),\n b: BigInt('0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00'),\n Gx: BigInt('0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66'),\n Gy: BigInt('0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650'),\n}))();\nfunction createSWU(Point, opts) {\n let map;\n // RFC 9380's NIST suites here all use m = 1, so createHasher passes one field element per map.\n // Building the SWU sqrt-ratio helper eagerly adds noticeable `nist.js` import cost, so defer it\n // to first use; after that the cached mapper is reused directly.\n return (scalars) => (map || (map = mapToCurveSimpleSWU(Point.Fp, opts)))(scalars[0]);\n}\n// NIST P256\nconst p256_Point = /* @__PURE__ */ weierstrass(p256_CURVE);\n/**\n * NIST P256 (aka secp256r1, prime256v1) curve, ECDSA and ECDH methods.\n * Hashes inputs with sha256 by default.\n *\n * @example\n * Generate one P-256 keypair, sign a message, and verify it.\n *\n * ```js\n * import { p256 } from '@noble/curves/nist.js';\n * const { secretKey, publicKey } = p256.keygen();\n * const recovered = p256.getPublicKey(secretKey);\n * const peer = p256.keygen();\n * const shared = p256.getSharedSecret(secretKey, peer.publicKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = p256.sign(msg, secretKey, { lowS: true, prehash: true });\n * const isValid = p256.verify(sig, msg, publicKey);\n * // const sigKeccak = p256.sign(keccak256(msg), secretKey, { prehash: false });\n * ```\n */\nexport const p256 = /* @__PURE__ */ ecdsa(p256_Point, sha256);\n/**\n * Hashing / encoding to p256 points / field. RFC 9380 methods.\n * @example\n * Hash one message onto the P-256 curve.\n *\n * ```ts\n * const point = p256_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const p256_hasher = /* @__PURE__ */ (() => {\n return createHasher(p256_Point, createSWU(p256_Point, {\n A: p256_CURVE.a,\n B: p256_CURVE.b,\n Z: p256_Point.Fp.neg(BigInt(10)),\n }), {\n DST: 'P256_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'P256_XMD:SHA-256_SSWU_NU_',\n p: p256_CURVE.p,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n });\n})();\n/**\n * p256 OPRF, defined in RFC 9497.\n * @example\n * Run one blind/evaluate/finalize OPRF round over P-256.\n *\n * ```ts\n * const input = new TextEncoder().encode('hello noble');\n * const keys = p256_oprf.oprf.generateKeyPair();\n * const blind = p256_oprf.oprf.blind(input);\n * const evaluated = p256_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded);\n * const output = p256_oprf.oprf.finalize(input, blind.blind, evaluated);\n * ```\n */\nexport const p256_oprf = /* @__PURE__ */ (() => createOPRF({\n name: 'P256-SHA256',\n Point: p256_Point,\n hash: sha256,\n hashToGroup: p256_hasher.hashToCurve,\n hashToScalar: p256_hasher.hashToScalar,\n}))();\n/**\n * FROST threshold signatures over p256. RFC 9591.\n * @example\n * Create one trusted-dealer package for 2-of-3 p256 signing.\n *\n * ```ts\n * const alice = p256_FROST.Identifier.derive('alice@example.com');\n * const bob = p256_FROST.Identifier.derive('bob@example.com');\n * const carol = p256_FROST.Identifier.derive('carol@example.com');\n * const deal = p256_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const p256_FROST = /* @__PURE__ */ (() => createFROST({\n name: 'FROST-P256-SHA256-v1',\n Point: p256_Point,\n hashToScalar: p256_hasher.hashToScalar,\n hash: sha256,\n}))();\nconst p384_Point = /* @__PURE__ */ weierstrass(p384_CURVE);\n/**\n * NIST P384 (aka secp384r1) curve, ECDSA and ECDH methods. Hashes inputs with sha384 by default.\n * @example\n * Generate one P-384 keypair, sign a message, and verify it.\n *\n * ```ts\n * const { secretKey, publicKey } = p384.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = p384.sign(msg, secretKey);\n * const isValid = p384.verify(sig, msg, publicKey);\n * ```\n */\nexport const p384 = /* @__PURE__ */ ecdsa(p384_Point, sha384);\n/**\n * Hashing / encoding to p384 points / field. RFC 9380 methods.\n * @example\n * Hash one message onto the P-384 curve.\n *\n * ```ts\n * const point = p384_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const p384_hasher = /* @__PURE__ */ (() => {\n return createHasher(p384_Point, createSWU(p384_Point, {\n A: p384_CURVE.a,\n B: p384_CURVE.b,\n Z: p384_Point.Fp.neg(BigInt(12)),\n }), {\n DST: 'P384_XMD:SHA-384_SSWU_RO_',\n encodeDST: 'P384_XMD:SHA-384_SSWU_NU_',\n p: p384_CURVE.p,\n m: 1,\n k: 192,\n expand: 'xmd',\n hash: sha384,\n });\n})();\n/**\n * p384 OPRF, defined in RFC 9497.\n * @example\n * Run one blind/evaluate/finalize OPRF round over P-384.\n *\n * ```ts\n * const input = new TextEncoder().encode('hello noble');\n * const keys = p384_oprf.oprf.generateKeyPair();\n * const blind = p384_oprf.oprf.blind(input);\n * const evaluated = p384_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded);\n * const output = p384_oprf.oprf.finalize(input, blind.blind, evaluated);\n * ```\n */\nexport const p384_oprf = /* @__PURE__ */ (() => createOPRF({\n name: 'P384-SHA384',\n Point: p384_Point,\n hash: sha384,\n hashToGroup: p384_hasher.hashToCurve,\n hashToScalar: p384_hasher.hashToScalar,\n}))();\n// NIST P521\n// RFC 7518 fixes the canonical JWK/JOSE width at 66 bytes:\n// - Section 3.4 says ECDSA octet strings must not omit leading zero octets\n// - Sections 6.2.1.2/6.2.1.3 say P-521 coordinates \"x\"/\"y\" must be 66 octets\n// - Section 6.2.2.1 says private scalar \"d\" must be ceil(log2(n)/8) octets, i.e. 66 for P-521\n// NIST FIPS 186-5 Appendix A.3.3 also routes deterministic ECDSA private keys through Appendix\n// B.2.3, whose Integer-to-Octet-String output has explicit fixed length L; for P-521 that is the\n// same 66-byte order width.\n// RFC 6979 matches that width too: private key x is an integer, while `int2octets(x)` uses\n// rlen = 8 * ceil(qlen/8); for P-521, qlen = 521 so the canonical octet width is 66 bytes.\n// Wycheproof ECDH stores private values as integers, not fixed-width scalar bytes, so it does not\n// require a dedicated 65-byte parser path; the repo tests now normalize those integer fixtures to\n// the canonical 66-byte width before use. There is no good standards or oracle reason to accept\n// exactly 65 bytes here: the coherent choices are canonical 66 only, or a broader integer-style\n// parser across many widths. Since this field parser is fixed-width, keep it canonical and use the\n// default exact-66-byte scalar field path.\n// A dedicated MersenneField primitive would allow speed-ups here: +40% getPublicKey, +23% sign,\n// +53% verify, +53% getSharedSecret.\nconst p521_Point = /* @__PURE__ */ weierstrass(p521_CURVE);\n/**\n * NIST P521 (aka secp521r1) curve, ECDSA and ECDH methods. Hashes inputs with sha512 by default.\n * Deterministic `keygen(seed)` expects 99 seed bytes here because the generic scalar-derivation\n * helper uses `getMinHashLength(n)`, not the 66-byte canonical secret-key width.\n * @example\n * Generate one P-521 keypair, sign a message, and verify it.\n *\n * ```ts\n * const { secretKey, publicKey } = p521.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = p521.sign(msg, secretKey);\n * const isValid = p521.verify(sig, msg, publicKey);\n * ```\n */\nexport const p521 = /* @__PURE__ */ ecdsa(p521_Point, sha512);\n/**\n * Hashing / encoding to p521 points / field. RFC 9380 methods.\n * @example\n * Hash one message onto the P-521 curve.\n *\n * ```ts\n * const point = p521_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const p521_hasher = /* @__PURE__ */ (() => {\n return createHasher(p521_Point, createSWU(p521_Point, {\n A: p521_CURVE.a,\n B: p521_CURVE.b,\n Z: p521_Point.Fp.neg(BigInt(4)),\n }), {\n DST: 'P521_XMD:SHA-512_SSWU_RO_',\n encodeDST: 'P521_XMD:SHA-512_SSWU_NU_',\n p: p521_CURVE.p,\n m: 1,\n k: 256,\n expand: 'xmd',\n hash: sha512,\n });\n})();\n/**\n * p521 OPRF, defined in RFC 9497.\n * @example\n * Run one blind/evaluate/finalize OPRF round over P-521.\n *\n * ```ts\n * const input = new TextEncoder().encode('hello noble');\n * const keys = p521_oprf.oprf.generateKeyPair();\n * const blind = p521_oprf.oprf.blind(input);\n * const evaluated = p521_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded);\n * const output = p521_oprf.oprf.finalize(input, blind.blind, evaluated);\n * ```\n */\nexport const p521_oprf = /* @__PURE__ */ (() => createOPRF({\n name: 'P521-SHA512',\n Point: p521_Point,\n hash: sha512,\n hashToGroup: p521_hasher.hashToCurve,\n hashToScalar: p521_hasher.hashToScalar, // produces L=98 just like in RFC\n}))();\n", "/**\n * HKDF (RFC 5869): extract + expand in one step.\n * See {@link https://soatok.blog/2021/11/17/understanding-hkdf/}.\n * @module\n */\nimport { hmac } from \"./hmac.js\";\nimport { abytes, ahash, anumber, clean } from \"./utils.js\";\n/**\n * HKDF-extract from spec. Less important part. `HKDF-Extract(IKM, salt) -> PRK`\n * Arguments position differs from spec (IKM is first one, since it is not optional)\n * Local validation only checks `hash`; `ikm` / `salt` byte validation is delegated to `hmac()`.\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n * @returns Pseudorandom key derived from input keying material.\n * @example\n * Run the HKDF extract step.\n * ```ts\n * import { extract } from '@noble/hashes/hkdf.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * extract(sha256, new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]));\n * ```\n */\nexport function extract(hash, ikm, salt) {\n ahash(hash);\n // NOTE: some libraries treat zero-length array as 'not provided';\n // we don't, since we have undefined as 'not provided'\n // https://github.com/RustCrypto/KDFs/issues/15\n if (salt === undefined)\n salt = new Uint8Array(hash.outputLen);\n return hmac(hash, salt, ikm);\n}\n// Shared mutable scratch byte for the RFC 5869 block counter `N`.\n// Safe to reuse because `expand()` is synchronous and resets it with `clean(...)` before returning.\nconst HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0);\n// Shared RFC 5869 empty string for both `info === undefined` and the first-block `T(0)` input.\nconst EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();\n/**\n * HKDF-expand from the spec. The most important part. `HKDF-Expand(PRK, info, L) -> OKM`\n * @param hash - hash function that would be used (e.g. sha256)\n * @param prk - a pseudorandom key of at least HashLen octets\n * (usually, the output from the extract step)\n * @param info - optional context and application specific information (can be a zero-length string)\n * @param length - length of output keying material in bytes.\n * RFC 5869 \u00A72.3 allows `0..255*HashLen`, so `0` returns an empty OKM.\n * @param _recycled - Internal destroyed extract hashes owned by the combined `hkdf()` call.\n * @returns Output keying material with the requested length.\n * @throws If the requested output length exceeds the HKDF limit\n * for the selected hash. {@link Error}\n * @example\n * Run the HKDF expand step.\n * ```ts\n * import { expand } from '@noble/hashes/hkdf.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * expand(sha256, new Uint8Array(32), new Uint8Array([1, 2, 3]), 16);\n * ```\n */\nexport function expand(hash, prk, info, length = 32, _recycled) {\n ahash(hash);\n anumber(length, 'length');\n abytes(prk, undefined, 'prk');\n const olen = hash.outputLen;\n // RFC 5869 \u00A72.3: PRK is \"a pseudorandom key of at least HashLen octets\".\n if (prk.length < olen)\n throw new Error('\"prk\" must be at least HashLen octets');\n // RFC 5869 \u00A72.3 only bounds `L` by `<= 255*HashLen`; `L=0` is valid and yields empty OKM.\n if (length > 255 * olen)\n throw new Error('Length must be <= 255*HashLen');\n const blocks = Math.ceil(length / olen);\n if (info === undefined)\n info = EMPTY_BUFFER;\n else\n abytes(info, undefined, 'info');\n if (!blocks) {\n if (_recycled)\n clean(prk); // Full hkdf() owns this intermediate PRK.\n return new Uint8Array();\n }\n // first L(ength) octets of T\n // The private PRK can become both T and a one-block result after HMAC consumes the key.\n const okm = _recycled && blocks === 1 ? prk : new Uint8Array(blocks * olen);\n const { iHash, oHash } = hmac.create(hash, prk);\n // Driving them directly also skips `_HMAC.digestInto`'s per-digest destroy.\n const T = _recycled ? prk : new Uint8Array(olen);\n // Full hkdf() donates one destroyed extract hash; standalone creates one alternating worker.\n const worker = blocks > 1 ? _recycled?.iHash || hash.create() : undefined;\n for (let counter = 0; counter < blocks - 1; counter++) {\n HKDF_COUNTER[0] = counter + 1;\n const iWork = iHash._cloneInto(worker);\n // T(0) = empty string (zero length)\n // T(N) = HMAC-Hash(PRK, T(N-1) | info | N)\n if (counter)\n iWork.update(T);\n iWork.update(info).update(HKDF_COUNTER).digestInto(T);\n oHash._cloneInto(worker).update(T).digestInto(T);\n okm.set(T, olen * counter);\n }\n // Midstates are key-equivalent: they allow computing HMAC(prk, ...) for any message.\n HKDF_COUNTER[0] = blocks; // Final block consumes them; retain worker for cleanup.\n if (blocks > 1)\n iHash.update(T);\n iHash.update(info).update(HKDF_COUNTER).digestInto(T);\n oHash.update(T).digestInto(T);\n okm.set(T, olen * (blocks - 1));\n iHash.destroy(); // Raw digests may leave key-derived base/worker state; wipe all explicitly.\n oHash.destroy();\n worker?.destroy();\n if (T !== okm)\n clean(T); // Wipe private T/PRK; standalone preserves caller-owned PRK.\n clean(HKDF_COUNTER);\n // Exact fit: return without the extra copy.\n if (length === okm.length)\n return okm;\n // Copy the requested prefix, then wipe the full buffer: its tail holds\n // up to HashLen-1 bytes of derived key material past `length`.\n const res = okm.slice(0, length);\n clean(okm);\n return res;\n}\n/**\n * HKDF (RFC 5869): derive keys from an initial input.\n * Combines hkdf_extract + hkdf_expand in one step\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n * @param info - optional context and application specific information bytes\n * @param length - length of output keying material in bytes.\n * RFC 5869 \u00A72.3 allows `0..255*HashLen`, so `0` returns an empty OKM.\n * @returns Output keying material derived from the input key.\n * @throws If the requested output length exceeds the HKDF limit\n * for the selected hash. {@link Error}\n * @example\n * HKDF (RFC 5869): derive keys from an initial input.\n * ```ts\n * import { hkdf } from '@noble/hashes/hkdf.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { randomBytes, utf8ToBytes } from '@noble/hashes/utils.js';\n * const inputKey = randomBytes(32);\n * const salt = randomBytes(32);\n * const info = utf8ToBytes('application-key');\n * const okm = hkdf(sha256, inputKey, salt, info, 32);\n * ```\n */\nexport const hkdf = (hash, ikm, salt, info, length) => {\n ahash(hash);\n if (salt === undefined)\n salt = new Uint8Array(hash.outputLen);\n const HMAC = hmac.create(hash, salt).update(ikm);\n // The intermediate PRK is secret key material; wipe it instead of\n // leaving it for GC.\n return expand(hash, HMAC.digest(), info, length, HMAC); // expand() owns and consumes it.\n};\n", "/**\n * Post-Quantum Hybrid Cryptography\n *\n * The current implementation is flawed and likely redundant. We should offer\n * a small, generic API to compose hybrid schemes instead of reimplementing\n * protocol-specific logic (SSH, GPG, etc.) with ad hoc encodings.\n *\n * 1. Core Issues\n * - sign/verify: implemented as two separate operations with different keys.\n * - EC getSharedSecret: could be refactored into a proper KEM.\n * - Multiple calls: keys, signatures, and shared secrets could be\n * concatenated to reduce the number of API invocations.\n * - Reinvention: most libraries add strange domain separations and\n * encodings instead of simple byte concatenation.\n *\n * 2. API Goals\n * - Provide primitives to build hybrids generically.\n * - Avoid embedding SSH- or GPG-specific formats in the core API.\n *\n * 3. Edge Cases\n * \u2022 Variable-length signatures:\n * - DER-encoded (Weierstrass curves).\n * - Falcon (unpadded).\n * - Concatenation works only if length is fixed; otherwise a length\n * prefix is required (but that breaks compatibility).\n *\n * \u2022 getSharedSecret:\n * - Default: non-KEM (authenticated ECDH).\n * - KEM conversion: generate a random SK to remove implicit auth.\n *\n * 4. Common Pitfalls\n * - Seed expansion:\n * \u2022 Expanding a small seed into multiple keys reduces entropy.\n * \u2022 API should allow identity mapping (no expansion).\n *\n * - Skipping full point encoding:\n * \u2022 Some omit the compression byte (parity) for WebCrypto compatibility.\n * \u2022 Better: hash the raw secret; coordinate output is already non-uniform.\n * \u2022 Some curves (e.g., X448) produce secrets that must be re-hashed to match\n * symmetric-key lengths.\n *\n * - Combiner inconsistencies:\n * \u2022 Different domain separations and encodings across libraries.\n * \u2022 Should live at the application layer, since key lengths vary.\n *\n * 5. Protocol Examples\n * - SSH:\n * \u2022 Concatenate keys.\n * \u2022 Combiner: SHA-512.\n *\n * - GPG:\n * \u2022 Concatenate keys.\n * \u2022 Combiner:\n * SHA3-256(kemShare || ecdhShare || ciphertext || pubKey || algId || domSep || len(domSep))\n *\n * - TLS:\n * \u2022 Transcript-based derivation (HKDF).\n *\n * 6. Relevant Specs & Implementations\n * - IETF Hybrid KEM drafts:\n * \u2022 draft-irtf-cfrg-hybrid-kems\n * \u2022 draft-connolly-cfrg-xwing-kem\n * \u2022 draft-westerbaan-tls-xyber768d00\n *\n * - PQC Libraries:\n * \u2022 superdilithium (cyph/pqcrypto.js) \u2013 low adoption.\n * \u2022 hybrid-pqc (DogeProtocol, quantumcoinproject) \u2013 complex encodings.\n *\n * 7. Signatures\n * - Ed25519: fixed-size, easy to support.\n * - Variable-size: introduces custom format requirements; best left to\n * higher-level code.\n *\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport {} from '@noble/curves/abstract/edwards.js';\nimport {} from '@noble/curves/abstract/montgomery.js';\nimport {} from '@noble/curves/abstract/weierstrass.js';\nimport { x25519 } from '@noble/curves/ed25519.js';\nimport { p256, p384 } from '@noble/curves/nist.js';\nimport { abool, afunction, asciiToBytes, bytesToNumberBE, bytesToNumberLE, concatBytes, numberToBytesBE, } from '@noble/curves/utils.js';\nimport { expand, extract } from '@noble/hashes/hkdf.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { sha3_256, shake256 } from '@noble/hashes/sha3.js';\nimport { abytes, ahash, anumber, isBytes } from '@noble/hashes/utils.js';\nimport { ml_kem1024, ml_kem768 } from \"./ml-kem.js\";\nimport { aobject, astring, cleanBytes, copyBytes, randomBytes, splitCoder, validateSigOpts, validateVerOpts, } from \"./utils.js\";\nconst validateKEM = (kem, title) => {\n const k = aobject(kem, title);\n aobject(k.lengths, `${title}.lengths`);\n afunction(k.keygen, `${title}.keygen`);\n afunction(k.getPublicKey, `${title}.getPublicKey`);\n afunction(k.encapsulate, `${title}.encapsulate`);\n afunction(k.decapsulate, `${title}.decapsulate`);\n return k;\n};\nconst validateSigner = (signer, title) => {\n const s = aobject(signer, title);\n aobject(s.lengths, `${title}.lengths`);\n afunction(s.keygen, `${title}.keygen`);\n afunction(s.getPublicKey, `${title}.getPublicKey`);\n afunction(s.sign, `${title}.sign`);\n afunction(s.verify, `${title}.verify`);\n return s;\n};\n// Can re-use if decide to signatures support, on other hand getSecretKey is specific and ugly\nfunction ecKeygen(curve, allowZeroKey = false) {\n const c = aobject(curve, 'curve');\n aobject(c.lengths, 'curve.lengths');\n afunction(c.keygen, 'curve.keygen');\n afunction(c.getPublicKey, 'curve.getPublicKey');\n abool(allowZeroKey, 'allowZeroKey');\n const lengths = curve.lengths;\n let keygen = curve.keygen;\n if (allowZeroKey) {\n // Only the ECDSA/Weierstrass branch uses raw scalar-byte secret keys here. Edwards seeds are\n // hashed/pruned and Montgomery keys are clamped byte strings, so forcing Point.Fn semantics on\n // those curves would change key construction instead of just relaxing scalar range handling.\n if (!('getSharedSecret' in curve && 'sign' in curve && 'verify' in curve))\n throw new Error('allowZeroKey requires a Weierstrass curve');\n // This legacy flag is really \"skip the +1 shift\" for vector matching, not \"accept scalar 0\".\n // It swaps seeded Weierstrass keygen from reduction into [1, ORDER) to direct reduction into\n // [0, ORDER), which preserves exact reduced bytes but still leaves scalar 0 invalid.\n // This is ugly, but we need to return exact results here.\n const wCurve = curve;\n const Fn = wCurve.Point.Fn;\n // Unlike noble-curves' seeded Weierstrass keygen, this path removes the post-reduction +1.\n // That is enough to match exact reduced-vector bytes, but an all-zero seed still reduces to\n // scalar 0 here and getPublicKey(secretKey) throws instead of \"allowing zero\".\n keygen = (seed = randomBytes(lengths.seed)) => {\n abytes(seed, lengths.seed, 'seed');\n const seedScalar = Fn.isLE ? bytesToNumberLE(seed) : bytesToNumberBE(seed);\n // Reduce directly into [0, ORDER); scalar 0 still stays invalid.\n const secretKey = Fn.toBytes(Fn.create(seedScalar));\n return {\n secretKey: secretKey,\n publicKey: curve.getPublicKey(secretKey),\n };\n };\n }\n return {\n lengths: { secretKey: lengths.secretKey, publicKey: lengths.publicKey, seed: lengths.seed },\n keygen: (seed) => keygen(seed),\n getPublicKey: (secretKey) => curve.getPublicKey(secretKey),\n };\n}\n/**\n * Wraps an ECDH-capable curve as a KEM.\n * Shared secrets stay in the wrapped curve's raw ECDH byte format with no built-in KDF.\n *\n * SECURITY: this is a low-level component adapter, not a standalone IND-CCA-secure KEM. It does\n * not bind the encapsulation or recipient public key into the secret, so distinct accepted point\n * encodings can produce the same output. Use it only inside a construction whose specified\n * combiner binds those values, or use a standardized DHKEM with labeled extract-and-expand.\n *\n * On SEC 1 / Weierstrass curves, that means the compressed shared-point body without the\n * 1-byte `0x02` / `0x03` prefix.\n * The X25519 path also leaves RFC 7748's optional all-zero shared-secret check to callers.\n * @param curve - Curve with `getSharedSecret`.\n * @param allowZeroKey - Legacy vector-matching toggle for Weierstrass keygen.\n * On Weierstrass curves this removes the usual post-reduction `+1` shift, changing seeded scalar\n * reduction from `[1, ORDER)` to direct reduction into `[0, ORDER)`. It does not make scalar zero\n * valid: an all-zero seed still derives scalar `0` and throws in `curve.getPublicKey(...)`.\n * Only supported on Weierstrass/ECDSA curves.\n * @returns KEM wrapper over the curve.\n * @throws If the curve does not expose `getSharedSecret`. {@link Error}\n * @example\n * Wrap an ECDH-capable curve as a generic KEM.\n * ```ts\n * import { x25519 } from '@noble/curves/ed25519.js';\n * import { _ecdhKem } from '@noble/post-quantum/hybrid.js';\n * const kem = _ecdhKem(x25519);\n * const publicKeyLen = kem.lengths.publicKey;\n * ```\n */\nexport function _ecdhKem(curve, allowZeroKey = false) {\n const kg = ecKeygen(curve, allowZeroKey);\n if (!curve.getSharedSecret)\n throw new Error('wrong curve'); // ed25519 doesn't have one!\n // Standalone (not `this.decapsulate`) so encapsulate works even when methods are destructured.\n const decapsulate = (cipherText, secretKey) => {\n const res = curve.getSharedSecret(secretKey, cipherText);\n return (curve.lengths.publicKeyHasPrefix ? res.subarray(1) : res);\n };\n return {\n lengths: { ...kg.lengths, msg: kg.lengths.seed, cipherText: kg.lengths.publicKey },\n keygen: kg.keygen,\n getPublicKey: kg.getPublicKey,\n encapsulate(publicKey, rand = randomBytes(curve.lengths.seed)) {\n // Some curve.keygen(seed) paths reuse the provided seed buffer as secretKey; detach caller\n // randomness first so cleanBytes() only wipes wrapper-owned material.\n const seed = copyBytes(rand);\n let ek = undefined;\n try {\n ek = kg.keygen(seed).secretKey;\n const sharedSecret = decapsulate(publicKey, ek);\n const cipherText = curve.getPublicKey(ek);\n return { sharedSecret, cipherText };\n }\n finally {\n // Invalid peer public keys can make decapsulation throw; wipe both the detached seed and\n // derived ephemeral secret key even when encapsulation aborts before returning.\n cleanBytes(seed);\n if (ek)\n cleanBytes(ek);\n }\n },\n decapsulate,\n };\n}\n/**\n * Wraps a curve signer as a generic `Signer`.\n * Signatures stay in the wrapped curve's native byte encoding.\n * This wrapper does not normalize or document which per-curve signing options are meaningful.\n * @param curve - Curve with `sign` and `verify`.\n * @param allowZeroKey - Legacy vector-matching toggle for Weierstrass keygen.\n * On Weierstrass curves this removes the usual post-reduction `+1` shift, changing seeded scalar\n * reduction from `[1, ORDER)` to direct reduction into `[0, ORDER)`. It does not make scalar zero\n * valid: an all-zero seed still derives scalar `0` and throws in `curve.getPublicKey(...)`.\n * Only supported on Weierstrass/ECDSA curves.\n * @returns Signer wrapper over the curve.\n * @throws If the curve does not expose `sign` and `verify`. {@link Error}\n * @example\n * Wrap a curve signer as a generic signer.\n * ```ts\n * import { ed25519 } from '@noble/curves/ed25519.js';\n * import { ecSigner } from '@noble/post-quantum/hybrid.js';\n * const signer = ecSigner(ed25519);\n * const sigLen = signer.lengths.signature;\n * ```\n */\nexport function ecSigner(curve, allowZeroKey = false) {\n const kg = ecKeygen(curve, allowZeroKey);\n if (!curve.sign || !curve.verify)\n throw new Error('wrong curve'); // ed25519 doesn't have one!\n return {\n lengths: { ...kg.lengths, signature: curve.lengths.signature, signRand: 0 },\n keygen: kg.keygen,\n getPublicKey: kg.getPublicKey,\n sign: (message, secretKey, opts = {}) => {\n opts = validateSigOpts(opts);\n // This generic wrapper intentionally keeps the Signer contract to message + key only.\n // Backend-specific knobs like ECDSA extraEntropy or Ed25519ctx context cannot be forwarded\n // uniformly through combineSigners(), so callers that need them must use the curve directly.\n if (opts.extraEntropy !== undefined)\n throw new Error('ecSigner does not support extraEntropy; use the underlying curve directly');\n if (opts.context !== undefined)\n throw new Error('ecSigner does not support context; use the underlying curve directly');\n return curve.sign(message, secretKey);\n },\n /** Verify one wrapped curve signature.\n * Returns the wrapped curve's `verify()` result for well-formed inputs. Throws on unsupported\n * generic opts and lets wrapped-curve malformed-input errors escape unchanged.\n */\n verify: (signature, message, publicKey, opts = {}) => {\n opts = validateVerOpts(opts);\n if (opts.context !== undefined)\n throw new Error('ecSigner does not support context; use the underlying curve directly');\n return curve.verify(signature, message, publicKey);\n },\n };\n}\nfunction positiveLength(value, title) {\n const length = anumber(value, title);\n if (length === 0)\n throw new RangeError(`\"${title}\" expected integer greater than 0, got 0`);\n return length;\n}\nfunction splitLengths(lst, name) {\n // Preserve caller order exactly; raw numeric fields still decode as splitCoder() subarray views.\n const coder = splitCoder(name, ...lst.map((i) => {\n if (typeof i.lengths[name] !== 'number')\n throw new Error('wrong length: ' + name);\n return positiveLength(i.lengths[name], name);\n }));\n positiveLength(coder.bytesLen, name);\n return coder;\n}\n// It is XOF for most cases, but can be more complex!\n/**\n * Adapts an XOF into an `ExpandSeed` callback.\n * The returned callback interprets its second argument as an output byte length passed as `dkLen`.\n * @param xof - Extendable-output hash function.\n * @returns Seed expander using `dkLen`.\n * @example\n * Adapt an XOF into a seed expander.\n * ```ts\n * import { shake256 } from '@noble/hashes/sha3.js';\n * import { expandSeedXof } from '@noble/post-quantum/hybrid.js';\n * const expandSeed = expandSeedXof(shake256);\n * const seed = expandSeed(new Uint8Array([1]), 4);\n * ```\n */\nexport function expandSeedXof(xof) {\n // Forward the caller seed directly: XOFs are expected to treat inputs as read-only, and this\n // adapter only translates the requested byte length into the hash API's `dkLen` option.\n return ((seed, seedLen) => xof(seed, { dkLen: seedLen }));\n}\nfunction combineKeys(realSeedLen, // how much bytes expandSeed expects\nexpandSeed_, ...ck_) {\n const expandSeed = expandSeed_;\n const ck = ck_;\n const seedCoder = splitLengths(ck, 'seed');\n const pkCoder = splitLengths(ck, 'publicKey');\n // Allows to use identity functions for combiner/expandSeed\n const rootSeedLen = positiveLength(realSeedLen === undefined ? seedCoder.bytesLen : realSeedLen, 'realSeedLen');\n function expandDecapsulationKey(seed) {\n abytes(seed, rootSeedLen);\n const expandedRaw = expandSeed(seed, seedCoder.bytesLen);\n // Identity/subarray expanders can hand back caller-owned seed storage. Detach those outputs so\n // later cleanup can wipe the expanded schedule without mutating the caller's root seed bytes.\n const expandedSeed = expandedRaw.buffer === seed.buffer ? copyBytes(expandedRaw) : expandedRaw;\n const expanded = [];\n const keySecret = [];\n const secretKey = [];\n const publicKey = [];\n let ok = false;\n try {\n // seedCoder.decode() returns zero-copy slices into expandedSeed and can throw before child\n // keygen() runs, so keep the raw expanded buffer separate and copy each child seed before any\n // later cleanup wipes the shared backing bytes.\n for (const part of seedCoder.decode(expandedSeed))\n expanded.push(copyBytes(part));\n for (let i = 0; i < ck.length; i++) {\n const keys = ck[i].keygen(expanded[i]);\n keySecret.push(keys.secretKey);\n secretKey.push(copyBytes(keys.secretKey));\n publicKey.push(keys.publicKey);\n }\n ok = true;\n return { secretKey, publicKey };\n }\n finally {\n // Child keygen() can throw after deriving only a prefix of the composite key schedule. Keep\n // the exported copies on success, but wipe all temporary and partially built secret material\n // on either path so failures do not strand derived child seeds in memory.\n cleanBytes(expandedSeed, expanded, keySecret);\n if (!ok)\n cleanBytes(secretKey);\n }\n }\n // Standalone (not a method) so getPublicKey / destructured usage never depends on `this`.\n const keygen = (seed) => {\n // Detach the root: the exported secretKey must not alias caller-owned seed bytes, so later\n // caller mutation of the seed cannot silently change the secret key (and vice versa).\n const root = seed === undefined ? randomBytes(rootSeedLen) : copyBytes(seed);\n let res;\n try {\n const { publicKey: pk, secretKey } = expandDecapsulationKey(root);\n try {\n res = {\n secretKey: root,\n publicKey: pkCoder.encode(pk),\n };\n }\n finally {\n // The exported secretKey is the (detached) root seed; child secret keys are internal\n // expansion outputs that are cleaned whether encoding succeeds or throws.\n cleanBytes(pk, secretKey);\n }\n return res;\n }\n finally {\n if (!res)\n cleanBytes(root);\n }\n };\n return {\n info: { lengths: { seed: rootSeedLen, publicKey: pkCoder.bytesLen, secretKey: rootSeedLen } },\n // Composite secret keys are root seeds, so public-key derivation reruns key expansion from\n // that seed instead of decoding a packed child-secret-key structure.\n getPublicKey: (secretKey) => {\n const keys = keygen(secretKey);\n // keygen detaches its exported root; getPublicKey discards that half of the result.\n cleanBytes(keys.secretKey);\n return keys.publicKey;\n },\n keygen,\n expandDecapsulationKey,\n realSeedLen: rootSeedLen,\n };\n}\n// This generic function that combines multiple KEMs into single one\n/**\n * Combines multiple KEMs into one composite KEM.\n * @param realSeedLen - Positive input seed length expected by `expandSeed`, or `undefined` to use\n * the sum of component seed lengths. Callers remain responsible for choosing a security-appropriate\n * size.\n * @param realMsgLen - Positive shared-secret length returned by `combiner`, or `undefined` to use\n * the sum of component message lengths.\n * @param expandSeed - Seed expander used to derive per-KEM seeds.\n * @param combiner - Combines the per-KEM outputs into one shared secret.\n * @param kems - At least one KEM implementation. A construction advertised as hybrid normally\n * supplies two or more.\n * @returns Composite KEM.\n * @throws On wrong argument types. {@link TypeError}\n * @throws If there are no components or any required length resolves to zero. {@link RangeError}\n * @example\n * Combine multiple KEMs into one composite KEM.\n * ```ts\n * import { shake256 } from '@noble/hashes/sha3.js';\n * import { combineKEMS, expandSeedXof } from '@noble/post-quantum/hybrid.js';\n * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js';\n * const hybrid = combineKEMS(\n * 32,\n * 32,\n * expandSeedXof(shake256),\n * (_pk, _ct, sharedSecrets) => sharedSecrets[0],\n * ml_kem768,\n * ml_kem768\n * );\n * const { publicKey } = hybrid.keygen();\n * ```\n */\nexport function combineKEMS(realSeedLen, // how much bytes expandSeed expects\nrealMsgLen, // how much bytes combiner returns\nexpandSeed, combiner, ...kems) {\n if (realSeedLen !== undefined)\n positiveLength(realSeedLen, 'realSeedLen');\n if (realMsgLen !== undefined)\n positiveLength(realMsgLen, 'realMsgLen');\n if (typeof expandSeed !== 'function')\n throw new TypeError('\"expandSeed\" expected function, got type=' + typeof expandSeed);\n if (typeof combiner !== 'function')\n throw new TypeError('\"combiner\" expected function, got type=' + typeof combiner);\n const rawCombiner = combiner;\n const rawKems = kems;\n if (rawKems.length === 0)\n throw new RangeError('combineKEMS requires at least one KEM');\n for (let i = 0; i < rawKems.length; i++)\n validateKEM(rawKems[i], `kems[${i}]`);\n const keys = combineKeys(realSeedLen, expandSeed, ...rawKems);\n const ctCoder = splitLengths(rawKems, 'cipherText');\n const pkCoder = splitLengths(rawKems, 'publicKey');\n const msgCoder = splitLengths(rawKems, 'msg');\n const sharedSecretLen = positiveLength(realMsgLen === undefined ? msgCoder.bytesLen : realMsgLen, 'realMsgLen');\n const lengths = Object.freeze({\n ...keys.info.lengths,\n msg: sharedSecretLen,\n msgRand: msgCoder.bytesLen,\n cipherText: ctCoder.bytesLen,\n });\n const combine = (publicKeys, cipherTexts, sharedSecrets) => {\n const combined = rawCombiner(publicKeys, cipherTexts, sharedSecrets);\n try {\n return copyBytes(abytes(combined, sharedSecretLen, 'sharedSecret'));\n }\n catch (error) {\n if (isBytes(combined)) {\n // A combiner may return any callback argument. Public keys during encapsulation and\n // ciphertexts during decapsulation are views into caller-owned inputs, so wipe an invalid\n // byte result only when its range does not overlap either public argument vector. Child\n // shared-secret aliases are already wiped by the operation's outer finally block.\n const overlaps = (value) => combined.buffer === value.buffer &&\n combined.byteOffset < value.byteOffset + value.byteLength &&\n value.byteOffset < combined.byteOffset + combined.byteLength;\n const aliasesPublicInput = publicKeys.some(overlaps) ||\n cipherTexts.some(overlaps);\n if (!aliasesPublicInput)\n cleanBytes(combined);\n }\n throw error;\n }\n };\n return Object.freeze({\n lengths,\n getPublicKey: keys.getPublicKey,\n keygen: keys.keygen,\n encapsulate(pk, randomness = randomBytes(msgCoder.bytesLen)) {\n const pks = pkCoder.decode(pk);\n const rand = msgCoder.decode(randomness);\n const sharedSecret = [];\n const cipherText = [];\n try {\n for (let i = 0; i < rawKems.length; i++) {\n const enc = rawKems[i].encapsulate(pks[i], rand[i]);\n sharedSecret.push(enc.sharedSecret);\n cipherText.push(enc.cipherText);\n }\n // Validate and detach public ciphertexts before deriving a final secret from them. This\n // also ensures a malformed child cannot make us allocate and then strand a combined key.\n const encodedCipherText = ctCoder.encode(cipherText);\n return {\n // Detach the combiner result before cleanup: a caller-provided combiner may alias one of\n // the child sharedSecret buffers, and those child buffers are zeroized immediately below.\n sharedSecret: combine(pks, cipherText, sharedSecret),\n cipherText: encodedCipherText,\n };\n }\n finally {\n // Child encapsulation or combiner failures can happen after some components already\n // returned secret material; zeroize whatever was produced before propagating the error.\n cleanBytes(sharedSecret, cipherText);\n }\n },\n decapsulate(ct, seed) {\n const cts = ctCoder.decode(ct);\n const { publicKey, secretKey } = keys.expandDecapsulationKey(seed);\n const sharedSecret = [];\n try {\n // Child decapsulate() is inside the try: it can throw on an attacker-supplied ciphertext\n // (e.g. a low-order X25519 point), and by then the expanded child secret keys \u2014 plus any\n // child shared secrets already produced \u2014 are live and must still be wiped.\n for (let i = 0; i < rawKems.length; i++)\n sharedSecret.push(rawKems[i].decapsulate(cts[i], secretKey[i]));\n // Detach the decapsulation result before cleanup: the combiner may hand back one of the\n // child shared-secret buffers, and those temporary buffers are zeroized below.\n return combine(publicKey, cts, sharedSecret);\n }\n finally {\n // Decapsulation only needs the expanded child secret keys and child shared secrets for this\n // call; keep the caller/root seed intact, but wipe all derived material even on errors.\n cleanBytes(secretKey, sharedSecret);\n }\n },\n });\n}\n// There is no specs for this, but can be useful\n// realSeedLen: how much bytes expandSeed expects.\n/**\n * Combines multiple signers into one composite signer.\n * @param realSeedLen - Positive input seed length expected by `expandSeed`, or `undefined` to use\n * the sum of component seed lengths. Callers remain responsible for choosing a security-appropriate\n * size.\n * @param expandSeed - Seed expander used to derive per-signer seeds.\n * @param signers - At least one signer. A construction advertised as hybrid normally supplies two\n * or more.\n * @returns Composite signer.\n * @throws On wrong argument types. {@link TypeError}\n * @throws If there are no components or any required length resolves to zero. {@link RangeError}\n * @example\n * Combine multiple signers into one composite signer.\n * ```ts\n * import { shake256 } from '@noble/hashes/sha3.js';\n * import { combineSigners, expandSeedXof } from '@noble/post-quantum/hybrid.js';\n * import { ml_dsa44 } from '@noble/post-quantum/ml-dsa.js';\n * const hybrid = combineSigners(32, expandSeedXof(shake256), ml_dsa44, ml_dsa44);\n * const seed = new Uint8Array(hybrid.lengths.seed!).fill(1);\n * const { secretKey, publicKey } = hybrid.keygen(seed);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = hybrid.sign(msg, secretKey);\n * const isValid = hybrid.verify(sig, msg, publicKey);\n * ```\n */\nexport function combineSigners(realSeedLen, expandSeed, ...signers) {\n if (realSeedLen !== undefined)\n positiveLength(realSeedLen, 'realSeedLen');\n if (typeof expandSeed !== 'function')\n throw new TypeError('\"expandSeed\" expected function, got type=' + typeof expandSeed);\n const rawSigners = signers;\n if (rawSigners.length === 0)\n throw new RangeError('combineSigners requires at least one signer');\n for (let i = 0; i < rawSigners.length; i++)\n validateSigner(rawSigners[i], `signers[${i}]`);\n const keys = combineKeys(realSeedLen, expandSeed, ...rawSigners);\n const sigCoder = splitLengths(rawSigners, 'signature');\n const pkCoder = splitLengths(rawSigners, 'publicKey');\n return {\n lengths: { ...keys.info.lengths, signature: sigCoder.bytesLen, signRand: 0 },\n getPublicKey: keys.getPublicKey,\n keygen: keys.keygen,\n sign(message, seed, opts = {}) {\n opts = validateSigOpts(opts);\n // This generic wrapper intentionally keeps the composite signer contract to message + root\n // seed only. Per-signer opts like context or extraEntropy cannot be preserved uniformly\n // across mixed backends, so callers that need them must use the underlying signer directly.\n if (opts.extraEntropy !== undefined)\n throw new Error('combineSigners does not support extraEntropy; use the underlying signer directly');\n if (opts.context !== undefined)\n throw new Error('combineSigners does not support context; use the underlying signer directly');\n const { secretKey } = keys.expandDecapsulationKey(seed);\n try {\n const sigs = rawSigners.map((i, j) => i.sign(message, secretKey[j]));\n return sigCoder.encode(sigs);\n }\n finally {\n // Composite secret keys are root seeds; the per-signer child secret keys are temporary\n // expansion outputs and must not stay live after the combined signature is produced.\n cleanBytes(secretKey);\n }\n },\n /** Verify one combined signature.\n * Wrong-length aggregate signatures return `false` (matching ml-dsa / slh-dsa behavior), as\n * does any failing child verify. Throws on unsupported generic opts or malformed publicKey.\n */\n verify: (signature, message, publicKey, opts = {}) => {\n opts = validateVerOpts(opts);\n if (opts.context !== undefined)\n throw new Error('combineSigners does not support context; use the underlying signer directly');\n // Malformed signature *length* is a verification failure, not a thrown type error \u2014\n // consistent with ml-dsa / slh-dsa. Must run before sigCoder.decode, which throws.\n // Preserve TypeError for non-byte API arguments before treating byte lengths as invalid.\n abytes(signature, undefined, 'signature');\n // A signature failure must not hide malformed aggregate public-key bytes.\n const pks = pkCoder.decode(publicKey);\n if (signature.length !== sigCoder.bytesLen)\n return false;\n const sigs = sigCoder.decode(signature);\n for (let i = 0; i < rawSigners.length; i++) {\n if (!rawSigners[i].verify(sigs[i], message, pks[i]))\n return false;\n }\n return true;\n },\n };\n}\n/**\n * Builds a QSF hybrid KEM preset from a PQ KEM and an elliptic-curve KEM.\n * The combined shared-secret length follows `kdf.outputLen`; the built-in presets use 32-byte\n * SHA3-256 output, while custom `kdf` choices inherit their own digest size.\n * Its combiner hashes `ss0 || ss1 || ct1 || pk1 || label`, not the full\n * `(c1, c2, ek1, ek2)` example input shape from SP 800-227 equation (15).\n * Labels are encoded with `asciiToBytes()`, so non-ASCII labels are rejected.\n * @param label - Domain-separation label.\n * @param pqc - Post-quantum KEM.\n * @param curveKEM - Classical curve KEM.\n * @param xof - XOF used for seed expansion.\n * @param kdf - Hash used for the final combiner.\n * @returns Hybrid KEM.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Build a QSF hybrid KEM preset from a PQ KEM and an elliptic-curve KEM.\n * ```ts\n * import { p256 } from '@noble/curves/nist.js';\n * import { sha3_256, shake256 } from '@noble/hashes/sha3.js';\n * import { QSF, _ecdhKem } from '@noble/post-quantum/hybrid.js';\n * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js';\n * const kem = QSF('example', ml_kem768, _ecdhKem(p256, true), shake256, sha3_256);\n * const publicKeyLen = kem.lengths.publicKey;\n * ```\n */\nexport function QSF(label, pqc, curveKEM, xof, kdf) {\n astring(label, 'label');\n validateKEM(pqc, 'pqc');\n validateKEM(curveKEM, 'curveKEM');\n if (typeof xof !== 'function' || typeof xof.create !== 'function')\n throw new TypeError('\"xof\" expected hash function, got type=' + typeof xof);\n ahash(xof);\n if (typeof kdf !== 'function' || typeof kdf.create !== 'function')\n throw new TypeError('\"kdf\" expected hash function, got type=' + typeof kdf);\n ahash(kdf);\n return combineKEMS(32, kdf.outputLen, expandSeedXof(xof), (pk, ct, ss) => kdf(concatBytes(ss[0], ss[1], ct[1], pk[1], asciiToBytes(label))), pqc, curveKEM);\n}\n/** QSF preset combining ML-KEM-768 with P-256. */\nexport const QSF_ml_kem768_p256 = /* @__PURE__ */ (() => QSF('QSF-KEM(ML-KEM-768,P-256)-XOF(SHAKE256)-KDF(SHA3-256)', ml_kem768, _ecdhKem(p256, true), shake256, sha3_256))();\n/** QSF preset combining ML-KEM-1024 with P-384. */\nexport const QSF_ml_kem1024_p384 = /* @__PURE__ */ (() => QSF('QSF-KEM(ML-KEM-1024,P-384)-XOF(SHAKE256)-KDF(SHA3-256)', ml_kem1024, _ecdhKem(p384, true), shake256, sha3_256))();\n/**\n * Builds the \"KitchenSink\" hybrid KEM combiner.\n * The current builder always derives a fixed 32-byte output,\n * regardless of the hash's native output size.\n * Its HKDF extract step uses implicit zero salt with IKM\n * `hybrid_prk || ss0 || ss1 || ct0 || pk0 || ct1 || pk1 || label`.\n * Its HKDF expand step fixes `info` to `len || 'shared_secret' || ''`.\n * Labels are encoded with `asciiToBytes()`, so non-ASCII labels are rejected.\n * @param label - Domain-separation label.\n * @param pqc - Post-quantum KEM.\n * @param curveKEM - Classical curve KEM.\n * @param xof - XOF used for seed expansion.\n * @param hash - Hash used for HKDF extraction and expansion.\n * @returns Hybrid KEM.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Build the \"KitchenSink\" hybrid KEM combiner.\n * ```ts\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { shake256 } from '@noble/hashes/sha3.js';\n * import { createKitchenSink, _ecdhKem } from '@noble/post-quantum/hybrid.js';\n * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js';\n * import { x25519 } from '@noble/curves/ed25519.js';\n * const kem = createKitchenSink('example', ml_kem768, _ecdhKem(x25519), shake256, sha256);\n * const publicKeyLen = kem.lengths.publicKey;\n * ```\n */\nexport function createKitchenSink(label, pqc, curveKEM, xof, hash) {\n astring(label, 'label');\n validateKEM(pqc, 'pqc');\n validateKEM(curveKEM, 'curveKEM');\n if (typeof xof !== 'function' || typeof xof.create !== 'function')\n throw new TypeError('\"xof\" expected hash function, got type=' + typeof xof);\n ahash(xof);\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new TypeError('\"hash\" expected hash function, got type=' + typeof hash);\n ahash(hash);\n return combineKEMS(32, 32, expandSeedXof(xof), (pk, ct, ss) => {\n const preimage = concatBytes(ss[0], ss[1], ct[0], pk[0], ct[1], pk[1], asciiToBytes(label));\n const len = 32;\n const ikm = concatBytes(asciiToBytes('hybrid_prk'), preimage);\n const prk = extract(hash, ikm);\n const info = concatBytes(numberToBytesBE(len, 2), asciiToBytes('shared_secret'), asciiToBytes(''));\n const res = expand(hash, prk, info, len);\n cleanBytes(prk, info, ikm, preimage);\n return res;\n }, pqc, curveKEM);\n}\n// Internal alias only: this stays exactly `_ecdhKem(x25519)`\n// and inherits that wrapper's mutation/oracle behavior.\nconst x25519kem = /* @__PURE__ */ _ecdhKem(x25519);\n/** KitchenSink preset combining ML-KEM-768 with X25519.\n * Caller randomness splits into 32 ML-KEM coins plus a 32-byte X25519 ephemeral-secret seed.\n */\nexport const KitchenSink_ml_kem768_x25519 = /* @__PURE__ */ (() => createKitchenSink('KitchenSink-KEM(ML-KEM-768,X25519)-XOF(SHAKE256)-KDF(HKDF-SHA-256)', ml_kem768, x25519kem, shake256, sha256))();\n// Always X25519 and ML-KEM - 768, no point to export\n/** X25519 + ML-KEM-768 hybrid preset.\n * Uses the hard-coded domain-separation label `\\\\.//^\\\\` and hashes only `ct1 || pk1`\n * from the X25519 side in addition to the two component shared secrets.\n */\nexport const ml_kem768_x25519 = /* @__PURE__ */ (() => combineKEMS(32, 32, expandSeedXof(shake256), \n// Awesome label, so much escaping hell in a single line.\n(pk, ct, ss) => sha3_256(concatBytes(ss[0], ss[1], ct[1], pk[1], asciiToBytes('\\\\.//^\\\\'))), ml_kem768, x25519kem))();\n/**\n * Internal SEC 1-style KEM wrapper for NIST curves.\n * `nseed` is only the rejection-sampling byte budget for deriving one nonzero scalar:\n * current presets use `128` bytes for P-256 and `48` bytes for P-384.\n * `decapsulate()` returns the uncompressed shared point body `x || y` without the `0x04`\n * prefix, not the SEC 1 `x_P`-only primitive output, because current hybrid combiners hash\n * both coordinates.\n */\nfunction nistCurveKem(curve, scalarLen, elemLen, nseed) {\n const Fn = curve.Point.Fn;\n if (!Fn)\n throw new Error('no Point.Fn');\n // Scan scalar-sized windows until one decodes to a nonzero scalar in `[1, n-1]`; if every\n // window is zero or out of range, fail instead of silently reducing modulo `n`.\n function rejectionSampling(seed) {\n let sk;\n for (let start = 0, end = scalarLen;; start = end, end += scalarLen) {\n if (end > seed.length)\n throw new Error('rejection sampling failed');\n sk = Fn.fromBytes(seed.subarray(start, end), true);\n if (Fn.isValidNot0(sk))\n break;\n }\n const secretKey = Fn.toBytes(Fn.create(sk));\n const publicKey = curve.getPublicKey(secretKey, false);\n return { secretKey, publicKey };\n }\n // Standalone (not `this.decapsulate`) so encapsulate works even when methods are destructured.\n const decapsulate = (cipherText, secretKey) => {\n const full = curve.getSharedSecret(secretKey, cipherText);\n return full.subarray(1);\n };\n return {\n lengths: {\n secretKey: scalarLen,\n publicKey: elemLen,\n seed: nseed,\n msg: nseed,\n cipherText: elemLen,\n },\n keygen(seed = randomBytes(nseed)) {\n abytes(seed, nseed, 'seed');\n return rejectionSampling(seed);\n },\n getPublicKey(secretKey) {\n return curve.getPublicKey(secretKey, false);\n },\n encapsulate(publicKey, rand = randomBytes(nseed)) {\n abytes(rand, nseed, 'rand');\n let ek = undefined;\n try {\n ek = rejectionSampling(rand).secretKey;\n const sharedSecret = decapsulate(publicKey, ek);\n const cipherText = curve.getPublicKey(ek, false);\n return { sharedSecret, cipherText };\n }\n finally {\n // Rejection-sampled NIST-curve ephemeral secret keys are temporary encapsulation state and\n // must be wiped even if peer-key validation or shared-secret derivation throws.\n if (ek)\n cleanBytes(ek);\n }\n },\n decapsulate,\n };\n}\n/**\n * Internal ML-KEM + NIST-curve combiner.\n * `nseed` controls only the curve-side rejection-sampling budget; it is expanded from the\n * 32-byte root seed and is not itself part of the exported secret-key length.\n * The domain-separation `label` is used only in the final `sha3_256` combiner, not in\n * `shake256(seed, { dkLen: 64 + nseed })`,\n * and the combiner hashes `ss0 || ss1 || ct1 || pk1 || label`.\n */\nfunction concreteHybridKem(label, mlkem, curve, nseed) {\n const { secretKey: scalarLen, publicKeyUncompressed: elemLen } = curve.lengths;\n if (!scalarLen || !elemLen)\n throw new Error('wrong curve');\n const curveKem = nistCurveKem(curve, scalarLen, elemLen, nseed);\n const mlkemSeedLen = 64;\n const totalSeedLen = mlkemSeedLen + nseed;\n return combineKEMS(32, 32, (seed) => {\n abytes(seed, 32);\n // One SHAKE256 stream split by the seed coder as mlkemSeed (64) || curveSeed (nseed).\n // Returned directly: the previous concatBytes of two adjacent subarrays produced an\n // identical copy while leaving this original buffer unwiped; expandDecapsulationKey\n // wipes the returned buffer after the child seeds are copied out.\n return shake256(seed, { dkLen: totalSeedLen });\n }, (pk, ct, ss) => sha3_256(concatBytes(ss[0], ss[1], ct[1], pk[1], asciiToBytes(label))), mlkem, curveKem);\n}\n/** P-256 + ML-KEM-768 hybrid preset. */\nexport const ml_kem768_p256 = /* @__PURE__ */ (() => concreteHybridKem('MLKEM768-P256', ml_kem768, p256, 128))();\n/** P-384 + ML-KEM-1024 hybrid preset. */\nexport const ml_kem1024_p384 = /* @__PURE__ */ (() => concreteHybridKem('MLKEM1024-P384', ml_kem1024, p384, 48))();\n", "/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abytes as abytes_, anumber as anumber_, bytesToHex as bytesToHex_, concatBytes as concatBytes_, hexToBytes as hexToBytes_, isBytes as isBytes_, randomBytes as randomBytes_, } from '@noble/hashes/utils.js';\n/**\n * Validates that a value is an array, optionally validating each element.\n * @param item - Value to validate.\n * @param title - Label included in thrown errors.\n * @param inner - Optional per-element validator, called with the element and its label.\n * @returns The validated array.\n * @example\n * Validate an array of points before batch processing.\n *\n * ```ts\n * aarray([1n, 2n], 'scalars');\n * ```\n */\nexport function aarray(item, title, inner = () => { }) {\n if (!Array.isArray(item))\n throw new TypeError(`\"${title}\" expected array, got type=${typeof item}`);\n for (let i = 0; i < item.length; i++)\n inner(item[i], `${title}[${i}]`);\n return item;\n}\n/**\n * Validates that a value is a byte array.\n * @param value - Value to validate.\n * @param length - Optional exact byte length.\n * @param title - Optional field name.\n * @returns Original byte array.\n * @example\n * Reject non-byte input before passing data into curve code.\n *\n * ```ts\n * abytes(new Uint8Array(1));\n * ```\n */\nexport const abytes = (value, length, title) => abytes_(value, length, title);\n/**\n * Validates that a value is a non-negative safe integer.\n * @param n - Value to validate.\n * @param title - Optional field name.\n * @returns The validated number.\n * @example\n * Validate a numeric length before allocating buffers.\n *\n * ```ts\n * anumber(1);\n * ```\n */\nexport const anumber = anumber_;\n/**\n * Asserts something is a string.\n * @param value - Value to validate.\n * @param title - Label included in thrown errors.\n * @returns The validated string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a label string.\n *\n * ```ts\n * astring('example', 'label');\n * ```\n */\nexport function astring(value, title = '') {\n if (typeof value !== 'string') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(prefix + 'expected string, got type=' + typeof value);\n }\n return value;\n}\n/**\n * Asserts something is a plain object-ish value, not null or array.\n * @param value - Value to validate.\n * @param title - Label included in thrown errors.\n * @returns The validated object.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate an options object before checking fields.\n *\n * ```ts\n * aobject({ flag: true });\n * ```\n */\nexport function aobject(value, title = 'object') {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n throw new TypeError(title === 'object'\n ? 'expected valid options object'\n : `\"${title}\" expected object, got type=${typeof value}`);\n return value;\n}\n/**\n * Asserts something is a function.\n * @param value - Value to validate.\n * @param title - Label included in thrown errors.\n * @returns The validated function.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a required method before calling it.\n *\n * ```ts\n * afunction(() => true, 'predicate');\n * ```\n */\nexport function afunction(value, title) {\n if (typeof value !== 'function')\n throw new TypeError(`\"${title}\" is invalid: expected function, got ${typeof value}`);\n return value;\n}\n/**\n * Encodes bytes as lowercase hex.\n * @param bytes - Bytes to encode.\n * @returns Lowercase hex string.\n * @example\n * Serialize bytes as hex for logging or fixtures.\n *\n * ```ts\n * bytesToHex(Uint8Array.of(1, 2, 3));\n * ```\n */\nexport const bytesToHex = bytesToHex_;\n/**\n * Concatenates byte arrays.\n * @param arrays - Byte arrays to join.\n * @returns Concatenated bytes.\n * @example\n * Join domain-separated chunks into one buffer.\n *\n * ```ts\n * concatBytes(Uint8Array.of(1), Uint8Array.of(2));\n * ```\n */\nexport const concatBytes = (...arrays) => concatBytes_(...arrays);\n/**\n * Decodes lowercase or uppercase hex into bytes.\n * @param hex - Hex string to decode.\n * @returns Decoded bytes.\n * @example\n * Parse fixture hex into bytes before hashing.\n *\n * ```ts\n * hexToBytes('0102');\n * ```\n */\nexport const hexToBytes = (hex) => hexToBytes_(hex);\n/**\n * Checks whether a value is a Uint8Array.\n * @param a - Value to inspect.\n * @returns `true` when `a` is a Uint8Array.\n * @example\n * Branch on byte input before decoding it.\n *\n * ```ts\n * isBytes(new Uint8Array(1));\n * ```\n */\nexport const isBytes = isBytes_;\n/**\n * Reads random bytes from the platform CSPRNG.\n * @param bytesLength - Number of random bytes to read.\n * @returns Fresh random bytes.\n * @example\n * Generate a random seed for a keypair.\n *\n * ```ts\n * randomBytes(2);\n * ```\n */\nexport const randomBytes = (bytesLength) => randomBytes_(bytesLength);\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n// Shared error-message prefix builder. Only called on throw paths, so assert\n// success paths never pay for the string concatenation.\nconst atitle = (title) => (title ? `\"${title}\" ` : '');\n/**\n * Validates that a flag is boolean.\n * @param value - Value to validate.\n * @param title - Optional field name.\n * @returns Original value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Reject non-boolean option flags early.\n *\n * ```ts\n * abool(true);\n * ```\n */\nexport function abool(value, title = '') {\n if (typeof value !== 'boolean')\n throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);\n return value;\n}\n/**\n * Validates that a value is a non-negative bigint or safe integer.\n * @param n - Value to validate.\n * @returns The same validated value.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate one integer-like value before serializing it.\n *\n * ```ts\n * abignumber(1n);\n * ```\n */\nexport function abignumber(n) {\n if (typeof n === 'bigint') {\n if (!isPosBig(n))\n throw new RangeError('positive bigint expected, got ' + n);\n }\n else\n anumber(n);\n return n;\n}\n/**\n * Validates that a value is a safe integer.\n * @param value - Integer to validate.\n * @param title - Optional field name.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a window size before scalar arithmetic uses it.\n *\n * ```ts\n * asafenumber(1);\n * ```\n */\nexport function asafenumber(value, title = '') {\n if (typeof value !== 'number') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(prefix + 'expected number, got type=' + typeof value);\n }\n if (!Number.isSafeInteger(value)) {\n const prefix = title && `\"${title}\" `;\n throw new RangeError(prefix + 'expected safe integer, got ' + value);\n }\n}\n/**\n * Encodes a bigint into even-length big-endian hex.\n * The historical \"unpadded\" name only means \"no fixed-width field padding\"; odd-length hex still\n * gets one leading zero nibble so the result always represents whole bytes.\n * @param num - Number to encode.\n * @returns Big-endian hex string.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Encode a scalar into hex without a `0x` prefix.\n *\n * ```ts\n * numberToHexUnpadded(255n);\n * ```\n */\nexport function numberToHexUnpadded(num) {\n const hex = abignumber(num).toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\n/**\n * Parses a big-endian hex string into bigint.\n * Accepts odd-length hex through the native `BigInt('0x' + hex)` parser and currently surfaces the\n * same native `SyntaxError` for malformed hex instead of wrapping it in a library-specific error.\n * @param hex - Hex string without `0x`.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Parse a scalar from fixture hex.\n *\n * ```ts\n * hexToNumber('ff');\n * ```\n */\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n// BE: Big Endian, LE: Little Endian\n/**\n * Parses big-endian bytes into bigint.\n * @param bytes - Bytes in big-endian order.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Read a scalar encoded in network byte order.\n *\n * ```ts\n * bytesToNumberBE(Uint8Array.of(1, 0));\n * ```\n */\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex_(bytes));\n}\n/**\n * Parses little-endian bytes into bigint.\n * @param bytes - Bytes in little-endian order.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Read a scalar encoded in little-endian form.\n *\n * ```ts\n * bytesToNumberLE(Uint8Array.of(1, 0));\n * ```\n */\nexport function bytesToNumberLE(bytes) {\n return hexToNumber(bytesToHex_(copyBytes(abytes_(bytes)).reverse()));\n}\n/**\n * Encodes a bigint into fixed-length big-endian bytes.\n * @param n - Number to encode.\n * @param len - Output length in bytes. Must be greater than zero.\n * @returns Big-endian byte array.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If a documented runtime validation or state check fails. {@link Error}\n * @example\n * Serialize a scalar into a 32-byte field element.\n *\n * ```ts\n * numberToBytesBE(255n, 2);\n * ```\n */\nexport function numberToBytesBE(n, len) {\n anumber_(len);\n if (len === 0)\n throw new Error('zero output length is invalid');\n n = abignumber(n);\n const expectedLen = len * 2;\n const hex = n.toString(16);\n // Detect overflow before hex parsing so oversized values don't leak the shared odd-hex error.\n if (hex.length > expectedLen)\n throw new RangeError('number is too large');\n return hexToBytes_(hex.padStart(expectedLen, '0'));\n}\n/**\n * Encodes a bigint into fixed-length little-endian bytes.\n * @param n - Number to encode.\n * @param len - Output length in bytes.\n * @returns Little-endian byte array.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If a documented runtime validation or state check fails. {@link Error}\n * @example\n * Serialize a scalar for little-endian protocols.\n *\n * ```ts\n * numberToBytesLE(255n, 2);\n * ```\n */\nexport function numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\n/**\n * Encodes a bigint into variable-length big-endian bytes.\n * @param n - Number to encode.\n * @returns Variable-length big-endian bytes.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Serialize a bigint without fixed-width padding.\n *\n * ```ts\n * numberToVarBytesBE(255n);\n * ```\n */\nexport function numberToVarBytesBE(n) {\n return hexToBytes_(numberToHexUnpadded(abignumber(n)));\n}\n// Compares 2 u8a-s in kinda constant time\n/**\n * Compares two byte arrays in constant-ish time.\n * @param a - Left byte array.\n * @param b - Right byte array.\n * @returns `true` when bytes match.\n * @example\n * Compare two encoded points without early exit.\n *\n * ```ts\n * equalBytes(Uint8Array.of(1), Uint8Array.of(1));\n * ```\n */\nexport function equalBytes(a, b) {\n a = abytes(a);\n b = abytes(b);\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n * @param bytes - Bytes to copy.\n * @returns Detached copy.\n * @example\n * Make an isolated copy before mutating serialized bytes.\n *\n * ```ts\n * copyBytes(Uint8Array.of(1, 2, 3));\n * ```\n */\nexport function copyBytes(bytes) {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes));\n}\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as `TextEncoder` for ASCII or throws.\n * @param ascii - ASCII input text.\n * @returns Encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode an ASCII domain-separation tag.\n *\n * ```ts\n * asciiToBytes('ABC');\n * ```\n */\nexport function asciiToBytes(ascii) {\n if (typeof ascii !== 'string')\n throw new TypeError('ascii string expected, got ' + typeof ascii);\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new RangeError(`string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`);\n }\n return charCode;\n });\n}\n/**\n * Checks whether n is non-negative bigint. Historical name.\n * @param n - candidate value\n * @returns `true` when the value is bigint and 0 or larger\n * @example\n * Check a candidate scalar before range validation.\n *\n * ```ts\n * isPosBig(2n);\n * ```\n */\nexport function isPosBig(n) {\n return typeof n === 'bigint' && _0n <= n;\n}\n/**\n * Checks whether a bigint lies inside a half-open range.\n * @param n - Candidate value.\n * @param min - Inclusive lower bound.\n * @param max - Exclusive upper bound.\n * @returns `true` when the value is inside the range.\n * @example\n * Check whether a candidate scalar fits the field order.\n *\n * ```ts\n * inRange(2n, 1n, 3n);\n * ```\n */\nexport function inRange(n, min, max) {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n/**\n * Asserts `min <= n < max`. NOTE: upper bound is exclusive.\n * @param title - Value label for error messages.\n * @param n - Candidate value.\n * @param min - Inclusive lower bound.\n * @param max - Exclusive upper bound.\n * Wrong-type inputs are not separated from out-of-range values here: they still flow through the\n * shared `RangeError` path because this is only a throwing wrapper around `inRange(...)`.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Assert that a bigint stays within one half-open range.\n *\n * ```ts\n * aInRange('x', 2n, 1n, 256n);\n * ```\n */\nexport function aInRange(title, n, min, max) {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new RangeError('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n// Bit operations\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n * @param n - Value to inspect.\n * @returns Bit length.\n * @throws If the value is negative. {@link Error}\n * @example\n * Measure the bit length of a scalar before serialization.\n *\n * ```ts\n * bitLen(8n);\n * ```\n */\nexport function bitLen(n) {\n // Size callers in this repo only use non-negative orders / scalars, so negative inputs are a\n // contract bug and must not silently collapse to zero bits.\n if (n < _0n)\n throw new Error('expected non-negative bigint, got ' + n);\n // Native radix conversion beats a shift loop at every size, and the loop is quadratic in bits.\n return n === _0n ? 0 : n.toString(2).length;\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 * @param n - Source value.\n * @param pos - Bit position. Negative positions are passed through to raw\n * bigint shift semantics; because the mask is built as `1n << pos`,\n * they currently collapse to `0n` and make the helper a no-op.\n * @returns Bit as bigint.\n * @example\n * Gets single bit at position.\n *\n * ```ts\n * bitGet(5n, 0);\n * ```\n */\nexport function bitGet(n, pos) {\n if (typeof n !== 'bigint')\n throw new TypeError('\"n\" expected bigint, got type=' + typeof n);\n asafenumber(pos, 'pos');\n return (n >> BigInt(pos)) & _1n;\n}\n/**\n * Sets single bit at position.\n * @param n - Source value.\n * @param pos - Bit position. Negative positions are passed through to raw bigint shift semantics,\n * so they currently behave like left shifts.\n * @param value - Whether the bit should be set.\n * @returns Updated bigint.\n * @example\n * Sets single bit at position.\n *\n * ```ts\n * bitSet(0n, 1, true);\n * ```\n */\nexport function bitSet(n, pos, value) {\n if (typeof n !== 'bigint')\n throw new TypeError('\"n\" expected bigint, got type=' + typeof n);\n asafenumber(pos, 'pos');\n abool(value, 'value');\n const mask = _1n << BigInt(pos);\n // Clearing needs AND-not here; OR with zero leaves an already-set bit untouched.\n return value ? n | mask : n & ~mask;\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 * @param n - Number of bits. Negative widths are currently passed through to raw bigint shift\n * semantics and therefore produce `-1n`.\n * @returns Bitmask value.\n * @example\n * Calculate mask for N bits.\n *\n * ```ts\n * bitMask(4);\n * ```\n */\nexport const bitMask = (n) => {\n asafenumber(n, 'n');\n return (_1n << BigInt(n)) - _1n;\n};\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @param hashLen - Hash output size in bytes. Callers are expected to pass a positive length; `0`\n * is not rejected here and would make the internal generate loop non-progressing.\n * @param qByteLen - Requested output size in bytes. Callers are expected to pass a positive length.\n * @param hmacFn - HMAC implementation.\n * @returns Function that will call DRBG until the predicate returns anything\n * other than `undefined`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Build a deterministic nonce generator for RFC6979-style signing.\n *\n * ```ts\n * import { createHmacDrbg } from '@noble/curves/utils.js';\n * import { hmac } from '@noble/hashes/hmac.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hmacFn = (key: Uint8Array, msg: Uint8Array) => hmac(sha256, key, msg);\n * const drbg = createHmacDrbg(32, 32, hmacFn);\n * const seed = new Uint8Array(32);\n * drbg(seed, (bytes) => bytes);\n * ```\n */\nexport function createHmacDrbg(hashLen, qByteLen, hmacFn) {\n anumber_(hashLen, 'hashLen');\n anumber_(qByteLen, 'qByteLen');\n if (typeof hmacFn !== 'function')\n throw new TypeError('hmacFn must be a function');\n // creates Uint8Array\n const u8n = (len) => new Uint8Array(len);\n const NULL = Uint8Array.of();\n const byte0 = Uint8Array.of(0x00);\n const byte1 = Uint8Array.of(0x01);\n const _maxDrbgIters = 1000;\n // Step B, Step C: set hashLen to 8*ceil(hlen/8).\n // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 signatures.\n let v = u8n(hashLen);\n // Steps B and C of RFC6979 3.2.\n let k = u8n(hashLen);\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 // hmac(k)(v, ...values)\n const h = (...msgs) => hmacFn(k, concatBytes(v, ...msgs));\n const reseed = (seed = NULL) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(byte0, seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0)\n return;\n k = h(byte1, 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++ >= _maxDrbgIters)\n throw new Error('drbg: tried max amount of iterations');\n let len = 0;\n const out = [];\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, pred) => {\n reset();\n reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until the predicate accepts a candidate.\n // Falsy values like 0 are valid outputs.\n while ((res = pred(gen())) === undefined)\n reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n/**\n * Validates declared required and optional field types on a plain object.\n * Extra keys are intentionally ignored because many callers validate only the subset they use from\n * richer option bags or runtime objects.\n * This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct\n * one-line guards such as `aobject()`, `afunction()`, `abool()`, or `asafenumber()` instead.\n * @param object - Object to validate.\n * @param fields - Required field types.\n * @param optFields - Optional field types.\n * @param title - Object label included in thrown errors.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Check user options before building a curve helper.\n *\n * ```ts\n * validateObject({ flag: true }, { flag: 'boolean' });\n * ```\n */\nexport function validateObject(object, fields = {}, optFields = {}, title = 'object') {\n aobject(object, title);\n aobject(fields, 'fields');\n aobject(optFields, 'optFields');\n function checkField(fieldName, expectedType, isOpt) {\n const label = title === 'object' ? `param \"${String(fieldName)}\"` : `\"${title}.${String(fieldName)}\"`;\n // Config fields must be explicit own properties. Optional inherited values are rejected too\n // because callers keep reading the same options object after validation.\n const val = object[fieldName];\n // Runtime objects such as Field instances intentionally satisfy required method slots\n // via their shared prototype.\n if (!Object.hasOwn(object, fieldName) &&\n (isOpt ? val !== undefined : expectedType !== 'function')) {\n throw new TypeError(`${label} is invalid: expected own property`);\n }\n if (isOpt && val === undefined)\n return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);\n }\n const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n}\n/**\n * Throws not implemented error.\n * @returns Never returns.\n * @throws If the unfinished code path is reached. {@link Error}\n * @example\n * Surface the placeholder error from an unfinished code path.\n *\n * ```ts\n * try {\n * notImplemented();\n * } catch {}\n * ```\n */\nexport const notImplemented = () => {\n throw new Error('not implemented');\n};\n", "/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { aarray, abool, abytes, afunction, anumber, aobject, asafenumber, bitLen, bytesToNumberBE, bytesToNumberLE, numberToBytesBE, numberToBytesLE, } from \"../utils.js\";\n// Numbers aren't used in x25519 / x448 builds\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2);\n// prettier-ignore\nconst _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5);\n// prettier-ignore\nconst _7n = /* @__PURE__ */ BigInt(7), _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9);\nconst _15n = /* @__PURE__ */ BigInt(15), _16n = /* @__PURE__ */ BigInt(16);\n// 2^64: exponents below this use plain square-and-multiply in pow()/FpPow(); the windowed path's\n// table build (14 multiplications) only pays off for longer exponents (break-even ~50 bits).\nconst POW_WINDOWED_MIN = /* @__PURE__ */ BigInt('0x10000000000000000');\n/**\n * @param a - Dividend value.\n * @param b - Positive modulus.\n * @returns Reduced value in `[0, b)` only when `b` is positive.\n * @throws If the modulus is not positive. {@link Error}\n * @example\n * Normalize a bigint into one field residue.\n *\n * ```ts\n * mod(-1n, 5n);\n * ```\n */\nexport function mod(a, b) {\n if (b <= _0n)\n throw new Error('mod: expected positive modulus, got ' + b);\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to a power with modular reduction.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * Low-level helper: callers that need canonical residues must pass a valid `num` for the chosen\n * modulus instead of relying on the `power===0/1` fast paths to normalize it.\n * @param num - Base value.\n * @param power - Exponent value.\n * @param modulo - Reduction modulus.\n * @returns Modular exponentiation result.\n * @throws If the modulus or exponent is invalid. {@link Error}\n * @example\n * Raise one bigint to a modular power.\n *\n * ```ts\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n * ```\n */\nexport function pow(num, power, modulo) {\n if (modulo <= _1n)\n throw new Error('pow: expected modulus > 1, got ' + modulo);\n // Non-bigint exponents coerce every comparison below to false and would silently return 1.\n if (typeof power !== 'bigint')\n throw new TypeError('invalid exponent: expected bigint, got ' + typeof power);\n if (power < _0n)\n throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n)\n return _1n;\n if (power === _1n)\n return num;\n let d = num % modulo;\n if (d < _0n)\n d += modulo;\n // Control flow in both branches below depends only on the exponent, never on `num` \u2014 invertCt()\n // relies on that for its (public-exponent) secret-independence guarantee.\n if (power < POW_WINDOWED_MIN) {\n // Square-and-multiply: cheaper than the windowed path for short exponents.\n let p = _1n;\n while (power > _0n) {\n if (power & _1n)\n p = (p * d) % modulo;\n d = (d * d) % modulo;\n power >>= _1n;\n }\n return p;\n }\n // Fixed 4-bit windows, MSB-first: a 14-multiplication table drops per-window cost to <1\n // multiplication (vs ~2 per window for square-and-multiply), ~25-30% faster for the dense\n // 256-bit exponents of sqrt / Legendre / invertCt.\n const digits = [];\n while (power > _0n) {\n digits.push(Number(power & _15n));\n power >>= _4n;\n }\n const table = new Array(16);\n table[0] = _1n;\n table[1] = d;\n for (let i = 2; i < 16; i++)\n table[i] = (table[i - 1] * d) % modulo;\n let p = table[digits[digits.length - 1]]; // top digit is nonzero: the loop above stops on 0\n for (let w = digits.length - 2; w >= 0; w--) {\n p = (p * p) % modulo;\n p = (p * p) % modulo;\n p = (p * p) % modulo;\n p = (p * p) % modulo;\n const digit = digits[w];\n if (digit !== 0)\n p = (p * table[digit]) % modulo;\n }\n return p;\n}\n/**\n * Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)`.\n * Low-level helper: callers that need canonical residues must pass a valid `x` for the chosen\n * modulus; the `power===0` fast path intentionally returns the input unchanged.\n * @param x - Base value.\n * @param power - Number of squarings.\n * @param modulo - Reduction modulus.\n * @returns Repeated-squaring result.\n * @throws If the exponent is negative. {@link Error}\n * @example\n * Apply repeated squaring inside one field.\n *\n * ```ts\n * pow2(3n, 2n, 11n);\n * ```\n */\nexport function pow2(x, power, modulo) {\n if (modulo <= _1n)\n throw new Error('pow2: expected modulus > 1, got ' + modulo);\n if (power < _0n)\n throw new Error('pow2: expected non-negative exponent, got ' + power);\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.\n * Implemented using the {@link https://brilliant.org/wiki/extended-euclidean-algorithm/ | extended Euclidean algorithm}.\n * @param number - Value to invert.\n * @param modulo - Modulus greater than 1.\n * @returns Multiplicative inverse.\n * @throws If the modulus is invalid or the inverse does not exist. {@link Error}\n * @example\n * Compute one modular inverse with the extended Euclidean algorithm.\n *\n * ```ts\n * invert(3n, 11n);\n * ```\n */\nexport function invert(number, modulo) {\n if (number === _0n)\n throw new Error('invert: expected non-zero number');\n // modulo = 1 is the zero ring: gcd(x, 1) = 1 makes the loop below \"succeed\" and return the\n // useless inverse 0. Reject it like pow() and invertCt() do.\n if (modulo <= _1n)\n throw new Error('invert: expected modulus > 1, got ' + modulo);\n // This is variable-time: the loop count depends on `number`. For a secret-independent\n // (Fermat) alternative over a prime modulus, see {@link invertCt} (~4x slower).\n let a = mod(number, modulo);\n let b = modulo;\n // Only the B\u00E9zout coefficient of `number` (x/u chain) is tracked; the coefficient of `modulo`\n // never affects the output, so it is not computed.\n // prettier-ignore\n let x = _0n, u = _1n;\n while (a !== _0n) {\n const q = b / a;\n const r = b - a * q;\n const m = x - u * q;\n // prettier-ignore\n b = a, a = r, x = u, u = m;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n/**\n * Inverses number over modulo using Fermat's little theorem: `a^(p-2) \u2261 a\u207B\u00B9 (mod p)`.\n *\n * Unlike {@link invert} (extended Euclidean), the exponent `p-2` is a public constant, so the\n * underlying square-and-multiply has the same control flow for every secret `a`: there is no\n * data-dependent branching or loop count that could leak `a` through timing (e.g. Minerva-style\n * ECDSA nonce-inversion attacks). This is only \"algorithmically\" constant-time \u2014 JS bigint\n * multiplication/reduction is still value-dependent \u2014 and it is roughly 4x slower than\n * {@link invert}.\n *\n * REQUIRES a prime modulus; Fermat's theorem does not hold otherwise. The result is verified to be\n * a real inverse, so a non-prime modulus (or a non-invertible input) fails closed with an error\n * instead of returning a wrong value.\n * @param a - Value to invert.\n * @param prime - Prime modulus.\n * @returns Multiplicative inverse in `[1, prime)`.\n * @throws If the modulus is below 2, the input reduces to zero, or the inverse does not exist.\n * {@link Error}\n * @example\n * Compute one modular inverse without secret-dependent branching.\n *\n * ```ts\n * invertCt(3n, 11n); // 4n, since 3 * 4 = 12 \u2261 1 (mod 11)\n * ```\n */\nexport function invertCt(a, prime) {\n if (prime <= _1n)\n throw new Error('invertCt: expected prime modulus > 1, got ' + prime);\n const an = mod(a, prime);\n if (an === _0n)\n throw new Error('invertCt: expected non-zero number');\n // Exponent (prime - 2) is public, so FpPow's square-and-multiply is secret-independent.\n const inverse = pow(an, prime - _2n, prime);\n // O(1) safety net: verifies the inverse and rejects composite moduli where a^(p-2) is not one.\n if (mod(an * inverse, prime) !== _1n)\n throw new Error('invertCt: does not exist');\n return inverse;\n}\nfunction assertIsSquare(Fp, root, n) {\n const F = Fp;\n if (!F.eql(F.sqr(root), n))\n throw new Error('Cannot find square root');\n}\n// The Legendre symbol and every sqrt variant here are only defined over an odd (prime) modulus.\n// An even ORDER makes their integer divisions \u2014 (p-1)/2, (p+1)/4, (p-5)/8, (p+7)/16 \u2014 truncate and\n// silently return a wrong result, so reject it explicitly at the entry points instead. This is a\n// cheap necessary-condition check, not a primality test (composite odd moduli are caught later by\n// the Legendre-result / assertIsSquare checks).\nfunction aoddModulus(order, fnName) {\n if ((order & _1n) === _0n)\n throw new Error(fnName + ': expected odd modulus, got ' + order);\n}\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4(Fp, n) {\n const F = Fp;\n const p1div4 = (F.ORDER + _1n) / _4n;\n const root = F.pow(n, p1div4);\n assertIsSquare(F, root, n);\n return root;\n}\n// Equivalent `q = 5 (mod 8)` square-root formula (Atkin-style), not the RFC Appendix I.2 CMOV\n// pseudocode verbatim.\nfunction sqrt5mod8(Fp, n) {\n const F = Fp;\n const p5div8 = (F.ORDER - _5n) / _8n;\n const n2 = F.mul(n, _2n);\n const v = F.pow(n2, p5div8);\n const nv = F.mul(n, v);\n const i = F.mul(F.mul(nv, _2n), v);\n const root = F.mul(nv, F.sub(i, F.ONE));\n assertIsSquare(F, root, n);\n return root;\n}\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P) {\n const Fp_ = Field(P);\n const tn = tonelliShanks(P);\n const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n const c3 = tn(Fp_, Fp_.neg(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 return ((Fp, n) => {\n const F = Fp;\n let tv1 = F.pow(n, c4); // 1. tv1 = x^c4\n let tv2 = F.mul(tv1, c1); // 2. tv2 = c1 * tv1\n const tv3 = F.mul(tv1, c2); // 3. tv3 = c2 * tv1\n const tv4 = F.mul(tv1, c3); // 4. tv4 = c3 * tv1\n const e1 = F.eql(F.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n const e2 = F.eql(F.sqr(tv3), n); // 6. e2 = (tv3^2) == x\n tv1 = F.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n tv2 = F.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n const e3 = F.eql(F.sqr(tv2), n); // 9. e3 = (tv2^2) == x\n const root = F.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2\n assertIsSquare(F, root, n);\n return root;\n });\n}\n/**\n * Tonelli-Shanks square root search algorithm.\n * This implementation is variable-time: it searches data-dependently for the first non-residue `Z`\n * and for the smallest `i` in the main loop, unlike RFC 9380 Appendix I.4's constant-time shape.\n * 1. {@link https://eprint.iacr.org/2012/685.pdf | eprint 2012/685}, page 12\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * @param P - field order\n * @returns function that takes field Fp (created from P) and number n\n * @throws If the field is too small, non-prime, or the square root does not exist. {@link Error}\n * @example\n * Construct a square-root helper for primes that need Tonelli-Shanks.\n *\n * ```ts\n * import { Field, tonelliShanks } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const sqrt = tonelliShanks(17n)(Fp, 4n);\n * ```\n */\nexport function tonelliShanks(P) {\n // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n)\n throw new Error('sqrt is not defined for small field');\n aoddModulus(P, 'tonelliShanks');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000)\n throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1)\n return sqrt3mod4;\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp, n) {\n const F = Fp;\n if (F.is0(n))\n return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(F, n) !== 1)\n throw new Error('Cannot find square root');\n // Initialize variables for the main loop\n let M = S;\n let c = F.mul(F.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = F.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = F.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n // Main loop\n // while t != 1\n while (!F.eql(t, F.ONE)) {\n // Unreachable over a genuine field (no zero divisors; n=0 already returned above). A zero t\n // means composite ORDER, where a fabricated root would be wrong: fail closed instead.\n if (F.is0(t))\n throw new Error('Cannot find square root: probably non-prime P');\n let i = 1;\n // Find the smallest i >= 1 such that t^(2^i) \u2261 1 (mod P)\n let t_tmp = F.sqr(t); // t^(2^1)\n while (!F.eql(t_tmp, F.ONE)) {\n i++;\n t_tmp = F.sqr(t_tmp); // t^(2^2)...\n if (i === M)\n throw new Error('Cannot find square root');\n }\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = F.pow(c, exponent); // b = 2^(M - i - 1)\n // Update variables\n M = i;\n c = F.sqr(b); // c = b^2\n t = F.mul(t, c); // t = (t * b^2)\n R = F.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P \u2261 3 (mod 4)\n * 2. P \u2261 5 (mod 8)\n * 3. P \u2261 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * 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 choose a root by oddness\n * (used for hash-to-curve).\n * @param P - Field order.\n * @returns Square-root helper. The generic fallback inherits Tonelli-Shanks' variable-time\n * behavior and this selector assumes prime-field-style integer moduli.\n * @throws If the field is unsupported or the square root does not exist. {@link Error}\n * @example\n * Choose the square-root helper appropriate for one field modulus.\n *\n * ```ts\n * import { Field, FpSqrt } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const sqrt = FpSqrt(17n)(Fp, 4n);\n * ```\n */\nexport function FpSqrt(P) {\n aoddModulus(P, 'Fp.sqrt');\n // P \u2261 3 (mod 4) => \u221An = n^((P+1)/4)\n if (P % _4n === _3n)\n return sqrt3mod4;\n // P \u2261 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n)\n return sqrt5mod8;\n // P \u2261 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n if (P % _16n === _9n)\n return sqrt9mod16(P);\n // Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n/**\n * @param num - Value to inspect.\n * @param modulo - Field modulus.\n * @returns `true` when the least-significant little-endian bit is set.\n * @throws If the modulus is invalid for `mod(...)`. {@link Error}\n * @example\n * Inspect the low bit used by little-endian sign conventions.\n *\n * ```ts\n * isNegativeLE(3n, 11n);\n * ```\n */\nexport const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;\n// prettier-ignore\n// Arithmetic-only subset checked by validateField(). This is intentionally not the full runtime\n// IField contract: helpers like `isValidNot0`, `invertBatch`, `toBytes`, `fromBytes`, `cmov`, and\n// field-specific extras like `isOdd` are left to the callers that actually need them.\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n];\n/**\n * @param field - Field implementation.\n * @returns Validated field. This only checks the arithmetic subset needed by generic helpers; it\n * does not guarantee full runtime-method coverage for serialization, batching, `cmov`, or\n * field-specific extras beyond positive `BYTES` / `BITS`.\n * @throws If the field shape or numeric metadata are invalid. {@link Error}\n * @example\n * Check that a field implementation exposes the operations curve code expects.\n *\n * ```ts\n * import { Field, validateField } from '@noble/curves/abstract/modular.js';\n * const Fp = validateField(Field(17n));\n * ```\n */\nexport function validateField(field) {\n aobject(field, 'field');\n if (typeof field.ORDER !== 'bigint')\n throw new TypeError('param \"ORDER\" is invalid: expected bigint, got ' + typeof field.ORDER);\n // Runtime field implementations must expose real integer byte/bit sizes; fractional / NaN /\n // infinite metadata breaks encoders and caches.\n asafenumber(field.BYTES, 'BYTES');\n asafenumber(field.BITS, 'BITS');\n for (const name of FIELD_FIELDS)\n afunction(field[name], 'field.' + name);\n // Runtime field implementations must expose positive byte/bit sizes; zero leaks through the\n // numeric shape checks above but still breaks encoding helpers and cached-length assumptions.\n if (field.BYTES < 1 || field.BITS < 1)\n throw new Error('invalid field: expected BYTES/BITS > 0');\n if (field.ORDER <= _1n)\n throw new Error('invalid field: expected ORDER > 1, got ' + field.ORDER);\n return field;\n}\n// Generic field functions\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @param Fp - Field implementation.\n * @param num - Base value.\n * @param power - Exponent value.\n * @returns Powered field element.\n * @throws If the exponent is negative. {@link Error}\n * @example\n * Raise one field element to a public exponent.\n *\n * ```ts\n * import { Field, FpPow } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const x = FpPow(Fp, 3n, 5n);\n * ```\n */\nexport function FpPow(Fp, num, power) {\n validateField(Fp);\n const F = Fp;\n // Non-bigint exponents (e.g. an accidental field element) coerce every comparison below to\n // false and would silently return ONE.\n if (typeof power !== 'bigint')\n throw new TypeError('invalid exponent: expected bigint, got ' + typeof power);\n if (power < _0n)\n throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n)\n return F.ONE;\n if (power === _1n)\n return num;\n if (power < POW_WINDOWED_MIN) {\n // Square-and-multiply: cheaper than the windowed path for short exponents (e.g. poseidon\n // sbox x^5), which would waste the 14-multiplication table build.\n let p = F.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n)\n p = F.mul(p, d);\n d = F.sqr(d);\n power >>= _1n;\n }\n return p;\n }\n // Fixed 4-bit windows, MSB-first \u2014 same shape as pow() above, over generic field ops.\n // Speeds up dense long exponents (extension-field sqrt / Legendre, e.g. Fp2 decompression).\n const digits = [];\n while (power > _0n) {\n digits.push(Number(power & _15n));\n power >>= _4n;\n }\n const table = new Array(16);\n table[0] = F.ONE;\n table[1] = num;\n for (let i = 2; i < 16; i++)\n table[i] = F.mul(table[i - 1], num);\n let p = table[digits[digits.length - 1]]; // top digit is nonzero: the loop above stops on 0\n for (let w = digits.length - 2; w >= 0; w--) {\n p = F.sqr(F.sqr(F.sqr(F.sqr(p))));\n const digit = digits[w];\n if (digit !== 0)\n p = F.mul(p, table[digit]);\n }\n return p;\n}\nexport function FpInvertBatch(Fp, nums, passZero = false) {\n validateField(Fp);\n aarray(nums, 'nums');\n abool(passZero, 'passZero');\n const F = Fp;\n const inverted = new Array(nums.length).fill(passZero ? F.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (F.is0(num))\n return acc;\n inverted[i] = acc;\n return F.mul(acc, num);\n }, F.ONE);\n // Invert last element\n const invertedAcc = F.inv(multipliedAcc);\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))\n return acc;\n // Non-zero `num` means the forward pass already stored a defined prefix product at index i.\n inverted[i] = F.mul(acc, inverted[i]);\n return F.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n/**\n * @param Fp - Field implementation.\n * @param lhs - Dividend value.\n * @param rhs - Divisor value.\n * @returns Division result.\n * @throws If the divisor is non-invertible. {@link Error}\n * @example\n * Divide one field element by another.\n *\n * ```ts\n * import { Field, FpDiv } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const x = FpDiv(Fp, 6n, 3n);\n * ```\n */\nexport function FpDiv(Fp, lhs, rhs) {\n validateField(Fp);\n const F = Fp;\n return F.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, F.ORDER) : F.inv(rhs));\n}\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\n * * (a | p) \u2261 1 if a is a square (mod p), quadratic residue\n * * (a | p) \u2261 -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) \u2261 0 if a \u2261 0 (mod p)\n * @param Fp - Field implementation.\n * @param n - Value to inspect.\n * @returns Legendre symbol.\n * @throws If the powered value does not match a valid Legendre symbol. {@link Error}\n * @example\n * Compute the Legendre symbol of one field element.\n *\n * ```ts\n * import { Field, FpLegendre } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const symbol = FpLegendre(Fp, 4n);\n * ```\n */\nexport function FpLegendre(Fp, n) {\n validateField(Fp);\n const F = Fp;\n aoddModulus(F.ORDER, 'FpLegendre');\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (F.ORDER - _1n) / _2n;\n const powered = F.pow(n, p1mod2);\n const yes = F.eql(powered, F.ONE);\n const zero = F.eql(powered, F.ZERO);\n const no = F.eql(powered, F.neg(F.ONE));\n if (!yes && !zero && !no)\n throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n/**\n * @param Fp - Field implementation.\n * @param n - Value to inspect.\n * @returns `true` when `Fp.sqrt(n)` exists. This includes `0`, even though strict \"quadratic\n * residue\" terminology often reserves that name for the non-zero square class.\n * @throws If the field returns an invalid Legendre symbol value. {@link Error}\n * @example\n * Check whether one field element has a square root in the field.\n *\n * ```ts\n * import { Field, FpIsSquare } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const isSquare = FpIsSquare(Fp, 4n);\n * ```\n */\nexport function FpIsSquare(Fp, n) {\n const l = FpLegendre(Fp, n);\n // Zero is a square too: 0 = 0^2, and Fp.sqrt(0) already returns 0.\n return l !== -1;\n}\n/**\n * @param n - Curve order. Callers are expected to pass a positive order.\n * @param nBitLength - Optional cached bit length. Callers are expected to pass a positive cached\n * value when overriding the derived bit length.\n * @returns Byte and bit lengths.\n * @throws If the order or cached bit length is invalid. {@link Error}\n * @example\n * Measure the encoding sizes needed for one modulus.\n *\n * ```ts\n * nLength(255n);\n * ```\n */\nexport function nLength(n, nBitLength) {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined)\n anumber(nBitLength);\n if (n <= _0n)\n throw new Error('invalid n length: expected positive n, got ' + n);\n if (nBitLength !== undefined && nBitLength < 1)\n throw new Error('invalid n length: expected positive bit length, got ' + nBitLength);\n const bits = bitLen(n);\n // Cached bit lengths smaller than ORDER would truncate serialized scalars/elements and poison\n // any math that relies on the derived field metadata.\n if (nBitLength !== undefined && nBitLength < bits)\n throw new Error(`invalid n length: expected nBitLength (${nBitLength}) >= bitLen(n) (${bits})`);\n const _nBitLength = nBitLength !== undefined ? nBitLength : bits;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n// Keep the lazy sqrt cache off-instance so Field(...) can return a frozen object. Otherwise the\n// cached helper write would keep the field surface externally mutable.\nconst FIELD_SQRT = new WeakMap();\nclass _Field {\n ORDER;\n BITS;\n BYTES;\n isLE;\n ZERO = _0n;\n ONE = _1n;\n _lengths;\n _mod;\n constructor(ORDER, opts = {}) {\n // ORDER <= 1 is degenerate: ONE would not be a valid field element and helpers like pow/inv\n // would stop modeling field arithmetic.\n if (ORDER <= _1n)\n throw new Error('invalid field: expected ORDER > 1, got ' + ORDER);\n let _nbitLength = undefined;\n this.isLE = false;\n if (opts != null && typeof opts === 'object') {\n // Cached bit lengths are trusted here and should already be positive / consistent with ORDER.\n if (typeof opts.BITS === 'number')\n _nbitLength = opts.BITS;\n if (typeof opts.sqrt === 'function')\n // `_Field.prototype` is frozen below, so custom sqrt hooks must become own properties\n // explicitly instead of relying on writable prototype shadowing via assignment.\n Object.defineProperty(this, 'sqrt', { value: opts.sqrt, enumerable: true });\n if (typeof opts.isLE === 'boolean')\n this.isLE = opts.isLE;\n if (opts.allowedLengths)\n this._lengths = Object.freeze(opts.allowedLengths.slice());\n if (typeof opts.modFromBytes === 'boolean')\n this._mod = opts.modFromBytes;\n }\n const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);\n if (nByteLength > 2048)\n throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n this.ORDER = ORDER;\n this.BITS = nBitLength;\n this.BYTES = nByteLength;\n Object.freeze(this);\n }\n create(num) {\n return mod(num, this.ORDER);\n }\n isValid(num) {\n if (typeof num !== 'bigint')\n throw new TypeError('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < this.ORDER; // 0 is valid element, but it's not invertible\n }\n is0(num) {\n return num === _0n;\n }\n // is valid and invertible\n isValidNot0(num) {\n return !this.is0(num) && this.isValid(num);\n }\n isOdd(num) {\n return (num & _1n) === _1n;\n }\n neg(num) {\n return mod(-num, this.ORDER);\n }\n eql(lhs, rhs) {\n return lhs === rhs;\n }\n sqr(num) {\n return mod(num * num, this.ORDER);\n }\n add(lhs, rhs) {\n return mod(lhs + rhs, this.ORDER);\n }\n sub(lhs, rhs) {\n return mod(lhs - rhs, this.ORDER);\n }\n mul(lhs, rhs) {\n return mod(lhs * rhs, this.ORDER);\n }\n pow(num, power) {\n return pow(num, power, this.ORDER);\n }\n div(lhs, rhs) {\n return mod(lhs * invert(rhs, this.ORDER), this.ORDER);\n }\n // Same as above, but doesn't normalize\n sqrN(num) {\n return num * num;\n }\n addN(lhs, rhs) {\n return lhs + rhs;\n }\n subN(lhs, rhs) {\n return lhs - rhs;\n }\n mulN(lhs, rhs) {\n return lhs * rhs;\n }\n inv(num) {\n return invert(num, this.ORDER);\n }\n sqrt(num) {\n // Caching sqrt helpers speeds up sqrt9mod16 by 5x and Tonelli-Shanks by about 10% without keeping\n // the field instance itself mutable.\n let sqrt = FIELD_SQRT.get(this);\n if (!sqrt)\n FIELD_SQRT.set(this, (sqrt = FpSqrt(this.ORDER)));\n return sqrt(this, num);\n }\n toBytes(num) {\n // Serialize fixed-width limbs without re-validating the field range. Callers that need a\n // canonical encoding must pass a valid element; some protocols intentionally serialize raw\n // residues here and reduce or validate them elsewhere.\n return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);\n }\n fromBytes(bytes, skipValidation = false) {\n abytes(bytes);\n const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;\n if (allowedLengths) {\n // `allowedLengths` must list real positive byte lengths; otherwise empty input would get\n // padded into zero and silently decode as a field element.\n if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);\n }\n const padded = new Uint8Array(BYTES);\n // isLE add 0 to right, !isLE to the left.\n padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n bytes = padded;\n }\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n if (modFromBytes)\n scalar = mod(scalar, ORDER);\n if (!skipValidation)\n if (!this.isValid(scalar))\n throw new Error('invalid field element: outside of range 0..ORDER');\n // Range validation is optional here because some protocols intentionally decode raw residues\n // and reduce or validate them elsewhere.\n return scalar;\n }\n // TODO: we don't need it here, move out to separate fn\n invertBatch(lst) {\n // `passZero` keeps the `bigint[]` contract honest: zero inputs map to `0` instead of leaking\n // `undefined` into a `bigint[]`. Callers that must distinguish non-invertible inputs should use\n // `FpInvertBatch` directly, whose default omits `passZero` and returns `(bigint | undefined)[]`.\n return FpInvertBatch(this, lst, true);\n }\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov(a, b, condition) {\n // Field elements have `isValid(...)`; the CMOV branch bit is a direct runtime input, so reject\n // non-boolean selectors here instead of letting JS truthiness silently change arithmetic.\n abool(condition, 'condition');\n return condition ? b : a;\n }\n}\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. Frozen stable object shape; the lazy sqrt cache lives in a module-level `WeakMap`.\n * Fragile: always run a benchmark on a change.\n * Security note: operations and low-level serializers like `toBytes` don't check `isValid` for\n * all elements for performance and protocol-flexibility reasons; callers are responsible for\n * supplying valid elements when they need canonical field behavior.\n * This is low-level code, please make sure you know what you're doing.\n *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER - field order, probably prime, or could be composite\n * @param opts - Field options such as bit length or endianness. See {@link FieldOpts}.\n * @returns Frozen field instance with a stable object shape. This wrapper forwards `opts` straight\n * into `_Field`, so it inherits `_Field`'s assumptions about cached sizes and `allowedLengths`.\n * @example\n * Construct one prime field with optional overrides.\n *\n * ```ts\n * Field(11n);\n * ```\n */\nexport function Field(ORDER, opts = {}) {\n // Freeze the shared method surface before any instance is reachable; otherwise callers can\n // poison every Field instance by monkey-patching `_Field.prototype` even if each instance is\n // frozen. Freezing here instead of module scope keeps `_Field` tree-shakeable for importers\n // that never construct a field; the call is idempotent and cheap.\n Object.freeze(_Field.prototype);\n return new _Field(ORDER, opts);\n}\n/**\n * @param Fp - Field implementation.\n * @param elm - Value to square-root.\n * @returns Odd square root when two roots exist. The special case `elm = 0` still returns `0`,\n * which is the only square root but is not odd.\n * @throws If the field lacks oddness checks or the square root does not exist. {@link Error}\n * @example\n * Select the odd square root when two roots exist.\n *\n * ```ts\n * import { Field, FpSqrtOdd } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const root = FpSqrtOdd(Fp, 4n);\n * ```\n */\nexport function FpSqrtOdd(Fp, elm) {\n validateField(Fp);\n const F = Fp;\n if (!F.isOdd)\n throw new Error(\"Field doesn't have isOdd\");\n const root = F.sqrt(elm);\n return F.isOdd(root) ? root : F.neg(root);\n}\n/**\n * @param Fp - Field implementation.\n * @param elm - Value to square-root.\n * @returns Even square root.\n * @throws If the field lacks oddness checks or the square root does not exist. {@link Error}\n * @example\n * Select the even square root when two roots exist.\n *\n * ```ts\n * import { Field, FpSqrtEven } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const root = FpSqrtEven(Fp, 4n);\n * ```\n */\nexport function FpSqrtEven(Fp, elm) {\n validateField(Fp);\n const F = Fp;\n if (!F.isOdd)\n throw new Error(\"Field doesn't have isOdd\");\n const root = F.sqrt(elm);\n return F.isOdd(root) ? F.neg(root) : root;\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. Callers are expected to pass an\n * order greater than 1.\n * @returns byte length of field\n * @throws If the field order is not a bigint. {@link Error}\n * @example\n * Read the fixed-width byte length of one field.\n *\n * ```ts\n * getFieldBytesLength(255n);\n * ```\n */\nexport function getFieldBytesLength(fieldOrder) {\n if (typeof fieldOrder !== 'bigint')\n throw new Error('field order must be bigint');\n // Valid field elements are in 0..ORDER-1, so ORDER <= 1 would make the encoded range degenerate.\n if (fieldOrder <= _1n)\n throw new Error('field order must be greater than 1');\n // Valid field elements are < ORDER, so the maximal encoded element is ORDER - 1.\n const bitLength = bitLen(fieldOrder - _1n);\n return Math.ceil(bitLength / 8);\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 * This is the reduction / modulo-bias lower bound; higher-level helpers may still impose a larger\n * absolute floor for policy reasons.\n * @param fieldOrder - number of field elements greater than 1, usually CURVE.n.\n * @returns byte length of target hash\n * @throws If the field order is invalid. {@link Error}\n * @example\n * Compute the minimum hash length needed for field reduction.\n *\n * ```ts\n * getMinHashLength(255n);\n * ```\n */\nexport function getMinHashLength(fieldOrder) {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\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. The implementation also keeps a hard\n * 16-byte minimum even when `getMinHashLength(...)` is smaller, so toy-small inputs do not look\n * accidentally acceptable for real scalar derivation.\n * See {@link https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ | Kudelski's modulo-bias guide},\n * {@link https://csrc.nist.gov/publications/detail/fips/186/5/final | FIPS 186-5 appendix A.2}, and\n * {@link https://www.rfc-editor.org/rfc/rfc9380#section-5 | RFC 9380 section 5}. Unlike RFC 9380\n * `hash_to_field`, this helper intentionally maps into the non-zero private-scalar range `1..n-1`.\n * @param key - Uniform input bytes.\n * @param fieldOrder - Size of subgroup.\n * @param isLE - interpret hash bytes as LE num\n * @returns valid private scalar\n * @throws If the hash length or field order is invalid for scalar reduction. {@link Error}\n * @example\n * Map hash output into a private scalar range.\n *\n * ```ts\n * mapHashToField(new Uint8Array(48).fill(1), 255n);\n * ```\n */\nexport function mapHashToField(key, fieldOrder, isLE = false) {\n abytes(key);\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = Math.max(getMinHashLength(fieldOrder), 16);\n // No toy-small inputs: the helper is for real scalar derivation, not tiny test curves. No huge\n // inputs: easier to reason about JS timing / allocation behavior.\n if (len < minLen || len > 1024)\n throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n // Map into the non-zero scalar range [1, fieldOrder-1]: reduce mod (fieldOrder-1) to land in\n // [0, fieldOrder-2], then add 1. This shifts the range off zero; it is NOT equal to\n // `mod(num, fieldOrder)` (which spans [0, fieldOrder-1] and can be 0). A residual modulo bias\n // remains but is negligible (~2^-(nBits/2), e.g. ~2^-128 for a 256-bit order) because `key` is\n // required to be at least `getMinHashLength(fieldOrder)` (~1.5x field size) bytes of input.\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n", "/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF-based ScalarMultiplier, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { aarray, abool, afunction, aobject, bitLen, bitMask, bytesToNumberBE, inRange, isBytes, isPosBig, validateObject, } from \"../utils.js\";\nimport { Field, FpInvertBatch, validateField } from \"./modular.js\";\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _4n = /* @__PURE__ */ BigInt(4);\nconst BLIND_BYTES = 16;\nconst BLIND_BITS = 128;\n// Fixed-window width for the constant-time multiply of un-precomputed points (W===1).\n// A flat 2^FW_WINDOW table has a small, scalar-independent build cost that amortizes over a single\n// multiply, unlike the larger per-point wNAF tables that only pay off when cached.\nconst FW_WINDOW = 5;\n// Precompute tables are capped at ~2 GiB of estimated heap. Rejecting larger windows up front\n// turns a typo'd window size into an immediate error instead of a multi-GB allocation (or an\n// effective hang) when the lazy table is built on first multiply.\nconst TABLE_BYTES_MAX = /* @__PURE__ */ (() => 2 ** 31)();\n/**\n * Validates the static surface of a point constructor.\n * This is only a cheap sanity check for the constructor hooks and fields consumed by generic\n * factories; it does not certify `BASE`/`ZERO` semantics or prove the curve implementation itself.\n * @param Point - Runtime point constructor.\n * @throws On missing constructor hooks or malformed field metadata. {@link TypeError}\n * @example\n * Check that one point constructor exposes the static hooks generic helpers need.\n *\n * ```ts\n * import { ed25519 } from '@noble/curves/ed25519.js';\n * import { validatePointCons } from '@noble/curves/abstract/curve.js';\n * validatePointCons(ed25519.Point);\n * ```\n */\nexport function validatePointCons(Point) {\n const pc = Point;\n if (typeof pc !== 'function')\n throw new TypeError('\"Point\" expected constructor, got type=' + typeof Point);\n afunction(pc.fromAffine, 'Point.fromAffine');\n afunction(pc.fromBytes, 'Point.fromBytes');\n afunction(pc.fromHex, 'Point.fromHex');\n // Generic helpers (ScalarMultiplier, normalizeZ, MSM) dereference BASE / ZERO:\n // fail here with a typed error instead of an `undefined` access later.\n aobject(pc.BASE, 'Point.BASE');\n aobject(pc.ZERO, 'Point.ZERO');\n validateField(pc.Fp);\n validateField(pc.Fn);\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 * Input points are left unchanged; the normalized points are returned as fresh instances.\n * @param c - Point constructor.\n * @param points - Projective points.\n * @returns Fresh projective points reconstructed from normalized affine coordinates.\n * @example\n * Batch-normalize projective points with a single shared inversion.\n *\n * ```ts\n * import { normalizeZ } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const points = normalizeZ(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()]);\n * ```\n */\nexport function normalizeZ(c, points) {\n // Match MSM helpers: reject malformed public inputs before reading projective internals.\n validatePointCons(c);\n validateMSMPoints(points, c);\n // Identity points (Z=0) rely on an implicit contract: FpInvertBatch without `passZero`\n // yields `undefined` for zero inputs, and `toAffine(undefined)` falls back to its internal\n // is0 handling instead of using the batch inverse.\n const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\n}\nfunction validateW(W, bits, min = 1) {\n if (!Number.isSafeInteger(W) || W < min || W > bits)\n throw new Error('invalid window size, expected [' + min + '..' + bits + '], got W=' + W);\n}\n// Rough per-point heap estimate for the {@link TABLE_BYTES_MAX} cap: up to 4 projective/extended\n// coordinates of Fp.BYTES each, plus bigint/object overhead. Callers pass the point count of the\n// largest table the checked parameters can produce.\nfunction validateTableBytes(numPoints, fpBytes) {\n const bytes = numPoints * (4 * fpBytes + 128);\n if (bytes > TABLE_BYTES_MAX)\n throw new Error('invalid window size: table would need ~' +\n Math.ceil(bytes / 2 ** 20) +\n ' MiB, max ' +\n TABLE_BYTES_MAX / 2 ** 20 +\n ' MiB');\n}\n/**\n * Probes an RNG once, at construction time: returns `undefined` when it is unavailable \u2014\n * throws or returns malformed bytes \u2014 so callers can downgrade to their unblinded /\n * deterministic constant-time fallback. Blinding is defense-in-depth (DPA/template\n * hardening), not a correctness or key-secrecy requirement, so availability-based\n * downgrade is acceptable.\n *\n * The downgrade decision is deliberately static. After a successful probe the RNG becomes\n * part of the trusted contract: later misbehavior must fail closed in per-call validation\n * (throw), never downgrade \u2014 a dynamic fallback would let a tampered RNG silently strip\n * blinding on demand. A probe can only ever classify broken environments, not adversarial\n * RNGs: a stateful RNG can always behave while probed and misbehave later.\n * @param randomBytes - RNG to probe, or `undefined` when the environment provides none.\n * @param length - Byte length requested from the probe call.\n * @returns The RNG when the probe produced `length` valid bytes; `undefined` otherwise.\n * @example\n * Probe an RNG once before enabling scalar blinding.\n *\n * ```ts\n * import { probeRandomBytes } from '@noble/curves/abstract/curve.js';\n * import { randomBytes } from '@noble/hashes/utils.js';\n * const rng = probeRandomBytes(randomBytes, 16);\n * ```\n */\nexport function probeRandomBytes(randomBytes, length) {\n if (randomBytes === undefined)\n return undefined;\n afunction(randomBytes, 'randomBytes');\n try {\n const probe = randomBytes(length);\n if (!isBytes(probe) || probe.length !== length)\n return undefined;\n }\n catch {\n return undefined;\n }\n return randomBytes;\n}\nfunction validateMSMPoints(points, c) {\n aarray(points, 'points');\n points.forEach((p, i) => {\n if (!(p instanceof c))\n throw new Error('invalid point at index ' + i);\n });\n}\n// Default bound is field membership (0 <= s < field.ORDER); a `maxScalar` override widens it\n// to 0 <= s < maxScalar for callers that accept oversized scalars.\nfunction validateMSMScalars(scalars, field, maxScalar) {\n if (!Array.isArray(scalars))\n throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n const ok = maxScalar === undefined ? field.isValid(s) : isPosBig(s) && s < maxScalar;\n if (!ok)\n throw new Error('invalid scalar at index ' + i);\n });\n}\nconst pointWindowSizes = new WeakMap();\nfunction getWindowSize(P) {\n // `1` is the uncached sentinel: use the non-precomputed (wNAF / fixed-window) path.\n return pointWindowSizes.get(P) || 1;\n}\n/** Table of odd multiples [1P, 3P, ..., (2\u22C5size\u22121)P]; width-W wNAF uses size = 2^(W\u22122). */\nfunction oddMultiples(p, size) {\n const dbl = p.double();\n const t = [p];\n for (let j = 1; j < size; j++)\n t.push(t[j - 1].add(dbl));\n return t;\n}\n/**\n * Width-W wNAF signed-digit recoding (W >= 2), LSB-first: digits are 0 or odd with\n * |digit| < 2^(W\u22121); nonzero density ~1/(W+1) (a nonzero digit is followed by W\u22121 zeros).\n */\nfunction wnafDigits(n, W) {\n const size = 2 ** W;\n const half = size / 2;\n const mask = BigInt(size - 1);\n const d = [];\n while (n > _0n) {\n let w = 0;\n if (n & _1n) {\n w = Number(n & mask); // n mod 2^W, odd\n if (w >= half)\n w -= size; // signed residue\n n -= BigInt(w); // n - w \u2261 0 mod 2^W: next W\u22121 digits are zero\n }\n d.push(w);\n n >>= _1n;\n }\n return d;\n}\n/**\n * Fixed-position signed-window recoding for precomputed wNAF: `n = \u03A3 digits[w]\u22C52^(w\u22C5W)` with\n * digits in `[\u22122^(W\u22121)+1, 2^(W\u22121)]`. Digit count is fixed by `windows` (callers reserve one\n * extra window for the final carry), so recoding length does not depend on the scalar.\n */\nfunction signedWindowDigits(n, W, windows) {\n const size = 2 ** W;\n const half = size / 2;\n const mask = BigInt(size - 1);\n const shiftBy = BigInt(W);\n const d = [];\n for (let w = 0; w < windows; w++) {\n let v = Number(n & mask);\n n >>= shiftBy;\n if (v > half) {\n v -= size; // negative digit, carry into the next window\n n += _1n;\n }\n d.push(v);\n }\n // Internal invariant: leftover bits mean the window count did not cover the scalar.\n if (n !== _0n)\n throw new Error('invalid wnaf');\n return d;\n}\n/**\n * Shared vartime walk over per-scalar wNAF digit streams: one doubling of a single shared\n * accumulator per bit position of the longest recoding, one signed table addition per\n * nonzero digit. `tables[i]` must hold the odd multiples of the i-th point.\n */\nfunction wnafWalk(zero, tables, digits) {\n let max = 0;\n for (const d of digits)\n max = Math.max(max, d.length);\n let acc = zero;\n for (let bit = max - 1; bit >= 0; bit--) {\n if (bit !== max - 1)\n acc = acc.double();\n for (let i = 0; i < digits.length; i++) {\n const w = digits[i][bit]; // reads past shorter recodings yield undefined, skipped below\n if (w) {\n const item = tables[i][(Math.abs(w) - 1) >> 1];\n acc = acc.add(w < 0 ? item.negate() : item);\n }\n }\n }\n return acc;\n}\n/**\n * Elliptic curve multiplication of Point by scalar.\n * Routes between cached-table, fixed-window, and one-shot wNAF paths; entry points validate\n * their own scalars (`mulCT`/`mulCTBlinded`: `1 <= s < Fn.ORDER`; `mulUnsafe`: up to the\n * `Fn.ORDER^4` DoS cap via {@link mulAddUnsafe}).\n * Table generation is expensive and happens on first call of `multiply()`\n * (or eagerly via `precompute(W, false)`). By default, `BASE` point is precomputed.\n *\n * Cached algorithm is signed fixed-window wNAF:\n * - table stores, for every window w, the multiples `[1..2^(W\u22121)]\u22C52^(w\u22C5W)\u22C5P` \u2014 all doublings\n * are baked in, so a multiplication is exactly one table addition per window\n * - window count is fixed (`ceil(bits/W) + 1`), so the point-operation count is scalar-independent\n * (basis of the constant-time path)\n * - for a 256-bit curve and W=6: 44\u22C532 = 1408 table points, 44 additions per multiply\n * - secret scalars are additionally blinded (see {@link ScalarMultiplier.mulCTBlinded}), which\n * widens tables by 128 bits\n * @param Point - Point constructor.\n * @param randomBytes - RNG used for scalar blinding; required by the blinded secret path.\n * @example\n * Elliptic curve multiplication of Point by scalar.\n *\n * ```ts\n * import { ScalarMultiplier } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const mul = new ScalarMultiplier(p256.Point);\n * ```\n */\nexport class ScalarMultiplier {\n Point;\n BASE;\n ZERO;\n randomBytes;\n wnafPrecomputes = new WeakMap();\n baseCanBeBlinded;\n bits;\n // Parametrized with a given Point class (not individual point)\n constructor(Point, randomBytes) {\n validatePointCons(Point);\n // Probe the RNG once (see {@link probeRandomBytes}): in environments without working\n // randomness (e.g. no WebCrypto), shouldBlind() then routes secret multiplication to the\n // unblinded constant-time path instead of throwing on every multiply(). The shape of\n // returned bytes is still validated on every blinded call, where breakage fails closed.\n this.randomBytes = probeRandomBytes(randomBytes, BLIND_BYTES);\n this.Point = Point;\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.bits = Point.Fn.BITS;\n }\n /**\n * Creates a signed fixed-window wNAF precomputation table: for every window w, the\n * multiples `[1..2^(W\u22121)]\u22C52^(w\u22C5W)\u22C5P`, flattened. All doublings are baked into the table,\n * so cached multiplication is additions-only. `windows = ceil(bits/W) + 1`: the extra\n * window absorbs the final carry of signed-digit recoding.\n * For a 256-bit curve and W=6, the table is 44\u22C532 = 1408 points.\n * @param point - Point instance\n * @param W - window size\n * @param bits - scalar bitlength the table must cover\n */\n buildWnafTable(point, W, bits) {\n // W needs no re-validation: its only source is setWindowSize(), which enforces\n // 1 <= W <= Fn.BITS <= bits (the blinded path only ever widens bits) and caps the\n // resulting table at ~2 GiB (sized against the wider blinded layout).\n const windows = Math.ceil(bits / W) + 1;\n const half = 2 ** (W - 1);\n const comp = [];\n let base = point;\n for (let w = 0; w < windows; w++) {\n let acc = base;\n for (let i = 0; i < half; i++) {\n comp.push(acc);\n acc = acc.add(base);\n }\n base = comp[comp.length - 1].double(); // 2\u22C5(2^(W\u22121)\u22C5base) = next window's base\n }\n return { W, bits, windows, comp };\n }\n /**\n * Implements ec multiplication using precomputed signed fixed-window wNAF tables.\n * Constant-time: fixed window count with one table addition per window \u2014 zero digits feed\n * the fake accumulator \u2014 and no doublings; the lookup scans the whole window slice.\n * Scalar bounds are validated by the public entry points ({@link ScalarMultiplier.mulCT},\n * {@link ScalarMultiplier.mulCTBlinded}, {@link ScalarMultiplier.mulUnsafe});\n * signedWindowDigits throws if `n` exceeds the table.\n * @returns real and fake (for const-time) points\n */\n wnafCachedCT(precomputes, n) {\n const { W, windows, comp } = precomputes;\n const half = 2 ** (W - 1);\n const digits = signedWindowDigits(n, W, windows);\n let p = this.ZERO;\n let f = this.BASE;\n for (let w = 0; w < windows; w++) {\n const digit = digits[w];\n const start = w * half;\n // Data-oblivious select: touch every entry of the window before the digit branch.\n const idx = Math.abs(digit) - 1; // -1 for zero digits: matches nothing, `sel` unused\n let sel = comp[start];\n for (let i = 1; i < half; i++)\n sel = i === idx ? comp[start + i] : sel;\n const neg = sel.negate(); // compute both signs; the digit only picks one\n if (digit === 0)\n f = f.add(comp[start]);\n else\n p = p.add(digit < 0 ? neg : sel);\n }\n return { p, f };\n }\n // Cache key is point identity plus (W, bits); at most two entries exist per point (public-width\n // `Fn.BITS` and blinded `Fn.BITS + BLIND_BITS`). Callers must not reuse the same point with\n // incompatible `transform(...)` layouts and expect a separate cache entry.\n getWnafPrecomputes(W, point, bits, transform) {\n let entries = this.wnafPrecomputes.get(point);\n let comp = entries?.find((entry) => entry.W === W && entry.bits === bits);\n if (!comp) {\n comp = this.buildWnafTable(point, W, bits);\n if (typeof transform === 'function')\n comp = { ...comp, comp: transform(comp.comp) };\n if (!entries) {\n entries = [];\n this.wnafPrecomputes.set(point, entries);\n }\n entries.push(comp);\n }\n return comp;\n }\n assertPoint(point) {\n if (!(point instanceof this.Point))\n throw new TypeError('\"point\" expected Point instance, got type=' + typeof point);\n }\n // Shared prologue of the constant-time entry points. Rejects scalar 0: in key/signature-style\n // callers a zero scalar means broken upstream plumbing, and concrete Points already reject it.\n // Uses inRange instead of Fn.isValidNot0: validateField() only certifies the arithmetic subset.\n validateMulInput(point, scalar) {\n this.assertPoint(point);\n if (!inRange(scalar, _1n, this.Point.Fn.ORDER))\n throw new Error('invalid scalar');\n }\n // Constant-time dispatch shared by mulCT / mulCTBlinded. Un-precomputed points (W===1, e.g.\n // ECDH peer keys) skip building a throwaway cached table in favor of a small fixed-window\n // multiply. `n` must be < 2^bits.\n runCT(point, n, bits, transform) {\n const W = getWindowSize(point);\n if (W === 1)\n return this.fixedWindowCT(point, n, bits);\n return this.wnafCachedCT(this.getWnafPrecomputes(W, point, bits, transform), n);\n }\n mulCT(point, scalar, transform) {\n this.validateMulInput(point, scalar);\n return this.runCT(point, scalar, this.bits, transform);\n }\n mulCTBlinded(point, scalar, transform) {\n this.validateMulInput(point, scalar);\n // Blinding computes n = scalar + blind*Fn.ORDER, then n*P via a constant-time multiply. This\n // equals scalar*P only when Fn.ORDER*P == O; callers guarantee that via shouldBlind() (always\n // for cofactor-1 curves; for cofactored curves only BASE, and only after checking BASE*n == O).\n // Fail before building the (large) precompute table if randomness is unavailable.\n if (this.randomBytes === undefined)\n throw new Error('randomBytes is required for scalar blinding');\n const bits = this.Point.Fn.BITS + BLIND_BITS;\n const blind = this.randomBytes(BLIND_BYTES);\n if (!isBytes(blind) || blind.length !== BLIND_BYTES)\n throw new Error('randomBytes returned invalid byte array');\n // Force the top two bits of the 128-bit blind to 10xxxxxx, so blind is in [2^127, 1.5*2^127):\n // * `| 0x80` (bit 127 = 1) is the load-bearing part: it guarantees blind >= 2^127, so the blind\n // is always a full-width, nonzero factor and the scalar is masked even with a degenerate RNG.\n // * `& 0x3f` (bit 126 = 0) is a safety margin: it caps blind < 1.5*2^127, keeping\n // blind*Fn.ORDER + scalar < 0.75*2^(nBits+128), i.e. ~half a window below the 2^(nBits+128)\n // ceiling. Not strictly required for the bound (see below), but it reserves headroom so the\n // guarantee does not rest on the tight `Fn.ORDER < 2^Fn.BITS` fact and the final carry window\n // only ever holds a small carry, never a full digit.\n blind[0] = (blind[0] & 0x3f) | 0x80;\n // Even at the extreme (blind < 2^128, scalar < Fn.ORDER < 2^nBits): n <= 2^128*Fn.ORDER - 1 <\n // 2^(nBits+128), so n stays below 2^bits and within the blinded table's\n // window count. Both cached CT kernels run a fixed number of windows/rows with one point-add\n // each, so the add count is independent of scalar (constant-time).\n const n = scalar + bytesToNumberBE(blind) * this.Point.Fn.ORDER;\n return this.runCT(point, n, bits, transform);\n }\n /**\n * Constant-time multiplication `n*point` for an un-precomputed point, via a small fixed window.\n * A cached wNAF table only pays off when reused; a flat 2^FW_WINDOW table (`size-1` adds) is\n * far cheaper to build for a single use. The point-operation sequence is independent of `n`:\n * build the table, then per window exactly FW_WINDOW doublings, a data-oblivious scan over\n * every table entry, and one addition (adds the identity when the window digit is 0 \u2014 never\n * skipped).\n *\n * `n` must be `< 2^bits`. Assumes complete addition (adding the identity costs the same as any\n * add), which holds for the Weierstrass/Edwards point types used here. The table is left in\n * projective form (no normalizeZ): normalizing this small a table costs more than the\n * mixed-add savings it would buy for a single multiply.\n * @returns real point `p`; `f` duplicates it only to match {@link wnafCachedCT}'s return shape\n * (this path needs no fake accumulator \u2014 its op-count is already scalar-independent).\n */\n fixedWindowCT(point, n, bits) {\n const W = FW_WINDOW;\n const size = 1 << W;\n const mask = bitMask(W);\n // Flat table [O, point, 2*point, ..., (size-1)*point].\n const table = new Array(size);\n table[0] = this.ZERO;\n for (let i = 1; i < size; i++)\n table[i] = table[i - 1].add(point);\n // Horner MSB->LSB. windows*W >= bits and n < 2^bits, so every bit of n is consumed.\n const windows = Math.ceil(bits / W);\n let acc = this.ZERO;\n for (let window = windows - 1; window >= 0; window--) {\n // W doublings per window; skipped for the first (topmost) window, where acc is still the\n // identity. The skip is scalar-independent: it depends only on the loop index.\n if (window !== windows - 1)\n for (let d = 0; d < W; d++)\n acc = acc.double();\n const digit = Number((n >> BigInt(window * W)) & mask);\n // Data-oblivious select: touch every entry, same as wnafCachedCT.\n let sel = table[0];\n for (let i = 1; i < size; i++)\n sel = i === digit ? table[i] : sel;\n acc = acc.add(sel); // one add per window, even for digit 0\n }\n return { p: acc, f: acc };\n }\n shouldBlind(point, cofactor) {\n // No usable RNG (probed in the constructor): blinding is impossible, use the plain CT path.\n if (this.randomBytes === undefined)\n return false;\n if (cofactor === _1n)\n return true;\n if (point !== this.BASE)\n return false;\n if (this.baseCanBeBlinded === undefined)\n this.baseCanBeBlinded = this.mulUnsafe(this.BASE, this.Point.Fn.ORDER).is0();\n return this.baseCanBeBlinded;\n }\n mulSecret(point, scalar, cofactor, transform) {\n return this.shouldBlind(point, cofactor)\n ? this.mulCTBlinded(point, scalar, transform)\n : this.mulCT(point, scalar, transform);\n }\n mulUnsafe(point, scalar, transform) {\n this.assertPoint(point);\n if (!isPosBig(scalar))\n throw new Error('invalid scalar');\n const W = getWindowSize(point);\n // W === 1 (un-precomputed): one-shot width-4 wNAF via {@link mulAddUnsafe} with L=1 \u2014\n // a cached table would be thrown away after one use. `allowOversized` swaps the\n // `s < Fn.ORDER` check for mulAddUnsafe's `Fn.ORDER^4` DoS cap.\n //\n // Oversized scalar could happen when:\n // a) user passes large scalar on their own (rare)\n // b) `assertValidity()` calls `isTorsionFree()`, which multiplies point by `Fn.ORDER`\n if (W === 1 || scalar >= this.Point.Fn.ORDER)\n return mulAddUnsafe(this.Point, [point], [scalar], true);\n // Precomputed points reuse the CT kernel (fake accumulator discarded): with W=6 only\n // ~1/64 of window-adds are skippable, so a dedicated vartime kernel saved just ~6% on\n // this path while doubling the cached-table code surface.\n const precomputes = this.getWnafPrecomputes(W, point, this.bits, transform);\n return this.wnafCachedCT(precomputes, scalar).p;\n }\n // Remembers the window size used for precomputed wNAF multiplication of the given point\n // and drops any previously built tables. Usually only the base point is precomputed.\n // W=1 resets the point to the un-precomputed (table-less) paths.\n // W is additionally capped so tables stay under ~2 GiB ({@link TABLE_BYTES_MAX}).\n setWindowSize(point, W) {\n this.assertPoint(point);\n validateW(W, this.bits);\n // Size against the widest table this W can produce: the blinded path adds BLIND_BITS.\n const windows = Math.ceil((this.bits + BLIND_BITS) / W) + 1;\n validateTableBytes(windows * 2 ** (W - 1), this.Point.Fp.BYTES);\n pointWindowSizes.set(point, W);\n this.wnafPrecomputes.delete(point);\n }\n // True when a window size is set: tables themselves are built lazily on first multiply.\n hasWindowSize(point) {\n return getWindowSize(point) !== 1;\n }\n}\n/**\n * Combined multi-scalar multiplication `\u03A3 scalars[i]\u22C5points[i]` via interleaved width-4 wNAF\n * (Strauss\u2013Shamir). Every input gets its own table of odd multiples `[1P, 3P, 5P, 7P]` and\n * signed-digit recoding, but all walks share one doubling chain, so total cost is\n * `~bits` doublings + `L\u22C5bits/5` additions instead of `L\u22C5bits` doublings for separate\n * multiplications. Intended for the 2-4 point shapes of signature verification\n * (`R = u1\u22C5G + u2\u22C5P`); use {@link pippenger} for larger batches.\n *\n * Not constant-time: only for public inputs. Scalars must satisfy `0 <= s < Fn.ORDER`;\n * fold negative signs into the points before calling.\n * @param c - Point constructor.\n * @param points - Array of curve points.\n * @param scalars - Array of non-negative scalars, same length as points.\n * @param allowOversized - Replace the `s < Fn.ORDER` scalar check with a `Fn.ORDER^4` DoS cap.\n * Off by default. For scalars that must NOT be reduced mod ORDER: torsion checks\n * (`Fn.ORDER\u22C5P \u225F O`) and cofactor-clearing multiples. Walk length grows with `bitLen(s)`.\n * @returns Combined multiplication result; identity for empty input.\n * @throws If the point set or scalar set is invalid. {@link Error}\n * @example\n * Combined multi-scalar multiplication via Strauss\u2013Shamir.\n *\n * ```ts\n * import { mulAddUnsafe } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const G = p256.Point.BASE;\n * const R = mulAddUnsafe(p256.Point, [G, G.double()], [2n, 3n]); // 2\u22C5G + 3\u22C5(2\u22C5G)\n * ```\n */\nexport function mulAddUnsafe(c, points, scalars, allowOversized = false) {\n validatePointCons(c);\n validateMSMPoints(points, c);\n abool(allowOversized, 'allowOversized');\n // Oversized cap is ORDER^4: hard bound to mitigate DoS, walk length grows with bitLen(s).\n validateMSMScalars(scalars, c.Fn, allowOversized ? c.Fn.ORDER ** _4n : undefined);\n if (points.length !== scalars.length)\n throw new Error('arrays of points and scalars must have equal length');\n const tables = points.map((p) => oddMultiples(p, 4));\n const digits = scalars.map((n) => wnafDigits(n, 4));\n return wnafWalk(c.ZERO, tables, digits);\n}\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Point-operation count is scalar-independent (for same L), even when 1 point + scalar, or when\n * scalar = 0 \u2014 but bucket indices are scalar windows, so the memory-access pattern is\n * scalar-dependent: do not rely on this for secret scalars.\n *\n * A repaired LFG bucket-set variant from ePrint 2024/750 was benchmarked on BLS12-381 G1\n * against this implementation: ~1.4x faster at 2048 points and ~1.1-1.25x faster at\n * 4096-32768 points, at the cost of extra recoding and multiplier-table complexity.\n * @param c - Curve Point constructor\n * @param points - array of L curve points\n * @param scalars - array of L scalars (aka secret keys / bigints)\n * @returns MSM result point. Empty input is accepted and returns the identity.\n * @throws If the point set, scalar set, or MSM sizing is invalid. {@link Error}\n * @example\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n *\n * ```ts\n * import { pippenger } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const point = pippenger(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()], [2n, 3n]);\n * ```\n */\nexport function pippenger(c, points, scalars) {\n // 0 is accepted in scalars\n validatePointCons(c);\n const fieldN = c.Fn;\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength)\n throw new Error('arrays of points and scalars must have equal length');\n const zero = c.ZERO;\n // Without this, the window loop below would still run ~Fn.BITS doublings of ZERO.\n if (plength === 0)\n return zero;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12)\n windowSize = wbits - 3;\n else if (wbits > 4)\n windowSize = wbits - 2;\n else if (wbits > 0)\n windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array\n const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n let sum = zero;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(zero);\n for (let j = 0; j < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & MASK);\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = zero; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0)\n for (let j = 0; j < windowSize; j++)\n sum = sum.double();\n }\n return sum;\n}\n/**\n * Interleaved wNAF multi-scalar multiplication (MSM, Pa + Qb + Rc + ...) over a FIXED set\n * of points: each point gets a one-time table of odd multiples\n * `[1P, 3P, ..., (2^(W\u22121)\u22121)P]`, and the returned closure evaluates MSMs against those\n * tables. All scalars share one doubling chain (Straus 1964) \u2014 one doubling per scalar bit\n * plus one signed table addition per nonzero width-W wNAF digit (density ~1/(W+1)) \u2014 the\n * \"interleaving\" method of M\u00F6ller, \"Algorithms for multi-exponentiation\" (SAC 2001).\n *\n * Table memory is `L\u22C52^(W\u22122)` points, capped at ~2 GiB. Prefer this over {@link pippenger}\n * when the same points are reused across many MSMs (fixed-base commitments etc.) and up to a\n * few hundred points; prefer pippenger for one-shot MSMs or thousands of points, where\n * bucketing beats per-point tables.\n *\n * Not constant-time (zero digits are skipped): public inputs only.\n * @param c - Curve Point constructor\n * @param points - array of L curve points, captured by the returned closure\n * @param windowSize - window width W in bits, from 2 to Fn.BITS; also capped so the\n * per-closure tables stay under ~2 GiB\n * @returns Function which multiplies points with scalars. The closure accepts at most\n * `points.length` scalars, and omitted trailing scalars are treated as zero.\n * @throws If the point set or precompute window is invalid. {@link Error}\n * @example\n * Interleaved wNAF multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n *\n * ```ts\n * import { interleavedMSMUnsafe } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const msm = interleavedMSMUnsafe(p256.Point, [p256.Point.BASE], 4);\n * const point = msm([3n]);\n * ```\n */\nexport function interleavedMSMUnsafe(c, points, windowSize) {\n validatePointCons(c);\n const fieldN = c.Fn;\n // Signed odd digits need at least width 2 (W=2 is plain NAF with a single-entry table).\n validateW(windowSize, fieldN.BITS, 2);\n validateMSMPoints(points, c);\n validateTableBytes(points.length * 2 ** (windowSize - 2), c.Fp.BYTES);\n const tables = points.map((p) => oddMultiples(p, 2 ** (windowSize - 2)));\n return (scalars) => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must not be larger than array of points');\n return wnafWalk(c.ZERO, tables, scalars.map((n) => wnafDigits(n, windowSize)));\n };\n}\nfunction createField(order, field, isLE) {\n if (field) {\n // Reuse supplied field overrides as-is; `isLE` only affects freshly constructed fallback\n // fields, and validateField() below only checks the arithmetic subset, not full byte/cmov\n // behavior.\n if (field.ORDER !== order)\n throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field;\n }\n else {\n return Field(order, { isLE });\n }\n}\n/**\n * Validates basic CURVE shape and field membership, then creates fields.\n * This does not prove that the generator is on-curve, that subgroup/order data are consistent, or\n * that the curve equation itself is otherwise sane.\n * @param type - Curve family.\n * @param CURVE - Curve parameters.\n * @param curveOpts - Optional field overrides. See {@link FpFn}:\n * - `Fp` (optional): Optional base-field override.\n * - `Fn` (optional): Optional scalar-field override.\n * @param FpFnLE - Whether field encoding is little-endian.\n * @returns Frozen curve parameters and fields.\n * @throws If the curve parameters or field overrides are invalid. {@link Error}\n * @example\n * Build curve fields from raw constants before constructing a curve instance.\n *\n * ```ts\n * const curve = createCurveFields('weierstrass', {\n * p: 17n,\n * n: 19n,\n * h: 1n,\n * a: 2n,\n * b: 2n,\n * Gx: 5n,\n * Gy: 1n,\n * });\n * ```\n */\nexport function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {\n if (type !== 'weierstrass' && type !== 'edwards')\n throw new Error('expected curve type \"weierstrass\" or \"edwards\"');\n if (FpFnLE === undefined)\n FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object')\n throw new Error(`expected valid ${type} CURVE object`);\n // Validate before reading Fp/Fn so explicit null fails with an options-object error.\n validateObject(curveOpts);\n for (const p of ['p', 'n', 'h']) {\n const val = CURVE[p];\n if (!(isPosBig(val) && val !== _0n))\n throw new Error(`CURVE.${p} must be positive bigint`);\n }\n const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n const _b = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b];\n for (const p of params) {\n // @ts-ignore\n if (!Fp.isValid(CURVE[p]))\n throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n }\n CURVE = Object.freeze(Object.assign({}, CURVE));\n return { CURVE, Fp, Fn };\n}\n/**\n * @param randomSecretKey - Secret-key generator.\n * @param getPublicKey - Public-key derivation helper.\n * @returns Keypair generator.\n * @example\n * Build a `keygen()` helper from existing secret-key and public-key primitives.\n *\n * ```ts\n * import { createKeygen } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const keygen = createKeygen(p256.utils.randomSecretKey, p256.getPublicKey);\n * const pair = keygen();\n * ```\n */\nexport function createKeygen(randomSecretKey, getPublicKey) {\n return function keygen(seed) {\n const secretKey = randomSecretKey(seed);\n return { secretKey, publicKey: getPublicKey(secretKey) };\n };\n}\n", "/**\n * Twisted Edwards curve. The formula is: ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2.\n * For design rationale of types / exports, see weierstrass module documentation.\n * Untwisted Edwards curves exist, but they aren't used in real-world protocols.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abool, abytes, aInRange, asafenumber, bytesToHex, bytesToNumberLE, concatBytes, copyBytes, hexToBytes, isBytes, notImplemented, validateObject, randomBytes as wcRandomBytes, } from \"../utils.js\";\nimport { createCurveFields, createKeygen, normalizeZ, ScalarMultiplier, validatePointCons, } from \"./curve.js\";\nimport { FpLegendre } from \"./modular.js\";\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _4n = /* @__PURE__ */ BigInt(4), _8n = /* @__PURE__ */ BigInt(8);\n// Affine Edwards-equation check only; this does not prove subgroup membership, canonical\n// encoding, prime-order base-point requirements, or identity exclusion.\nfunction isEdValidXY(Fp, CURVE, x, y) {\n const x2 = Fp.sqr(x);\n const y2 = Fp.sqr(y);\n const left = Fp.add(Fp.mul(CURVE.a, x2), y2);\n const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));\n return Fp.eql(left, right);\n}\n/**\n * @param params - Curve parameters. See {@link EdwardsOpts}.\n * @param extraOpts - Optional helpers and overrides. See {@link EdwardsExtraOpts}.\n * @returns Edwards point constructor. Generator validation here only checks\n * that `(Gx, Gy)` satisfies the affine Edwards equation.\n * RFC 8032 base-point constraints like `B != (0,1)` and `[L]B = 0`\n * are left to the caller's chosen parameters, since eager subgroup\n * validation here adds about 10-15ms to heavyweight imports like ed448.\n * The returned constructor also eagerly marks `Point.BASE` for W=6\n * precompute caching. Some code paths still assume\n * `Fp.BYTES === Fn.BYTES`, so mismatched byte lengths are not fully audited here.\n * @throws If the curve parameters or Edwards overrides are invalid. {@link Error}\n * @example\n * ```ts\n * import { edwards } from '@noble/curves/abstract/edwards.js';\n * import { jubjub } from '@noble/curves/misc.js';\n * // Build a point constructor from explicit curve parameters, then use its base point.\n * const Point = edwards(jubjub.Point.CURVE());\n * Point.BASE.toHex();\n * ```\n */\nexport function edwards(params, extraOpts = {}) {\n validateObject(extraOpts, {}, {}, 'extraOpts');\n const opts = extraOpts;\n const validated = createCurveFields('edwards', params, opts, opts.FpFnLE);\n const { Fp, Fn } = validated;\n let CURVE = validated.CURVE;\n const { h: cofactor } = CURVE;\n // The unified add-2008-hwcd formulas (see EdwardsPoint.add/double) are complete \u2014\n // exception-free for every input pair \u2014 only when a is a square and d a non-square in Fp\n // (Bernstein\u2013Birkner\u2013Joye\u2013Lange\u2013Peters, \"Twisted Edwards curves\", thm 3.3). The constant-time\n // kernels in curve.ts assume completeness, so an incomplete curve could silently produce\n // wrong results on exceptional inputs. Fail construction instead.\n if (FpLegendre(Fp, CURVE.a) !== 1)\n throw new Error('edwards: CURVE.a must be a square in Fp for complete addition formulas');\n if (FpLegendre(Fp, CURVE.d) !== -1)\n throw new Error('edwards: CURVE.d must be a non-square in Fp for complete addition formulas');\n validateObject(opts, {}, { uvRatio: 'function', randomBytes: 'function' });\n const randomBytes = opts.randomBytes === undefined ? wcRandomBytes : opts.randomBytes;\n // Coordinate and ZIP-215 bounds follow the base-field byte container, not scalar bytes.\n const MASK = _2n << (BigInt(Fp.BYTES * 8) - _1n);\n function isOdd(n) {\n if (!Fp.isOdd)\n throw new Error('Field does not have .isOdd()');\n return Fp.isOdd(n);\n }\n // sqrt(u/v)\n const uvRatio = opts.uvRatio === undefined\n ? (u, v) => {\n try {\n return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };\n }\n catch (e) {\n return { isValid: false, value: _0n };\n }\n }\n : opts.uvRatio;\n // Validate whether the passed curve params are valid.\n // equation ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2 should work for generator point.\n if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))\n throw new Error('bad curve params: generator point');\n // Multiplication by param `a` sits on the double() / add() hot paths. For the common twists\n // a=-1 (ed25519, jubjub) and a=1 (ed448) the full field multiplication is replaced with\n // negation / identity. Selection depends only on public curve constants.\n const mulA = Fp.eql(CURVE.a, Fp.neg(Fp.ONE)) ? (x) => Fp.neg(x)\n : Fp.eql(CURVE.a, Fp.ONE) ? (x) => x\n : (x) => Fp.mul(CURVE.a, x); // prettier-ignore\n /**\n * Asserts coordinate is valid: 0 <= n < MASK.\n * Coordinates >= Fp.ORDER are allowed for zip215.\n */\n function acoord(title, n, banZero = false) {\n const min = banZero ? _1n : _0n;\n aInRange('coordinate ' + title, n, min, MASK);\n return n;\n }\n function aedpoint(other) {\n if (!(other instanceof Point))\n throw new Error('EdwardsPoint 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 {\n static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE, Fp.mul(CURVE.Gx, CURVE.Gy));\n static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ONE, Fp.ZERO);\n static Fp = Fp;\n static Fn = Fn;\n X;\n Y;\n Z;\n T;\n constructor(X, Y, Z, T) {\n this.X = acoord('x', X);\n this.Y = acoord('y', Y);\n this.Z = acoord('z', Z, true);\n this.T = acoord('t', T);\n Object.freeze(this);\n }\n static CURVE() {\n return CURVE;\n }\n /**\n * Create one extended Edwards point from affine coordinates.\n * Does NOT validate that the point is on-curve or torsion-free.\n * Use `.assertValidity()` on adversarial inputs.\n */\n static fromAffine(p) {\n if (p instanceof Point)\n throw new Error('extended point not allowed');\n const { x, y } = p || {};\n acoord('x', x);\n acoord('y', y);\n return new Point(x, y, Fp.ONE, Fp.mul(x, y));\n }\n // Uses algo from RFC8032 5.1.3.\n static fromBytes(bytes, zip215 = false) {\n const len = Fp.BYTES;\n const { a, d } = CURVE;\n bytes = copyBytes(abytes(bytes, len, 'point'));\n abool(zip215, 'zip215');\n const normed = copyBytes(bytes); // copy again, we'll manipulate it\n const lastByte = bytes[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = bytesToNumberLE(normed);\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n const max = zip215 ? MASK : Fp.ORDER;\n aInRange('point.y', y, _0n, max);\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 = Fp.sqr(y); // denominator is always non-0 mod p.\n const u = Fp.sub(y2, Fp.ONE); // u = y\u00B2 - 1\n const v = Fp.sub(Fp.mulN(d, y2), a); // v = d y\u00B2 - a.\n let { isValid, value: x } = uvRatio(u, v); // \u221A(u/v)\n if (!isValid)\n throw new Error('bad point: invalid y coordinate');\n const isXOdd = isOdd(x); // 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 && Fp.is0(x) && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('bad point: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd)\n x = Fp.neg(x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromHex(hex, zip215 = false) {\n return Point.fromBytes(hexToBytes(hex), zip215);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n precompute(windowSize = 6, isLazy = true) {\n wnaf.setWindowSize(this, windowSize);\n if (!isLazy)\n this.multiply(_2n); // random number\n return this;\n }\n // Useful in fromAffine() - not for fromBytes(), which always created valid points.\n assertValidity() {\n const p = this;\n const { a, d } = CURVE;\n // Keep generic Edwards validation fail-closed on the neutral point.\n // Even though ZERO is algebraically valid and can roundtrip through encodings, higher-level\n // callers often reach it only through broken hash/scalar plumbing; rejecting it here avoids\n // silently treating that degenerate state as an ordinary public point.\n if (p.is0())\n 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 { X, Y, Z, T } = p;\n const X2 = Fp.sqr(X); // X\u00B2\n const Y2 = Fp.sqr(Y); // Y\u00B2\n const Z2 = Fp.sqr(Z); // Z\u00B2\n const Z4 = Fp.sqr(Z2); // Z\u2074\n const aX2 = Fp.mul(X2, a); // aX\u00B2\n const left = Fp.mul(Fp.add(aX2, Y2), Z2); // (aX\u00B2 + Y\u00B2)Z\u00B2\n const right = Fp.add(Z4, Fp.mul(d, Fp.mul(X2, Y2))); // Z\u2074 + dX\u00B2Y\u00B2\n if (!Fp.eql(left, right))\n 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 = Fp.mul(X, Y);\n const ZT = Fp.mul(Z, T);\n if (!Fp.eql(XY, ZT))\n throw new Error('bad point: equation left != right (2)');\n }\n // Compare one point to another.\n equals(other) {\n aedpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n const X1Z2 = Fp.mul(X1, Z2);\n const X2Z1 = Fp.mul(X2, Z1);\n const Y1Z2 = Fp.mul(Y1, Z2);\n const Y2Z1 = Fp.mul(Y2, Z1);\n return Fp.eql(X1Z2, X2Z1) && Fp.eql(Y1Z2, Y2Z1);\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n negate() {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(Fp.neg(this.X), this.Y, this.Z, Fp.neg(this.T));\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() {\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const A = Fp.sqr(X1); // A = X12\n const B = Fp.sqr(Y1); // B = Y12\n const C = Fp.mul(Fp.sqr(Z1), _2n); // C = 2*Z12\n const D = mulA(A); // D = a*A\n const x1y1 = Fp.addN(X1, Y1);\n const E = Fp.sub(Fp.subN(Fp.sqr(x1y1), A), B); // E = (X1+Y1)2-A-B\n const G = Fp.addN(D, B); // G = D+B\n const F = Fp.subN(G, C); // F = G-C\n const H = Fp.subN(D, B); // H = D-B\n const X3 = Fp.mul(E, F); // X3 = E*F\n const Y3 = Fp.mul(G, H); // Y3 = G*H\n const T3 = Fp.mul(E, H); // T3 = E*H\n const Z3 = Fp.mul(F, G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\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) {\n aedpoint(other);\n const { d } = CURVE;\n const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;\n const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;\n const A = Fp.mul(X1, X2); // A = X1*X2\n const B = Fp.mul(Y1, Y2); // B = Y1*Y2\n const C = Fp.mul(Fp.mulN(T1, d), T2); // C = T1*d*T2\n const D = Fp.mul(Z1, Z2); // D = Z1*Z2\n // E = (X1+Y1)*(X2+Y2)-A-B\n const E = Fp.sub(Fp.subN(Fp.mulN(Fp.addN(X1, Y1), Fp.addN(X2, Y2)), A), B);\n const F = Fp.subN(D, C); // F = D-C\n const G = Fp.addN(D, C); // G = D+C\n const H = Fp.sub(B, mulA(A)); // H = B-a*A\n const X3 = Fp.mul(E, F); // X3 = E*F\n const Y3 = Fp.mul(G, H); // Y3 = G*H\n const T3 = Fp.mul(E, H); // T3 = E*H\n const Z3 = Fp.mul(F, G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n subtract(other) {\n // Validate before calling `negate()` so wrong inputs fail with the point guard\n // instead of leaking a foreign `negate()` error.\n aedpoint(other);\n return this.add(other.negate());\n }\n // Constant-time multiplication.\n multiply(scalar) {\n // 1 <= scalar < L\n // Keep the subgroup-scalar contract strict instead of reducing 0 / n to ZERO.\n // In keygen/signing-style callers, those values usually mean broken hash/scalar plumbing,\n // and failing closed is safer than silently producing the identity point.\n if (!Fn.isValidNot0(scalar))\n throw new RangeError('invalid scalar: expected 1 <= sc < curve.n');\n const { p, f } = wnaf.mulSecret(this, scalar, cofactor, normalize);\n return normalize([p, f])[0];\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 // Keeps the same subgroup-scalar contract: 0 is allowed for public-scalar callers, but\n // n and larger values are rejected instead of being reduced mod n to the identity point.\n multiplyUnsafe(scalar) {\n // 0 <= scalar < L\n if (!Fn.isValid(scalar))\n throw new RangeError('invalid scalar: expected 0 <= sc < curve.n');\n if (scalar === _0n)\n return Point.ZERO;\n if (this.is0() || scalar === _1n)\n return this;\n return wnaf.mulUnsafe(this, scalar, normalize);\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 // Clears cofactor and checks if the result is 0.\n isSmallOrder() {\n return this.clearCofactor().is0();\n }\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree() {\n return wnaf.mulUnsafe(this, CURVE.n).is0();\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(invertedZ) {\n const p = this;\n let iz = invertedZ;\n if (iz != null && typeof iz !== 'bigint')\n throw new TypeError('\"invertedZ\" expected bigint, got type=' + typeof iz);\n const { X, Y, Z } = p;\n const is0 = p.is0();\n if (iz == null)\n iz = is0 ? Fp.create(_8n) : Fp.inv(Z);\n const x = Fp.mul(X, iz);\n const y = Fp.mul(Y, iz);\n const zz = Fp.mul(Z, iz);\n if (is0)\n return { x: Fp.ZERO, y: Fp.ONE };\n if (!Fp.eql(zz, Fp.ONE))\n throw new Error('invZ was invalid');\n return { x, y };\n }\n clearCofactor() {\n if (cofactor === _1n)\n return this;\n // 2.8-3.8x speed-up vs naive\n if (cofactor === _2n)\n return this.double();\n if (cofactor === _4n)\n return this.double().double();\n if (cofactor === _8n)\n return this.double().double().double();\n return this.multiplyUnsafe(cofactor);\n }\n toBytes() {\n const { x, y } = this.toAffine();\n // Fp.toBytes() allows non-canonical encoding of y (>= p).\n const bytes = Fp.toBytes(y);\n // Each y has 2 valid points: (x, y), (x,-y).\n // When compressing, it's enough to store y and use the last byte to encode sign of x\n bytes[bytes.length - 1] |= isOdd(x) ? 0x80 : 0;\n return bytes;\n }\n toHex() {\n return bytesToHex(this.toBytes());\n }\n toString() {\n return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n }\n }\n // Keep constructor work cheap: subgroup/generator validation belongs to the caller's curve\n // parameters, and doing the extra checks here adds about 10-15ms to heavy module imports.\n // Callers that construct custom curves are responsible for supplying the correct base point.\n // try {\n // Point.BASE.assertValidity();\n // if (!Point.BASE.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');\n // } catch {\n // throw new Error('bad curve params: generator point');\n // }\n const normalize = (points) => normalizeZ(Point, points);\n const wnaf = new ScalarMultiplier(Point, randomBytes);\n // Enable W=6 wNAF precomputes. Slows down first publicKey computation.\n // Disable for tiny toy curves, with scalar fields < 6 bits.\n if (wnaf.bits >= 6)\n Point.BASE.precompute(6);\n Object.freeze(Point.prototype);\n Object.freeze(Point);\n return Point;\n}\n/**\n * Base class for prime-order points like Ristretto255 and Decaf448.\n * These points eliminate cofactor issues by representing equivalence classes\n * of Edwards curve points. Multiple Edwards representatives can describe the\n * same abstract wrapper element, so wrapper validity is not the same thing as\n * the hidden representative being torsion-free.\n * @param ep - Backing Edwards point.\n * @example\n * Base class for prime-order points like Ristretto255 and Decaf448.\n *\n * ```ts\n * import { ristretto255 } from '@noble/curves/ed25519.js';\n * const point = ristretto255.Point.BASE.multiply(2n);\n * ```\n */\nexport class PrimeEdwardsPoint {\n static BASE;\n static ZERO;\n static Fp;\n static Fn;\n ep;\n /**\n * Wrap one internal Edwards representative directly.\n * This is not a canonical encoding boundary: alternate Edwards\n * representatives may still describe the same abstract wrapper element.\n */\n constructor(ep) {\n this.ep = ep;\n }\n // Static methods that must be implemented by subclasses\n static fromBytes(_bytes) {\n notImplemented();\n }\n static fromHex(_hex) {\n notImplemented();\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n // Common implementations\n clearCofactor() {\n // no-op for the abstract prime-order wrapper group; this is about the\n // wrapper element, not the hidden Edwards representative.\n return this;\n }\n assertValidity() {\n // Keep wrapper validity at the abstract-group boundary. Canonical decode\n // may choose Edwards representatives that differ by small torsion, so\n // checking `this.ep.isTorsionFree()` here would reject valid wrapper points.\n this.ep.assertValidity();\n }\n /**\n * Return affine coordinates of the current internal Edwards representative.\n * This is a convenience helper, not a canonical Ristretto/Decaf encoding.\n * Equal abstract elements may expose different `x` / `y`; use\n * `toBytes()` / `fromBytes()` for canonical roundtrips.\n */\n toAffine(invertedZ) {\n return this.ep.toAffine(invertedZ);\n }\n toHex() {\n return bytesToHex(this.toBytes());\n }\n toString() {\n return this.toHex();\n }\n isTorsionFree() {\n // Abstract Ristretto/Decaf elements are already prime-order even when the\n // hidden Edwards representative is not torsion-free.\n return true;\n }\n isSmallOrder() {\n return false;\n }\n add(other) {\n this.assertSame(other);\n return this.init(this.ep.add(other.ep));\n }\n subtract(other) {\n this.assertSame(other);\n return this.init(this.ep.subtract(other.ep));\n }\n multiply(scalar) {\n return this.init(this.ep.multiply(scalar));\n }\n multiplyUnsafe(scalar) {\n return this.init(this.ep.multiplyUnsafe(scalar));\n }\n double() {\n return this.init(this.ep.double());\n }\n negate() {\n return this.init(this.ep.negate());\n }\n precompute(windowSize, isLazy) {\n this.ep.precompute(windowSize, isLazy);\n // Keep the wrapper identity stable like the backing Edwards API instead of\n // allocating a fresh wrapper around the same cached point.\n return this;\n }\n}\n/**\n * Initializes EdDSA signatures over given Edwards curve.\n * @param Point - Edwards point constructor.\n * @param cHash - Hash function.\n * @param eddsaOpts - Optional signature helpers. See {@link EdDSAOpts}.\n * @returns EdDSA helper namespace.\n * @throws If the hash function, options, or derived point operations are invalid. {@link Error}\n * @example\n * Initializes EdDSA signatures over given Edwards curve.\n *\n * ```ts\n * import { eddsa } from '@noble/curves/abstract/edwards.js';\n * import { jubjub } from '@noble/curves/misc.js';\n * import { sha512 } from '@noble/hashes/sha2.js';\n * const sigs = eddsa(jubjub.Point, sha512);\n * const { secretKey, publicKey } = sigs.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = sigs.sign(msg, secretKey);\n * const isValid = sigs.verify(sig, msg, publicKey);\n * ```\n */\nexport function eddsa(Point, cHash, eddsaOpts = {}) {\n validatePointCons(Point);\n if (typeof cHash !== 'function')\n throw new Error('\"hash\" function param is required');\n const hash = cHash;\n const opts = eddsaOpts;\n validateObject(opts, {}, {\n adjustScalarBytes: 'function',\n randomBytes: 'function',\n domain: 'function',\n prehash: 'function',\n zip215: 'boolean',\n mapToCurve: 'function',\n toMontgomery: 'function',\n toMontgomerySecret: 'function',\n });\n const { prehash } = opts;\n const { BASE, Fp, Fn } = Point;\n const outputLen = hash.outputLen;\n const expectedLen = 2 * Fp.BYTES;\n // When hash metadata is available, reject incompatible EdDSA wrappers at construction time\n // instead of deferring the mismatch until the first keygen/sign call.\n if (outputLen !== undefined) {\n asafenumber(outputLen, 'hash.outputLen');\n if (outputLen !== expectedLen)\n throw new Error(`hash.outputLen must be ${expectedLen}, got ${outputLen}`);\n }\n const randomBytes = opts.randomBytes === undefined ? wcRandomBytes : opts.randomBytes;\n const toMontgomery = opts.toMontgomery;\n const toMontgomerySecret = opts.toMontgomerySecret;\n const adjustScalarBytes = opts.adjustScalarBytes === undefined\n ? (bytes) => bytes\n : opts.adjustScalarBytes;\n const domain = opts.domain === undefined\n ? (data, ctx, phflag) => {\n abool(phflag, 'phflag');\n if (ctx.length || phflag)\n throw new Error('Contexts/pre-hash are not supported');\n return data;\n }\n : opts.domain; // NOOP\n // Parse an EdDSA digest as a little-endian integer and reduce it modulo the scalar field order.\n function modN_LE(hash) {\n return Fn.create(bytesToNumberLE(hash)); // Not Fn.fromBytes: it has length limit\n }\n // Get the hashed private scalar per RFC8032 5.1.5\n function getPrivateScalar(key) {\n const len = lengths.secretKey;\n abytes(key, lengths.secretKey, 'secretKey');\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 = abytes(hash(key), 2 * len, 'hashedSecretKey');\n // Slice before clamping so in-place adjustors don't corrupt the prefix half.\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 return { head, prefix, scalar };\n }\n /** Convenience method that creates public key from scalar. RFC8032 5.1.5\n * Also exposes the derived scalar/prefix tuple and point form reused by sign().\n */\n function getExtendedPublicKey(secretKey) {\n const { head, prefix, scalar } = getPrivateScalar(secretKey);\n const point = BASE.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toBytes();\n return { head, prefix, scalar, point, pointBytes };\n }\n /** Calculates EdDSA pub key. RFC8032 5.1.5. */\n function getPublicKey(secretKey) {\n return getExtendedPublicKey(secretKey).pointBytes;\n }\n // Hash domain-separated chunks into a little-endian scalar modulo the group order.\n function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {\n const msg = concatBytes(...msgs);\n return modN_LE(hash(domain(msg, abytes(context, undefined, 'context'), !!prehash)));\n }\n /** Signs message with secret key. RFC8032 5.1.6 */\n function sign(msg, secretKey, options = {}) {\n validateObject(options, {}, {}, 'options');\n // Snapshot once: nonce and challenge must use the same invocation-time message bytes.\n msg = copyBytes(abytes(msg, undefined, 'message'));\n if (prehash)\n msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n // RFC 8032 5.1.6 allows r mod L = 0, and SUPERCOP ref10 accepts the resulting identity-point\n // signature.\n // We intentionally keep the safe multiply() rejection here so a miswired all-zero hash provider\n // fails loudly instead of silently producing a degenerate signature.\n const R = BASE.multiply(r).toBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = Fn.create(r + k * scalar); // S = (r + k * s) mod L\n if (!Fn.isValid(s))\n throw new Error('sign failed: invalid s'); // 0 <= s < L\n const rs = concatBytes(R, Fn.toBytes(s));\n return abytes(rs, lengths.signature, 'result');\n }\n // Keep the shared helper strict by default: RFC 8032 / NIST-style wrappers should reject\n // non-canonical encodings unless they explicitly opt into ZIP-215's more permissive decode rules.\n const verifyOpts = {\n zip215: opts.zip215,\n };\n /**\n * Verifies EdDSA signature against message and public key. RFC 8032 \u00A7\u00A75.1.7 and 5.2.7.\n * A cofactored verification equation is checked.\n */\n function verify(sig, msg, publicKey, options = verifyOpts) {\n // Validate before destructuring so explicit null follows the standard options error.\n validateObject(options);\n // Preserve the wrapper-selected default for `{}` / `{ zip215: undefined }`, not just omitted opts.\n const { context } = options;\n const zip215 = options.zip215 === undefined ? !!verifyOpts.zip215 : options.zip215;\n const len = lengths.signature;\n sig = abytes(sig, len, 'signature');\n msg = abytes(msg, undefined, 'message');\n publicKey = abytes(publicKey, lengths.publicKey, 'publicKey');\n if (zip215 !== undefined)\n abool(zip215, 'zip215');\n if (prehash)\n msg = prehash(msg); // for ed25519ph, etc\n const mid = len / 2;\n const r = sig.subarray(0, mid);\n const s = bytesToNumberLE(sig.subarray(mid, len));\n let A, R, SB;\n try {\n // ZIP-215 is more permissive than RFC 8032 / NIST186-5. Use it only for wrappers that\n // explicitly want consensus-style unreduced encoding acceptance.\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n A = Point.fromBytes(publicKey, zip215);\n R = Point.fromBytes(r, zip215);\n SB = BASE.multiplyUnsafe(s); // 0 <= s < l is done inside\n }\n catch (error) {\n return false;\n }\n // RFC 8032 \u00A7\u00A75.1.7/5.2.7 and FIPS 186-5 \u00A7\u00A77.7.2/7.8.2 only decode A' and check the cofactored\n // verification equation; they do not add a separate low-order-public-key rejection here.\n // Strict mode still rejects small-order A' intentionally for SBS-style non-repudiation and to\n // avoid ambiguous verification outcomes where unusual low-order keys can make distinct\n // key/signature/message combinations verify.\n if (!zip215 && A.isSmallOrder())\n return false;\n // ZIP-215 accepts noncanonical / unreduced point encodings, so the challenge hash must use the\n // exact signature/public-key bytes rather than canonicalized re-encodings of the decoded points.\n const k = hashDomainToScalar(context, r, publicKey, msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // Check the cofactored verification equation via the curve cofactor h.\n // [h][S]B = [h]R + [h][k]A'\n return RkA.subtract(SB).clearCofactor().is0();\n }\n const _size = Fp.BYTES; // 32 for ed25519, 57 for ed448\n const lengths = {\n secretKey: _size,\n publicKey: _size,\n signature: 2 * _size,\n seed: _size,\n };\n function randomSecretKey(seed) {\n seed = seed === undefined ? randomBytes(lengths.seed) : seed;\n return abytes(seed, lengths.seed, 'seed');\n }\n function isValidSecretKey(key) {\n return isBytes(key) && key.length === lengths.secretKey;\n }\n function isValidPublicKey(key, zip215) {\n try {\n // Preserve the wrapper-selected default for omitted / `undefined` ZIP-215 flags here too.\n return !!Point.fromBytes(key, zip215 === undefined ? verifyOpts.zip215 : zip215);\n }\n catch (error) {\n return false;\n }\n }\n const utils = {\n getExtendedPublicKey,\n randomSecretKey,\n isValidSecretKey,\n isValidPublicKey,\n /** Converts an Edwards public key to a companion Montgomery public key. */\n toMontgomery(publicKey) {\n if (toMontgomery === undefined)\n throw new Error('Montgomery conversion is not supported for this curve');\n return toMontgomery(Point.fromBytes(publicKey));\n },\n toMontgomerySecret(secretKey) {\n if (toMontgomerySecret === undefined)\n throw new Error('Montgomery conversion is not supported for this curve');\n return toMontgomerySecret(secretKey);\n },\n };\n Object.freeze(lengths);\n Object.freeze(utils);\n return Object.freeze({\n keygen: createKeygen(randomSecretKey, getPublicKey),\n getPublicKey,\n sign,\n verify,\n utils,\n Point,\n lengths,\n });\n}\n", "/**\n * Montgomery curve methods. It's not really whole montgomery curve,\n * just bunch of very specific methods for X25519 / X448 from\n * [RFC 7748](https://www.rfc-editor.org/rfc/rfc7748)\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abytes, aInRange, bytesToNumberLE, copyBytes, numberToBytesLE, randomBytes, validateObject, } from \"../utils.js\";\nimport { createKeygen } from \"./curve.js\";\nimport { mod } from \"./modular.js\";\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\n// cswap from RFC7748 \"example code\", adapted to BigInt.\n//\n// RFC: \"dummy = mask(swap) AND (x_2 XOR x_3), where mask(swap) is the all-1 or all-0 word of the\n// same length as x_2 and x_3\". On fixed-width machine words both cases cost the same. BigInt has\n// no fixed width, so a {0n, 1n} selector does not: V8 short-circuits `0n * v` - and, identically,\n// `0n & v`, `v + 0n`, `v - 0n` - to a no-op, while `1n * v` is a real multiply. The ladder calls\n// this with swap = k_t XOR k_(t+1), which would make total running time a linear function of how\n// often adjacent bits of the secret scalar differ: remotely measurable, and worth ~4 bits of a\n// long-term key.\n//\n// So select with a full-width mask instead, and interpolate rather than mask off a dummy.\n/**\n * Selector for cswap(): `P` to keep, `P + 1` to swap, chosen by the low bit of `swap`.\n * Higher bits are ignored, and `swap` is passed in whole rather than as a {0n, 1n} bit on\n * purpose: `P + (swap & _1n)` would short-circuit the addition whenever the bit is clear, which\n * is the very leak this construction avoids, one round-trip further down. Subtracting `swap`\n * with its low bit cleared keeps every operand full-width instead.\n * @param P - Field modulus.\n * @param swap - Value whose low bit selects; ignored above that bit.\n * @returns `P` when the low bit is clear, `P + 1` when it is set.\n */\nfunction cmask(P, swap) {\n return P + swap - ((swap >> _1n) << _1n);\n}\n/**\n * Swap two field elements when `mask` is `P + 1`, keep them when it is `P`:\n *\n * d = 6P + x_3 - x_2\n * x_2' = d * mask + x_2 (mod P) x_3' = (x_2 + x_3) - x_2'\n *\n * The extra `6P * mask` vanishes modulo P, so `mask === P` leaves x_2 and `mask === P + 1`\n * leaves x_3. Without the offset, the reduction dividend changes sign with input order and crosses\n * BigInt limb boundaries; those classes measured differently on the tested Node/V8 build. For\n * canonical inputs, the deliberately left-associative `offset + x_3 - x_2` is between 5P and 7P,\n * keeping the dividend positive and in one word-count band for both RFC fields and masks. Six is\n * the smallest coefficient `c` for which the shared offset `cP` has that property.\n *\n * This reduced the tested sign/size timing ratios, but JavaScript BigInt has no constant-time\n * contract and the contents of the multiply and remainder still vary. Valid ladder states can\n * contain genuine zero coordinates; this construction does not mask those value-shape effects.\n * Computing `x_3'` independently as `((6P + x_2 - x_3) * mask + x_3) % P` is more symmetric.\n * On the tested Node/V8 build, it reduced the timing difference between keeping `(0, v)` and\n * swapping `(v, 0)`\u2014both return `(0, v)`\u2014from about 10%/13% for X25519/X448 to about 3%.\n * Successful calls cannot reach that zero-in-the-first-output case. For the case they can reach,\n * swapping `(0, v)` and keeping `(v, 0)` both return `(v, 0)`; the difference instead grew from\n * about 0.7%/1.1% to 2.7%/2.8%. The extra multiply/remainder also made public\n * `getSharedSecret()` about 16% slower. The retained one-remainder form measured about 2.5%\n * slower than the prior helper for public X25519 `getSharedSecret()` in the same environment.\n * x_3' falls out of the sum, which a swap leaves invariant: no second multiply or reduction is\n * needed. Bind `6P` once per field so production and the timing regression exercise the same\n * configured helper without paying for the multiplication in every ladder round.\n *\n * The returned function is called twice per ladder round, so it validates nothing. Both elements\n * MUST already be reduced mod P; unreduced input silently corrupts the kept-side output.\n * @param P - Field modulus.\n * @returns A field-bound swap function taking mask, x_2, and x_3.\n */\nfunction cswap(P) {\n const offset = BigInt(6) * P;\n return (mask, x_2, x_3) => {\n const sum = x_2 + x_3;\n const d = offset + x_3 - x_2;\n const a = (d * mask + x_2) % P;\n return { x_2: a, x_3: sum - a };\n };\n}\n/** Internal helpers, exported for tests only. Not part of the public API. */\nexport const __TEST = /* @__PURE__ */ Object.freeze({\n cmask,\n cswap,\n});\nfunction validateOpts(curve) {\n // Validate constructor config eagerly, but do not call user-provided hooks here:\n // `randomBytes` may be transcript-backed or otherwise contextual. Runtime type checks are\n // enough to fail fast on malformed configs without consuming user state.\n validateObject(curve, {\n P: 'bigint',\n type: 'string',\n adjustScalarBytes: 'function',\n powPminus2: 'function',\n }, {\n randomBytes: 'function',\n scalarMultBase: 'function',\n });\n return Object.freeze({ ...curve });\n}\n/**\n * @param curveDef - Montgomery curve definition.\n * @returns ECDH helper namespace.\n * @throws If the curve definition or derived shared point is invalid. {@link Error}\n * @example\n * Build an X25519 helper from curve parameters, then derive one public key.\n *\n * ```ts\n * import { montgomery } from '@noble/curves/abstract/montgomery.js';\n * const P = 2n ** 255n - 19n;\n * const mod = (num: bigint) => {\n * const out = num % P;\n * return out >= 0n ? out : out + P;\n * };\n * const pow = (num: bigint, power: bigint) => {\n * let res = 1n;\n * for (; power > 0n; power >>= 1n) {\n * if (power & 1n) res = mod(res * num);\n * num = mod(num * num);\n * }\n * return res;\n * };\n * const x25519 = montgomery({\n * P,\n * type: 'x25519',\n * adjustScalarBytes(bytes: Uint8Array) {\n * bytes[0] &= 248;\n * bytes[31] &= 127;\n * bytes[31] |= 64;\n * return bytes;\n * },\n * powPminus2(x) {\n * return pow(x, P - 2n);\n * },\n * });\n * const publicKey = x25519.getPublicKey(new Uint8Array(32).fill(1));\n * ```\n */\nexport function montgomery(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { P, type, adjustScalarBytes, powPminus2, randomBytes: rand } = CURVE;\n const mulBaseHook = CURVE.scalarMultBase;\n const is25519 = type === 'x25519';\n if (!is25519 && type !== 'x448')\n throw new Error('invalid type');\n const randomBytes_ = rand === undefined ? randomBytes : rand;\n const montgomeryBits = is25519 ? 255 : 448;\n const swap = cswap(P);\n const fieldLen = is25519 ? 32 : 56;\n const Gu = is25519 ? BigInt(9) : BigInt(5);\n // RFC 7748 #5:\n // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 and\n // (156326 - 2) / 4 = 39081 for curve448/X448\n // const a = is25519 ? 486662n : 156326n;\n const a24 = is25519 ? BigInt(121665) : BigInt(39081);\n // RFC: x25519 \"the resulting integer is of the form 2^254 plus\n // eight times a value between 0 and 2^251 - 1 (inclusive)\"\n // x448: \"2^447 plus four times a value between 0 and 2^445 - 1 (inclusive)\"\n const minScalar = is25519 ? _2n ** BigInt(254) : _2n ** BigInt(447);\n const maxAdded = is25519\n ? BigInt(8) * (_2n ** BigInt(251) - _1n)\n : BigInt(4) * (_2n ** BigInt(445) - _1n);\n const maxScalar = minScalar + maxAdded + _1n; // (inclusive)\n const modP = (n) => mod(n, P);\n const GuBytes = encodeU(Gu);\n function encodeU(u) {\n return numberToBytesLE(modP(u), fieldLen);\n }\n function decodeU(u) {\n const _u = copyBytes(abytes(u, fieldLen, 'uCoordinate'));\n // RFC: When receiving such an array, implementations of X25519\n // (but not X448) MUST mask the most significant bit in the final byte.\n if (is25519)\n _u[31] &= 127; // 0b0111_1111\n // RFC: Implementations MUST accept non-canonical values and process them as\n // if they had been reduced modulo the field prime. The non-canonical\n // values are 2^255 - 19 through 2^255 - 1 for X25519 and 2^448 - 2^224\n // - 1 through 2^448 - 1 for X448.\n return modP(bytesToNumberLE(_u));\n }\n function decodeScalar(scalar) {\n return bytesToNumberLE(adjustScalarBytes(copyBytes(abytes(scalar, fieldLen, 'scalar'))));\n }\n /**\n * u coordinates whose order divides the cofactor, on the curve and on its quadratic twist -\n * the ladder sends every one of them to zero. Same blocklist libsodium and post-CVE-2017-0379\n * Libgcrypt carry. decodeU() reduces mod P first, so the non-canonical encodings P and P + 1\n * collapse onto 0 and 1, and `type` admits no curve beyond these two, so both lists are total.\n *\n * Complete by construction: x-only doubling sends u to (u^2 - 1)^2 / 4u(u^2 + a*u + 1). Order 4\n * therefore needs (u^2 - 1)^2 === 0, i.e. u = +-1; order 2 needs u(u^2 + a*u + 1) === 0, and\n * a^2 - 4 is a non-residue on both curves, leaving u = 0. curve448 stops there (cofactor 4);\n * curve25519 (cofactor 8) adds the two order-8 roots below. Cross-checked by clearing the\n * cofactor with those same doublings over 200k random u: no sixth value exists.\n */\n const lowOrderU = new Set(is25519\n ? [\n _0n,\n _1n,\n P - _1n,\n BigInt('325606250916557431795983626356110631294008115727848805560023387167927233504'),\n BigInt('39382357235489614581723060781553021112529911719440698176882885853963445705823'),\n ]\n : [_0n, _1n, P - _1n]);\n function scalarMult(scalar, u) {\n // Some public keys are useless, of low-order. Curve author doesn't think\n // it needs to be validated, but we do it nonetheless.\n // https://cr.yp.to/ecdh.html#validate\n //\n // Reject them BEFORE the ladder. RFC 7748 #6.1 also permits detecting them from the\n // all-zero output, but that first runs all 255 rounds against the long-term secret,\n // handing an unauthenticated attacker a free timing oracle. Low-order inputs also drive\n // the ladder into a degenerate state (x_2 + z_2 === 0) whose extra zero-operand\n // multiplications amplify any residual key-dependent timing.\n const pointU = decodeU(u);\n if (lowOrderU.has(pointU))\n throw new Error('invalid private or public key received');\n const pu = montgomeryLadder(pointU, decodeScalar(scalar));\n // Unreachable for RFC 7748 clamped scalars, which are cofactor multiples smaller than the\n // group order; kept because adjustScalarBytes is caller-supplied.\n if (pu === _0n)\n throw new Error('invalid private or public key received');\n return encodeU(pu);\n }\n // Computes public key from private. By doing scalar multiplication of base point.\n // With a curve-provided fixed-base hook (Edwards tables), the ladder is skipped, but the\n // contract \u2014 scalar validation, low-order rejection, encoding \u2014 stays identical.\n function scalarMultBase(scalar) {\n if (mulBaseHook === undefined)\n return scalarMult(scalar, GuBytes);\n const k = decodeScalar(scalar);\n aInRange('scalar', k, minScalar, maxScalar);\n const pu = modP(mulBaseHook(k));\n if (pu === _0n)\n throw new Error('invalid private or public key received');\n return encodeU(pu);\n }\n const getPublicKey = scalarMultBase;\n const getSharedSecret = scalarMult;\n /**\n * Montgomery x-only multiplication ladder for the selected X25519/X448 curve.\n * @param pointU - decoded Montgomery u coordinate for the selected curve\n * @param scalar - decoded clamped scalar by which the point is multiplied\n * @returns resulting Montgomery u coordinate for the selected curve\n */\n function montgomeryLadder(u, scalar) {\n aInRange('u', u, _0n, P);\n aInRange('scalar', scalar, minScalar, maxScalar);\n const k = 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 // The RFC tracks `swap` across rounds to hold k_t XOR k_(t+1); the low bit of `kx >> t` is\n // the same value, without the carried state. aInRange above pins bit (montgomeryBits - 1)\n // of k set and everything above it clear, so `kx >> t` is never zero and its width is a\n // function of t alone - never of a secret bit.\n const kx = k ^ (k >> _1n);\n for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {\n const mask = cmask(P, kx >> t);\n ({ x_2, x_3 } = swap(mask, x_2, x_3));\n ({ x_2: z_2, x_3: z_3 } = swap(mask, z_2, z_3));\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 // trailing cswap: the RFC's `swap` holds k_0 here, which is the low bit of k\n const mask = cmask(P, k);\n ({ x_2, x_3 } = swap(mask, x_2, x_3));\n ({ x_2: z_2, x_3: z_3 } = swap(mask, z_2, z_3));\n const z2 = powPminus2(z_2); // `Fp.pow(x, P - _2n)` is much slower equivalent\n return modP(x_2 * z2); // Return x_2 * (z_2^(p - 2))\n }\n const lengths = {\n secretKey: fieldLen,\n publicKey: fieldLen,\n seed: fieldLen,\n };\n const randomSecretKey = (seed) => {\n seed = seed === undefined ? randomBytes_(fieldLen) : seed;\n abytes(seed, lengths.seed, 'seed');\n // Reuse caller-supplied seed bytes verbatim; clamping is deferred until\n // decodeScalar(...) when the secret key is actually used.\n return seed;\n };\n const utils = { randomSecretKey };\n Object.freeze(lengths);\n Object.freeze(utils);\n return Object.freeze({\n keygen: createKeygen(randomSecretKey, getPublicKey),\n getSharedSecret,\n getPublicKey,\n scalarMult,\n scalarMultBase,\n utils,\n GuBytes: GuBytes.slice(),\n lengths,\n });\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 * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, concatBytes, hexToBytes } from '@noble/hashes/utils.js';\nimport {} from \"./abstract/curve.js\";\nimport { eddsa, edwards, PrimeEdwardsPoint, } from \"./abstract/edwards.js\";\nimport { createFROST } from \"./abstract/frost.js\";\nimport { _DST_scalar, createHasher, expand_message_xmd, } from \"./abstract/hash-to-curve.js\";\nimport { FpInvertBatch, FpSqrtEven, isNegativeLE, mod, pow2, } from \"./abstract/modular.js\";\nimport { montgomery } from \"./abstract/montgomery.js\";\nimport { createOPRF } from \"./abstract/oprf.js\";\nimport { asciiToBytes, bytesToNumberLE, equalBytes } from \"./utils.js\";\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _5n = /* @__PURE__ */ BigInt(5), _8n = /* @__PURE__ */ BigInt(8);\n// P = 2n**255n - 19n\nconst ed25519_CURVE_p = /* @__PURE__ */ BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed');\n// N = 2n**252n + 27742317777372353535851937790883648493n\n// a = Fp.create(BigInt(-1))\n// d = -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666))\nconst ed25519_CURVE = /* @__PURE__ */ (() => ({\n p: ed25519_CURVE_p,\n n: BigInt('0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed'),\n h: _8n,\n a: BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec'),\n d: BigInt('0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3'),\n Gx: BigInt('0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a'),\n Gy: BigInt('0x6666666666666666666666666666666666666666666666666666666666666658'),\n}))();\nfunction ed25519_pow_2_252_3(x) {\n // prettier-ignore\n const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n const P = ed25519_CURVE_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 // ^ This is x^((p-5)/8); multiply by x once more to get x^((p+3)/8).\n return { pow_p_5_8, b2 };\n}\n// Mutates and returns the provided 32-byte buffer in place.\nfunction adjustScalarBytes(bytes) {\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// \u221A(-1) aka \u221A(a) aka 2^((p-1)/4)\n// Fp.sqrt(Fp.neg(1))\nconst ED25519_SQRT_M1 = /* @__PURE__ */ BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');\n// sqrt(u/v). Returns `{ isValid, value }`; on non-squares `value` is still a\n// dummy root-shaped field element so callers can stay constant-time.\nfunction uvRatio(u, v) {\n const P = ed25519_CURVE_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)\n x = root1;\n if (useRoot2 || noRoot)\n x = root2; // We return root2 anyway, for const-time\n if (isNegativeLE(x, P))\n x = mod(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\nconst ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE, { uvRatio });\n// Public field alias stays stricter than the RFC 8032 Appendix A sample code:\n// `Fp.inv(0)` throws instead of returning `0`.\nconst Fp = /* @__PURE__ */ (() => ed25519_Point.Fp)();\nfunction toMontgomery(point) {\n // Birational map from Ed25519 to Curve25519 / X25519:\n // (u, v) = ((1 + y) / (1 - y), sqrt(-486664) * u / x)\n // (x, y) = (sqrt(-486664) * u / v, (u - 1) / (u + 1))\n const { y } = point;\n return Fp.toBytes(Fp.div(_1n + y, _1n - y));\n}\nfunction toMontgomerySecret(secretKey) {\n const size = ed25519_Point.Fp.BYTES;\n abytes(secretKey, size);\n return adjustScalarBytes(sha512(secretKey.subarray(0, size))).subarray(0, size);\n}\nconst Fn = /* @__PURE__ */ (() => ed25519_Point.Fn)();\n// RFC 8032 `dom2` helper for ctx/ph variants only. Plain Ed25519 keeps the\n// empty-domain path in `ed()` and would be wrong if routed through this helper.\nfunction ed25519_domain(data, ctx, phflag) {\n if (ctx.length > 255)\n throw new Error('Context is too big');\n return concatBytes(asciiToBytes('SigEd25519 no Ed25519 collisions'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);\n}\nfunction ed(opts) {\n // Ed25519 keeps ZIP-215 default verification semantics for consensus compatibility.\n return eddsa(ed25519_Point, sha512, Object.assign({ adjustScalarBytes, toMontgomery, toMontgomerySecret, zip215: true }, opts));\n}\n/**\n * ed25519 curve with EdDSA signatures.\n * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided\n * 32-byte seed buffer instead of copying it.\n * @example\n * Generate one Ed25519 keypair, sign a message, and verify it.\n *\n * ```js\n * import { ed25519 } from '@noble/curves/ed25519.js';\n * const { secretKey, publicKey } = ed25519.keygen();\n * // const publicKey = ed25519.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ed25519.sign(msg, secretKey);\n * const isValid = ed25519.verify(sig, msg, publicKey); // ZIP215\n * // RFC8032 / FIPS 186-5\n * const isValid2 = ed25519.verify(sig, msg, publicKey, { zip215: false });\n * ```\n */\nexport const ed25519 = /* @__PURE__ */ ed({});\n/**\n * Context version of ed25519 (ctx for domain separation). See {@link ed25519}\n * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided\n * 32-byte seed buffer instead of copying it.\n * @example\n * Sign and verify with Ed25519ctx under one explicit context.\n *\n * ```ts\n * const context = new TextEncoder().encode('docs');\n * const { secretKey, publicKey } = ed25519ctx.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ed25519ctx.sign(msg, secretKey, { context });\n * const isValid = ed25519ctx.verify(sig, msg, publicKey, { context });\n * ```\n */\nexport const ed25519ctx = /* @__PURE__ */ ed({ domain: ed25519_domain });\n/**\n * Prehashed version of ed25519. See {@link ed25519}\n * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided\n * 32-byte seed buffer instead of copying it.\n * @example\n * Use the prehashed Ed25519 variant for one message.\n *\n * ```ts\n * const { secretKey, publicKey } = ed25519ph.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ed25519ph.sign(msg, secretKey);\n * const isValid = ed25519ph.verify(sig, msg, publicKey);\n * ```\n */\nexport const ed25519ph = /* @__PURE__ */ ed({ domain: ed25519_domain, prehash: sha512 });\n/**\n * FROST threshold signatures over ed25519. RFC 9591.\n * @example\n * Create one trusted-dealer package for 2-of-3 ed25519 signing.\n *\n * ```ts\n * const alice = ed25519_FROST.Identifier.derive('alice@example.com');\n * const bob = ed25519_FROST.Identifier.derive('bob@example.com');\n * const carol = ed25519_FROST.Identifier.derive('carol@example.com');\n * const deal = ed25519_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const ed25519_FROST = /* @__PURE__ */ (() => createFROST({\n name: 'FROST-ED25519-SHA512-v1',\n Point: ed25519_Point,\n validatePoint: (p) => {\n p.assertValidity();\n if (!p.isTorsionFree())\n throw new Error('bad point: not torsion-free');\n },\n hash: sha512,\n // RFC 9591 keeps H2 undecorated here for RFC 8032 compatibility. In createFROST(),\n // `H2: ''` becomes an empty DST prefix; the built-in hashToScalar fallback treats\n // that the same as omitted DST, even though custom hooks can still observe the empty bag.\n H2: '',\n}))();\n/**\n * ECDH using curve25519 aka x25519.\n * `getSharedSecret()` rejects low-order peer inputs by default, and seeded\n * `keygen(seed)` reuses the provided 32-byte seed buffer instead of copying it.\n * @example\n * Derive one shared secret between two X25519 peers.\n *\n * ```js\n * import { x25519 } from '@noble/curves/ed25519.js';\n * const alice = x25519.keygen();\n * const bob = x25519.keygen();\n * const alicePublic = x25519.getPublicKey(alice.secretKey);\n * const shared = x25519.getSharedSecret(alice.secretKey, bob.publicKey);\n * ```\n */\nexport const x25519 = /* @__PURE__ */ (() => {\n const P = ed25519_CURVE_p;\n const powPminus2 = (x) => {\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, _3n, P) * b2, P);\n };\n return montgomery({\n P,\n type: 'x25519',\n powPminus2,\n adjustScalarBytes,\n // ~3x faster fixed-base: [k]B on the birationally-equivalent Edwards curve using cached\n // base tables, mapped back via u = (1+y)/(1-y) = (Z+Y)/(Z-Y) with one Fermat inversion.\n // Same construction as libsodium's crypto_scalarmult_curve25519_base.\n scalarMultBase: (k) => {\n // Clamped k (\u22482^254) exceeds n, but B has prime order n, so [k]B == [k mod n]B.\n const kn = mod(k, ed25519_Point.Fn.ORDER);\n // k \u2261 0 (mod n): [k]B is the point at infinity, whose u is 0 in the x-only ladder;\n // returning 0 makes montgomery() reject it exactly like the ladder path.\n if (kn === _0n)\n return _0n;\n const p = ed25519_Point.BASE.multiply(kn);\n // Z-Y == 0 only at the identity, which kn != 0 excludes.\n return mod((p.Z + p.Y) * powPminus2(mod(p.Z - p.Y, P)), P);\n },\n });\n})();\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// RFC 9380 Appendix G.2.2 / Err4730 requires `sgn0(c1) = 0` for the Edwards\n// map constant below, so use the even root explicitly.\n// 1. c1 = (q + 3) / 8 # Integer arithmetic\nconst ELL2_C1 = /* @__PURE__ */ (() => (ed25519_CURVE_p + _3n) / _8n)();\nconst ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1\nconst ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1)\nconst ELL2_J = /* @__PURE__ */ BigInt(486662);\n/**\n * RFC 9380 method `map_to_curve_elligator2_curve25519`. Experimental name: may be renamed later.\n * @private\n */\n// prettier-ignore\nexport function _map_to_curve_elligator2_curve25519(u) {\n // 4. c4 = (q - 5) / 8: tv2^c4 below reuses the ed25519_pow_2_252_3 addition chain,\n // whose pow_p_5_8 output is exactly x^((p-5)/8).\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let xd = Fp.add(tv1, Fp.ONE);\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 = ed25519_pow_2_252_3(tv2).pow_p_5_8; // 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 // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let y1 = Fp.cmov(y12, y11, e1);\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 // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n let y2 = Fp.cmov(y22, y21, e2);\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// sgn0(c1) MUST equal 0\nconst ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))();\nfunction map_to_curve_elligator2_edwards25519(u) {\n // 1. (xMn, xMd, yMn, yMd) = map_to_curve_elligator2_curve25519(u)\n const { xMn, xMd, yMn, yMd } = _map_to_curve_elligator2_curve25519(u);\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 // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let yd = Fp.add(xMn, xMd);\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 const [xd_inv, yd_inv] = FpInvertBatch(Fp, [xd, yd], true); // batch division\n // Noble normalizes the RFC rational representation to affine `{ x, y }`\n // before returning from the internal helper.\n return { x: Fp.mul(xn, xd_inv), y: Fp.mul(yn, yd_inv) }; // 13. return (xn, xd, yn, yd)\n}\n/**\n * Hashing to ed25519 points / field. RFC 9380 methods.\n * Public `mapToCurve()` returns the cofactor-cleared subgroup point; the\n * internal map callback below consumes one field element bigint, not `[bigint]`.\n * @example\n * Hash one message onto the ed25519 curve.\n *\n * ```ts\n * const point = ed25519_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const ed25519_hasher = /* @__PURE__ */ (() => createHasher(ed25519_Point, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: ed25519_CURVE_p,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\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 = /* @__PURE__ */ BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235');\n// 1 / \u221A(a-d)\nconst INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578');\n// 1-d\u00B2\nconst ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838');\n// (d-1)\u00B2\nconst D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952');\n// `SQRT_RATIO_M1(1, number)` specialization. Returns `{ isValid, value }`,\n// where non-squares get the nonnegative `sqrt(SQRT_M1 / number)` branch.\nconst invertSqrt = (number) => uvRatio(_1n, number);\nconst MAX_255B = /* @__PURE__ */ BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\n// RFC 9496 \u00A74.3.4 MAP parser: masks bit 255 and reduces modulo p for element\n// derivation. The decode path has the opposite contract and rejects that bit.\nconst bytes255ToNumberLE = (bytes) => Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n/**\n * Computes Elligator map for Ristretto255.\n * Primary formula source is RFC 9496 \u00A74.3.4 MAP; RFC 9380 Appendix B builds\n * `hash_to_ristretto255` on top of this helper.\n * Returns an internal Edwards representative, not a public `_RistrettoPoint`.\n */\nfunction calcElligatorRistrettoMap(r0) {\n const { d } = ed25519_CURVE;\n const r = Fp.mul(Fp.mulN(SQRT_M1, r0), r0); // 1\n const Ns = Fp.mul(Fp.addN(r, _1n), ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = Fp.mul(Fp.subN(c, Fp.mulN(d, r)), Fp.add(r, d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = Fp.mul(s, r0); // 6\n if (!Fp.isOdd(s_))\n s_ = Fp.neg(s_);\n if (!Ns_D_is_sq)\n s = s_; // 7\n if (!Ns_D_is_sq)\n c = r; // 8\n const Nt = Fp.sub(Fp.mulN(Fp.mulN(c, Fp.subN(r, _1n)), D_MINUS_ONE_SQ), D); // 9\n const s2 = Fp.sqrN(s);\n const W0 = Fp.mul(Fp.addN(s, s), D); // 10\n const W1 = Fp.mul(Nt, SQRT_AD_MINUS_ONE); // 11\n const W2 = Fp.sub(_1n, s2); // 12\n const W3 = Fp.add(_1n, s2); // 13\n return new ed25519_Point(Fp.mul(W0, W3), Fp.mul(W2, W1), Fp.mul(W1, W3), Fp.mul(W0, W2));\n}\n/**\n * Wrapper over Edwards Point for ristretto255.\n *\n * Each ed25519/EdwardsPoint 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 EdwardsPoint,\n * but it should work in its own namespace: do not combine those two.\n * See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496).\n */\nclass _RistrettoPoint extends PrimeEdwardsPoint {\n // Do NOT change syntax: the following gymnastics is done,\n // because typescript strips comments, which makes bundlers disable tree-shaking.\n // prettier-ignore\n static BASE = \n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.BASE))();\n // prettier-ignore\n static ZERO = \n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.ZERO))();\n // prettier-ignore\n static Fp = \n /* @__PURE__ */ (() => Fp)();\n // prettier-ignore\n static Fn = \n /* @__PURE__ */ (() => Fn)();\n constructor(ep) {\n super(ep);\n }\n /**\n * Create one Ristretto255 point from affine Edwards coordinates.\n * This wraps the internal Edwards representative directly and is not a\n * canonical ristretto255 decoding path.\n * Use `toBytes()` / `fromBytes()` if canonical ristretto255 bytes matter.\n */\n static fromAffine(ap) {\n return new _RistrettoPoint(ed25519_Point.fromAffine(ap));\n }\n assertSame(other) {\n if (!(other instanceof _RistrettoPoint))\n throw new Error('RistrettoPoint expected');\n }\n init(ep) {\n return new _RistrettoPoint(ep);\n }\n static fromBytes(bytes) {\n abytes(bytes, 32);\n const { a, d } = ed25519_CURVE;\n const s = bytes255ToNumberLE(bytes);\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(Fp.toBytes(s), bytes) || Fp.isOdd(s))\n throw new Error('invalid ristretto255 encoding 1');\n const s2 = Fp.sqr(s);\n const u1 = Fp.add(_1n, Fp.mulN(a, s2)); // 4 (a is -1)\n const u2 = Fp.sub(_1n, Fp.mulN(a, s2)); // 5\n const u1_2 = Fp.sqr(u1);\n const u2_2 = Fp.sqr(u2);\n const v = Fp.sub(Fp.mulN(Fp.mulN(a, d), u1_2), u2_2); // 6\n const { isValid, value: I } = invertSqrt(Fp.mul(v, u2_2)); // 7\n const Dx = Fp.mul(I, u2); // 8\n const Dy = Fp.mul(Fp.mulN(I, Dx), v); // 9\n let x = Fp.mul(Fp.addN(s, s), Dx); // 10\n if (Fp.isOdd(x))\n x = Fp.neg(x); // 10\n const y = Fp.mul(u1, Dy); // 11\n const t = Fp.mul(x, y); // 12\n if (!isValid || Fp.isOdd(t) || Fp.is0(y))\n throw new Error('invalid ristretto255 encoding 2');\n return new _RistrettoPoint(new ed25519_Point(x, y, Fp.ONE, t));\n }\n /**\n * Converts ristretto-encoded string to ristretto point.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).\n * @param hex - Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex) {\n return _RistrettoPoint.fromBytes(hexToBytes(hex));\n }\n /**\n * Encodes ristretto point to Uint8Array.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).\n */\n toBytes() {\n let { X, Y, Z, T } = this.ep;\n const u1 = Fp.mul(Fp.add(Z, Y), Fp.sub(Z, Y)); // 1\n const u2 = Fp.mul(X, Y); // 2\n // Square root always exists\n const u2sq = Fp.sqr(u2);\n const { value: invsqrt } = invertSqrt(Fp.mul(u1, u2sq)); // 3\n const D1 = Fp.mul(invsqrt, u1); // 4\n const D2 = Fp.mul(invsqrt, u2); // 5\n const zInv = Fp.mul(Fp.mulN(D1, D2), T); // 6\n let D; // 7\n if (Fp.isOdd(Fp.mul(T, zInv))) {\n let _x = Fp.mul(Y, SQRT_M1);\n let _y = Fp.mul(X, SQRT_M1);\n X = _x;\n Y = _y;\n D = Fp.mul(D1, INVSQRT_A_MINUS_D);\n }\n else {\n D = D2; // 8\n }\n if (Fp.isOdd(Fp.mul(X, zInv)))\n Y = Fp.neg(Y); // 9\n let s = Fp.mul(Fp.subN(Z, Y), D); // 10 (check footer's note, no sqrt(-a))\n if (Fp.isOdd(s))\n s = Fp.neg(s);\n return Fp.toBytes(s); // 11\n }\n /**\n * Compares two Ristretto points.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).\n */\n equals(other) {\n this.assertSame(other);\n const { X: X1, Y: Y1 } = this.ep;\n const { X: X2, Y: Y2 } = other.ep;\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = Fp.eql(Fp.mul(X1, Y2), Fp.mul(Y1, X2));\n const two = Fp.eql(Fp.mul(Y1, Y2), Fp.mul(X1, X2));\n return one || two;\n }\n is0() {\n return this.equals(_RistrettoPoint.ZERO);\n }\n}\n/** Prime-order Ristretto255 group bundle. */\nexport const ristretto255 = /* @__PURE__ */ (() => {\n Object.freeze(_RistrettoPoint.BASE);\n Object.freeze(_RistrettoPoint.ZERO);\n Object.freeze(_RistrettoPoint.prototype);\n Object.freeze(_RistrettoPoint);\n return Object.freeze({ Point: _RistrettoPoint });\n})();\n/**\n * Hashing to ristretto255 points / field. RFC 9380 methods.\n * `hashToCurve()` is RFC 9380 Appendix B, `deriveToCurve()` is the RFC 9496\n * \u00A74.3.4 element-derivation building block, and `hashToScalar()` is a\n * library-specific helper for OPRF-style use.\n * @example\n * Hash one message onto ristretto255.\n *\n * ```ts\n * const point = ristretto255_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const ristretto255_hasher = \n/* @__PURE__ */ Object.freeze({\n Point: _RistrettoPoint,\n /**\n * Spec: https://www.rfc-editor.org/rfc/rfc9380.html#name-hashing-to-ristretto255. Caveats:\n * * There are no test vectors\n * * encodeToCurve / mapToCurve is undefined\n * * mapToCurve would be `calcElligatorRistrettoMap(scalars[0])`, not ristretto255_map!\n * * hashToScalar is undefined too, so we just use OPRF implementation\n * * We cannot re-use 'createHasher', because ristretto255_map is different algorithm/RFC\n (os2ip -> bytes255ToNumberLE)\n * * mapToCurve == calcElligatorRistrettoMap, hashToCurve == ristretto255_map\n * * hashToScalar is undefined in RFC9380 for ristretto, so we use the OPRF\n version here. Using `bytes255ToNumblerLE` will create a different result\n if we use `bytes255ToNumberLE` as os2ip\n * * current version is closest to spec.\n */\n hashToCurve(msg, options) {\n // == 'hash_to_ristretto255'\n // Preserve explicit empty/invalid DST overrides so expand_message_xmd() can reject them.\n const DST = options?.DST === undefined ? 'ristretto255_XMD:SHA-512_R255MAP_RO_' : options.DST;\n const xmd = expand_message_xmd(msg, DST, 64, sha512);\n // NOTE: RFC 9380 incorrectly calls this function `ristretto255_map`.\n // In RFC 9496, `map` was the per-point function inside the construction.\n // That also led to confusion that `ristretto255_map` is `mapToCurve`.\n // It is not: it is the older hash-to-curve construction.\n return ristretto255_hasher.deriveToCurve(xmd);\n },\n hashToScalar(msg, options) {\n const DST = options?.DST === undefined ? _DST_scalar : options.DST;\n const xmd = expand_message_xmd(msg, DST, 64, sha512);\n return Fn.create(bytesToNumberLE(xmd));\n },\n /**\n * HashToCurve-like construction based on RFC 9496 (Element Derivation).\n * Converts 64 uniform random bytes into a curve point.\n *\n * WARNING: This represents an older hash-to-curve construction from before\n * RFC 9380 was finalized.\n * It was later reused as a component in the newer\n * `hash_to_ristretto255` function defined in RFC 9380.\n */\n deriveToCurve(bytes) {\n // https://www.rfc-editor.org/rfc/rfc9496.html#name-element-derivation\n abytes(bytes, 64);\n const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new _RistrettoPoint(R1.add(R2));\n },\n});\n/**\n * ristretto255 OPRF/VOPRF/POPRF bundle, defined in RFC 9497.\n * @example\n * Run one blind/evaluate/finalize OPRF round over ristretto255.\n *\n * ```ts\n * const input = new TextEncoder().encode('hello noble');\n * const keys = ristretto255_oprf.oprf.generateKeyPair();\n * const blind = ristretto255_oprf.oprf.blind(input);\n * const evaluated = ristretto255_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded);\n * const output = ristretto255_oprf.oprf.finalize(input, blind.blind, evaluated);\n * ```\n */\nexport const ristretto255_oprf = /* @__PURE__ */ (() => createOPRF({\n name: 'ristretto255-SHA512',\n Point: _RistrettoPoint,\n hash: sha512,\n hashToGroup: ristretto255_hasher.hashToCurve,\n hashToScalar: ristretto255_hasher.hashToScalar,\n}))();\n/**\n * FROST threshold signatures over ristretto255. RFC 9591.\n * @example\n * Create one trusted-dealer package for 2-of-3 ristretto255 signing.\n *\n * ```ts\n * const alice = ristretto255_FROST.Identifier.derive('alice@example.com');\n * const bob = ristretto255_FROST.Identifier.derive('bob@example.com');\n * const carol = ristretto255_FROST.Identifier.derive('carol@example.com');\n * const deal = ristretto255_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const ristretto255_FROST = /* @__PURE__ */ (() => createFROST({\n name: 'FROST-RISTRETTO255-SHA512-v1',\n Point: _RistrettoPoint,\n validatePoint: (p) => {\n // Prime-order wrappers are torsion-free at the abstract-group level.\n p.assertValidity();\n },\n hash: sha512,\n}))();\n/**\n * Weird / bogus points, useful for debugging.\n * All 8 ed25519 points of 8-torsion subgroup can be generated from the point\n * T = `26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05`.\n * The subgroup generated by `T` is `{ O, T, 2T, 3T, 4T, 5T, 6T, 7T }`; the\n * array below is that set, not the powers in that exact index order.\n * @example\n * Decode one known torsion point for debugging.\n *\n * ```ts\n * import { ED25519_TORSION_SUBGROUP, ed25519 } from '@noble/curves/ed25519.js';\n * const point = ed25519.Point.fromHex(ED25519_TORSION_SUBGROUP[1]);\n * ```\n */\nexport const ED25519_TORSION_SUBGROUP = /* @__PURE__ */ Object.freeze([\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n]);\n", "/**\n * Edwards448 (also called Goldilocks) curve with following addons:\n * - X448 ECDH\n * - Decaf cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n * Conforms to RFC 8032 https://www.rfc-editor.org/rfc/rfc8032.html#section-5.2\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { shake256 } from '@noble/hashes/sha3.js';\nimport { concatBytes, hexToBytes, createHasher as wrapConstructor } from '@noble/hashes/utils.js';\nimport { eddsa, edwards, PrimeEdwardsPoint, } from \"./abstract/edwards.js\";\nimport { createFROST } from \"./abstract/frost.js\";\nimport { _DST_scalar, createHasher, expand_message_xof, } from \"./abstract/hash-to-curve.js\";\nimport { Field, FpInvertBatch, mod, pow2 } from \"./abstract/modular.js\";\nimport { montgomery } from \"./abstract/montgomery.js\";\nimport { createOPRF } from \"./abstract/oprf.js\";\nimport { abytes, asciiToBytes, bytesToNumberLE, equalBytes, } from \"./utils.js\";\n// edwards448 curve\n// a = 1n\n// d = Fp.neg(39081n)\n// Finite field 2n**448n - 2n**224n - 1n\n// Subgroup order\n// 2n**446n - 13818066809895115352007386748515426880336692474882178609894547503885n\nconst ed448_CURVE_p = /* @__PURE__ */ BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\nconst ed448_CURVE = /* @__PURE__ */ (() => ({\n p: ed448_CURVE_p,\n n: BigInt('0x3fffffffffffffffffffffffffffffffffffffffffffffffffffffff7cca23e9c44edb49aed63690216cc2728dc58f552378c292ab5844f3'),\n h: BigInt(4),\n a: BigInt(1),\n d: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffffffffffffffffffffffffffffffffffffffffffffffff6756'),\n Gx: BigInt('0x4f1970c66bed0ded221d15a622bf36da9e146570470f1767ea6de324a3d3a46412ae1af72ab66511433b80e18b00938e2626a82bc70cc05e'),\n Gy: BigInt('0x693f46716eb6bc248876203756c9c7624bea73736ca3984087789c1e05a0c2d73ad3ff1ce67c39c4fdbd132c4ed7c8ad9808795bf230fa14'),\n}))();\n// This is not RFC 8032 edwards448 / Goldilocks (`ed448` below, d = -39081).\n// It is NIST SP 800-186 \u00A73.2.3.3 E448, the Curve448-isomorphic Edwards model\n// also described in draft-ietf-lwig-curve-representations-23 Appendix M, with\n// d = 39082/39081 and Gy = 3/2.\n// RFC 7748's literal Edwards point / birational map are wrong here: the literal\n// point is the wrong-sign (Gx, -Gy) order-2*n variant. Keep the corrected\n// prime-order (Gx, Gy) base so Point.BASE stays a subgroup generator, which is\n// what noble's generic Edwards API expects.\nconst E448_CURVE = /* @__PURE__ */ (() => Object.assign({}, ed448_CURVE, {\n d: BigInt('0xd78b4bdc7f0daf19f24f38c29373a2ccad46157242a50f37809b1da3412a12e79ccc9c81264cfe9ad080997058fb61c4243cc32dbaa156b9'),\n Gx: BigInt('0x79a70b2b70400553ae7c9df416c792c61128751ac92969240c25a07d728bdc93e21f7787ed6972249de732f38496cd11698713093e9c04fc'),\n Gy: BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffff80000000000000000000000000000000000000000000000000000001'),\n}))();\nconst shake256_114 = /* @__PURE__ */ wrapConstructor(() => shake256.create({ dkLen: 114 }));\nconst shake256_64 = /* @__PURE__ */ wrapConstructor(() => shake256.create({ dkLen: 64 }));\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _11n = /* @__PURE__ */ BigInt(11);\n// prettier-ignore\nconst _22n = /* @__PURE__ */ BigInt(22), _44n = /* @__PURE__ */ BigInt(44), _88n = /* @__PURE__ */ BigInt(88), _223n = /* @__PURE__ */ BigInt(223);\n// powPminus3div4 calculates z = x^k mod p, where k = (p-3)/4.\n// Used for efficient square root calculation.\n// ((P-3)/4).toString(2) would produce bits [223x 1, 0, 222x 1]\nfunction ed448_pow_Pminus3div4(x) {\n const P = ed448_CURVE_p;\n const b2 = (x * x * x) % P;\n const b3 = (b2 * b2 * x) % P;\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 b222 = (pow2(b220, _2n, P) * b2) % P;\n const b223 = (pow2(b222, _1n, P) * x) % P;\n return (pow2(b223, _223n, P) * b222) % P;\n}\n// Mutates and returns the provided buffer in place. The final `bytes[56] = 0`\n// write is the Ed448 path; for 56-byte X448 inputs it is an out-of-bounds no-op.\nfunction adjustScalarBytes(bytes) {\n // Section 5: Likewise, for X448, set the two least significant bits of the first byte to 0,\n bytes[0] &= 252; // 0b11111100\n // and the most significant bit of the last byte to 1.\n bytes[55] |= 128; // 0b10000000\n // NOTE: is NOOP for 56 bytes scalars (X25519/X448)\n bytes[56] = 0; // Byte outside of group (456 buts vs 448 bits)\n return bytes;\n}\n// Constant-time Ed448 decode helper for RFC 8032 \u00A75.2.3 steps 2-3. Unlike\n// `SQRT_RATIO_M1`, the returned `value` only has the documented meaning when\n// `isValid` is true.\nfunction uvRatio(u, v) {\n const P = ed448_CURVE_p;\n // https://www.rfc-editor.org/rfc/rfc8032#section-5.2.3\n // To compute the square root of (u/v), the first step is to compute the\n // candidate root x = (u/v)^((p+1)/4). This can be done using the\n // following trick, to use a single modular powering for both the\n // inversion of v and the square root:\n // x = (u/v)^((p+1)/4) = u\u00B3v(u\u2075v\u00B3)^((p-3)/4) (mod p)\n const u2v = mod(u * u * v, P); // u\u00B2v\n const u3v = mod(u2v * u, P); // u\u00B3v\n const u5v3 = mod(u3v * u2v * v, P); // u\u2075v\u00B3\n const root = ed448_pow_Pminus3div4(u5v3);\n const x = mod(u3v * root, P);\n // Verify that root is exists\n const x2 = mod(x * x, P); // x\u00B2\n // If vx\u00B2 = u, the recovered x-coordinate is x. Otherwise, no\n // square root exists, and the decoding fails.\n return { isValid: mod(x2 * v, P) === u, value: x };\n}\n// Finite field 2n**448n - 2n**224n - 1n\n// RFC 8032 encodes Ed448 field/scalar elements in 57 bytes even though field\n// values fit in 448 bits and scalars in 446 bits. Noble models that with a\n// 456-bit storage width so the final-octet x-sign bit (bit 455) still fits in\n// the shared little-endian container.\nconst Fp = /* @__PURE__ */ (() => Field(ed448_CURVE_p, { BITS: 456, isLE: true }))();\n// Same 57-byte container shape as `Fp`; canonical scalar encodings still have\n// the top ten bits clear per RFC 8032.\nconst Fn = /* @__PURE__ */ (() => Field(ed448_CURVE.n, { BITS: 456, isLE: true }))();\n// Generic 56-byte field shape used by decaf448 and raw X448 u-coordinates.\n// Plain `Field` decoding stays canonical here, so callers that want RFC 7748's\n// modulo-p acceptance must reduce externally.\nconst Fp448 = /* @__PURE__ */ (() => Field(ed448_CURVE_p, { BITS: 448, isLE: true }))();\n// Strict 56-byte scalar parser matching RFC 9496's recommended canonical form.\nconst Fn448 = /* @__PURE__ */ (() => Field(ed448_CURVE.n, { BITS: 448, isLE: true }))();\nfunction toMontgomery(point) {\n // RFC 7748 section 4.2 maps Ed448-Goldilocks to Curve448 via a 4-isogeny.\n // The u-coordinate map is:\n // u = y^2 / x^2\n // In projective coordinates this is:\n // u = Y^2 / X^2\n const u = Fp.div(Fp.mul(point.Y, point.Y), Fp.mul(point.X, point.X));\n return Fp448.toBytes(u);\n}\nfunction toMontgomerySecret(secretKey) {\n const size = ed448_Point.Fp.BYTES;\n abytes(secretKey, size);\n return adjustScalarBytes(shake256_114(secretKey.subarray(0, size))).subarray(0, 56);\n}\n// SHAKE256(dom4(phflag,context)||x, 114)\n// RFC 8032 `dom4` prefix. Empty contexts are valid; the accepted length range\n// is 0..255 octets inclusive.\nfunction dom4(data, ctx, phflag) {\n if (ctx.length > 255)\n throw new Error('context must be smaller than 255, got: ' + ctx.length);\n return concatBytes(asciiToBytes('SigEd448'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);\n}\nconst ed448_Point = /* @__PURE__ */ edwards(ed448_CURVE, { Fp, Fn, uvRatio });\n// Shared internal factory for both `ed448` and `ed448ph`; callers are only\n// expected to override narrow family options such as prehashing.\nfunction ed4(opts) {\n return eddsa(ed448_Point, shake256_114, Object.assign({ adjustScalarBytes, domain: dom4, toMontgomery, toMontgomerySecret }, opts));\n}\n/**\n * ed448 EdDSA curve and methods.\n * @example\n * Generate one Ed448 keypair, sign a message, and verify it.\n *\n * ```js\n * import { ed448 } from '@noble/curves/ed448.js';\n * const { secretKey, publicKey } = ed448.keygen();\n * // const publicKey = ed448.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ed448.sign(msg, secretKey);\n * const isValid = ed448.verify(sig, msg, publicKey);\n * ```\n */\nexport const ed448 = /* @__PURE__ */ ed4({});\n// There is no ed448ctx, since ed448 supports ctx by default\n/**\n * Prehashed version of ed448. See {@link ed448}\n * @example\n * Use the prehashed Ed448 variant for one message.\n *\n * ```ts\n * const { secretKey, publicKey } = ed448ph.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ed448ph.sign(msg, secretKey);\n * const isValid = ed448ph.verify(sig, msg, publicKey);\n * ```\n */\nexport const ed448ph = /* @__PURE__ */ ed4({ prehash: shake256_64 });\n/**\n * E448 here is NIST SP 800-186 \u00A73.2.3.3 E448, the Edwards representation of\n * Curve448, not RFC 8032 edwards448 / Goldilocks.\n * Goldilocks is the separate 4-isogenous curve exposed as `ed448`.\n * We keep the corrected prime-order base here; RFC 7748's literal Edwards\n * point / map are wrong for this curve model, and the literal point is the\n * wrong-sign order-2*n variant.\n * @param X - Projective X coordinate.\n * @param Y - Projective Y coordinate.\n * @param Z - Projective Z coordinate.\n * @param T - Projective T coordinate.\n * @example\n * Reconstruct and validate the E448 base point from its projective coordinates.\n *\n * ```ts\n * import { E448 } from '@noble/curves/ed448.js';\n * const point = new E448(E448.BASE.X, E448.BASE.Y, E448.BASE.Z, E448.BASE.T);\n * point.assertValidity();\n * ```\n */\nexport const E448 = /* @__PURE__ */ edwards(E448_CURVE, { Fp, Fn });\n/**\n * ECDH using curve448 aka x448.\n * The wrapper aborts on all-zero shared secrets by default, and seeded\n * `keygen(seed)` reuses the provided 56-byte seed buffer instead of copying it.\n *\n * @example\n * Derive one shared secret between two X448 peers.\n *\n * ```js\n * import { x448 } from '@noble/curves/ed448.js';\n * const alice = x448.keygen();\n * const bob = x448.keygen();\n * const shared = x448.getSharedSecret(alice.secretKey, bob.publicKey);\n * ```\n */\nexport const x448 = /* @__PURE__ */ (() => {\n const P = ed448_CURVE_p;\n const powPminus2 = (x) => {\n const Pminus3div4 = ed448_pow_Pminus3div4(x);\n const Pminus3 = pow2(Pminus3div4, _2n, P);\n return mod(Pminus3 * x, P); // Pminus3 * x = Pminus2\n };\n return montgomery({\n P,\n type: 'x448',\n powPminus2,\n adjustScalarBytes,\n // ~3x faster fixed-base: [k]B on Ed448-Goldilocks using cached base tables, mapped back\n // through the 4-isogeny to curve448: u = y\u00B2/x\u00B2 = Y\u00B2/X\u00B2 (the isogeny is a homomorphism and\n // sends the Ed448 base point to u=5, so no scalar correction factor is needed).\n scalarMultBase: (k) => {\n // Clamped k (\u22482^447) exceeds n, but B has prime order n, so [k]B == [k mod n]B.\n const kn = mod(k, ed448_Point.Fn.ORDER);\n // k \u2261 0 (mod n): [k]B is the point at infinity, whose u is 0 in the x-only ladder;\n // returning 0 makes montgomery() reject it exactly like the ladder path.\n if (kn === _0n)\n return _0n;\n const p = ed448_Point.BASE.multiply(kn);\n // X == 0 only at the identity and the order-2 point, both excluded from the prime-order\n // subgroup hit by kn in 1..n-1.\n return mod(p.Y * p.Y * powPminus2(mod(p.X * p.X, P)), P);\n },\n });\n})();\n// Hash To Curve Elligator2 Map\n// 1. c1 = (q - 3) / 4 # Integer arithmetic \u2014 tv3^c1 below reuses the\n// ed448_pow_Pminus3div4 addition chain, which computes exactly x^((p-3)/4).\nconst ELL2_J = /* @__PURE__ */ BigInt(156326);\n// Returns RFC 9380 Appendix G.2.3 rational Montgomery numerators/denominators\n// `{ xn, xd, yn, yd }`, not an affine point.\nfunction map_to_curve_elligator2_curve448(u) {\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n let e1 = Fp.eql(tv1, Fp.ONE); // 2. e1 = tv1 == 1\n tv1 = Fp.cmov(tv1, Fp.ZERO, e1); // 3. tv1 = CMOV(tv1, 0, e1) # If Z * u^2 == -1, set tv1 = 0\n let xd = Fp.sub(Fp.ONE, tv1); // 4. xd = 1 - tv1\n let x1n = Fp.neg(ELL2_J); // 5. x1n = -J\n let tv2 = Fp.sqr(xd); // 6. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 7. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, Fp.neg(ELL2_J)); // 8. gx1 = -J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 9. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 10. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 11. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 12. tv3 = gxd^2\n tv2 = Fp.mul(gx1, gxd); // 13. tv2 = gx1 * gxd # gx1 * gxd\n tv3 = Fp.mul(tv3, tv2); // 14. tv3 = tv3 * tv2 # gx1 * gxd^3\n let y1 = ed448_pow_Pminus3div4(tv3); // 15. y1 = tv3^c1 # (gx1 * gxd^3)^((p - 3) / 4)\n y1 = Fp.mul(y1, tv2); // 16. y1 = y1 * tv2 # gx1 * gxd * (gx1 * gxd^3)^((p - 3) / 4)\n // 17. x2n = -tv1 * x1n # x2 = x2n / xd = -1 * u^2 * x1n / xd\n let x2n = Fp.mul(x1n, Fp.neg(tv1));\n let y2 = Fp.mul(y1, u); // 18. y2 = y1 * u\n y2 = Fp.cmov(y2, Fp.ZERO, e1); // 19. y2 = CMOV(y2, 0, e1)\n tv2 = Fp.sqr(y1); // 20. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 21. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx1); // 22. e2 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e2); // 23. xn = CMOV(x2n, x1n, e2) # If e2, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e2); // 24. y = CMOV(y2, y1, e2) # If e2, y = y1, else y = y2\n let e3 = Fp.isOdd(y); // 25. e3 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e2 !== e3); // 26. y = CMOV(y, -y, e2 XOR e3)\n return { xn, xd, yn: y, yd: Fp.ONE }; // 27. return (xn, xd, y, 1)\n}\n// Returns affine `{ x, y }` after inverting the Appendix G.2.4 denominators.\nfunction map_to_curve_elligator2_edwards448(u) {\n // 1. (xn, xd, yn, yd) = map_to_curve_elligator2_curve448(u)\n let { xn, xd, yn, yd } = map_to_curve_elligator2_curve448(u);\n let xn2 = Fp.sqr(xn); // 2. xn2 = xn^2\n let xd2 = Fp.sqr(xd); // 3. xd2 = xd^2\n let xd4 = Fp.sqr(xd2); // 4. xd4 = xd2^2\n let yn2 = Fp.sqr(yn); // 5. yn2 = yn^2\n let yd2 = Fp.sqr(yd); // 6. yd2 = yd^2\n let xEn = Fp.sub(xn2, xd2); // 7. xEn = xn2 - xd2\n let tv2 = Fp.sub(xEn, xd2); // 8. tv2 = xEn - xd2\n xEn = Fp.mul(xEn, xd2); // 9. xEn = xEn * xd2\n xEn = Fp.mul(xEn, yd); // 10. xEn = xEn * yd\n xEn = Fp.mul(xEn, yn); // 11. xEn = xEn * yn\n xEn = Fp.mul(xEn, _4n); // 12. xEn = xEn * 4\n tv2 = Fp.mul(tv2, xn2); // 13. tv2 = tv2 * xn2\n tv2 = Fp.mul(tv2, yd2); // 14. tv2 = tv2 * yd2\n let tv3 = Fp.mul(yn2, _4n); // 15. tv3 = 4 * yn2\n let tv1 = Fp.add(tv3, yd2); // 16. tv1 = tv3 + yd2\n tv1 = Fp.mul(tv1, xd4); // 17. tv1 = tv1 * xd4\n let xEd = Fp.add(tv1, tv2); // 18. xEd = tv1 + tv2\n tv2 = Fp.mul(tv2, xn); // 19. tv2 = tv2 * xn\n let tv4 = Fp.mul(xn, xd4); // 20. tv4 = xn * xd4\n let yEn = Fp.sub(tv3, yd2); // 21. yEn = tv3 - yd2\n yEn = Fp.mul(yEn, tv4); // 22. yEn = yEn * tv4\n yEn = Fp.sub(yEn, tv2); // 23. yEn = yEn - tv2\n tv1 = Fp.add(xn2, xd2); // 24. tv1 = xn2 + xd2\n tv1 = Fp.mul(tv1, xd2); // 25. tv1 = tv1 * xd2\n tv1 = Fp.mul(tv1, xd); // 26. tv1 = tv1 * xd\n tv1 = Fp.mul(tv1, yn2); // 27. tv1 = tv1 * yn2\n tv1 = Fp.mul(tv1, BigInt(-2)); // 28. tv1 = -2 * tv1\n let yEd = Fp.add(tv2, tv1); // 29. yEd = tv2 + tv1\n tv4 = Fp.mul(tv4, yd2); // 30. tv4 = tv4 * yd2\n yEd = Fp.add(yEd, tv4); // 31. yEd = yEd + tv4\n tv1 = Fp.mul(xEd, yEd); // 32. tv1 = xEd * yEd\n let e = Fp.eql(tv1, Fp.ZERO); // 33. e = tv1 == 0\n xEn = Fp.cmov(xEn, Fp.ZERO, e); // 34. xEn = CMOV(xEn, 0, e)\n xEd = Fp.cmov(xEd, Fp.ONE, e); // 35. xEd = CMOV(xEd, 1, e)\n yEn = Fp.cmov(yEn, Fp.ONE, e); // 36. yEn = CMOV(yEn, 1, e)\n yEd = Fp.cmov(yEd, Fp.ONE, e); // 37. yEd = CMOV(yEd, 1, e)\n const inv = FpInvertBatch(Fp, [xEd, yEd], true); // batch division\n return { x: Fp.mul(xEn, inv[0]), y: Fp.mul(yEn, inv[1]) }; // 38. return (xEn, xEd, yEn, yEd)\n}\n/**\n * Hashing / encoding to ed448 points / field. RFC 9380 methods.\n * Public `mapToCurve()` consumes one field element bigint for `m = 1`, and RFC\n * Appendix J vectors use the special `QUUX-V01-*` test DST overrides rather\n * than the default suite IDs below.\n * @example\n * Hash one message onto the ed448 curve.\n *\n * ```ts\n * const point = ed448_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const ed448_hasher = /* @__PURE__ */ (() => createHasher(ed448_Point, (scalars) => map_to_curve_elligator2_edwards448(scalars[0]), {\n DST: 'edwards448_XOF:SHAKE256_ELL2_RO_',\n encodeDST: 'edwards448_XOF:SHAKE256_ELL2_NU_',\n p: ed448_CURVE_p,\n m: 1,\n k: 224,\n expand: 'xof',\n hash: shake256,\n}))();\n/**\n * FROST threshold signatures over ed448. RFC 9591.\n * @example\n * Create one trusted-dealer package for 2-of-3 ed448 signing.\n *\n * ```ts\n * const alice = ed448_FROST.Identifier.derive('alice@example.com');\n * const bob = ed448_FROST.Identifier.derive('bob@example.com');\n * const carol = ed448_FROST.Identifier.derive('carol@example.com');\n * const deal = ed448_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const ed448_FROST = /* @__PURE__ */ (() => createFROST({\n name: 'FROST-ED448-SHAKE256-v1',\n Point: ed448_Point,\n // createFROST() already rejects the identity and non-prime-order elements per RFC 9591\n // Section 3.1; this hook only adds the on-curve check.\n validatePoint: (p) => {\n p.assertValidity();\n },\n // Group: edwards448 [RFC8032], where Ne = 57 and Ns = 57.\n // Fn is 57 bytes, Fp is 57 bytes too\n Fn,\n hash: shake256_114,\n H2: 'SigEd448\\0\\0',\n}))();\n// 1-d\nconst ONE_MINUS_D = /* @__PURE__ */ BigInt('39082');\n// 1-2d\nconst ONE_MINUS_TWO_D = /* @__PURE__ */ BigInt('78163');\n// \u221A(-d)\nconst SQRT_MINUS_D = /* @__PURE__ */ BigInt('98944233647732219769177004876929019128417576295529901074099889598043702116001257856802131563896515373927712232092845883226922417596214');\n// 1 / \u221A(-d)\nconst INVSQRT_MINUS_D = /* @__PURE__ */ BigInt('315019913931389607337177038330951043522456072897266928557328499619017160722351061360252776265186336876723201881398623946864393857820716');\n// RFC 9496 `SQRT_RATIO_M1` must return `CT_ABS(s)`, i.e. the nonnegative root.\n// Keep this Decaf-local: RFC 9496 decode/encode/map formulas depend on that\n// canonical representative, while ordinary Ed448 decoding still uses `uvRatio()`\n// plus the public sign bit from RFC 8032.\nconst sqrtRatioM1 = (u, v) => {\n const { isValid, value } = uvRatio(u, v);\n return { isValid, value: Fp448.isOdd(value) ? Fp448.neg(value) : value };\n};\nconst invertSqrt = (number) => sqrtRatioM1(_1n, number);\n/**\n * Elligator map for hash-to-curve of decaf448.\n * Primary formula source is RFC 9496 \u00A75.3.4. Step 1 intentionally reduces the\n * input modulo `p`, and the return value is the internal Edwards\n * representation, not a public decaf encoding.\n */\nfunction calcElligatorDecafMap(r0) {\n const { d } = ed448_CURVE;\n const r = Fp448.create(-Fp448.sqrN(r0)); // 1\n const u0 = Fp448.mul(d, Fp448.subN(r, _1n)); // 2\n const u1 = Fp448.mul(Fp448.addN(u0, _1n), Fp448.subN(u0, r)); // 3\n const { isValid: was_square, value: v } = sqrtRatioM1(ONE_MINUS_TWO_D, Fp448.mul(Fp448.addN(r, _1n), u1)); // 4\n let v_prime = v; // 5\n if (!was_square)\n v_prime = Fp448.mul(r0, v);\n let sgn = _1n; // 6\n if (!was_square)\n sgn = Fp448.neg(Fp448.ONE);\n const s = Fp448.mul(v_prime, Fp448.addN(r, _1n)); // 7\n let s_abs = s;\n if (Fp448.isOdd(s))\n s_abs = Fp448.neg(s);\n const s2 = Fp448.sqrN(s);\n const W0 = Fp448.mul(s_abs, _2n); // 8\n const W1 = Fp448.add(s2, _1n); // 9\n const W2 = Fp448.sub(s2, _1n); // 10\n const W3 = Fp448.add(Fp448.mulN(Fp448.mulN(Fp448.mulN(v_prime, s), Fp448.subN(r, _1n)), ONE_MINUS_TWO_D), sgn); // 11\n return new ed448_Point(Fp448.mul(W0, W3), Fp448.mul(W2, W1), Fp448.mul(W1, W3), Fp448.mul(W0, W2));\n}\n// Keep the Decaf448 base representative literal here: deriving it with\n// `new _DecafPoint(ed448_Point.BASE).multiplyUnsafe(2)` forces eager WNAF precomputes and\n// adds about 100ms to `ed448.js` import time.\nconst DECAF_BASE_X = /* @__PURE__ */ BigInt('0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa955555555555555555555555555555555555555555555555555555555');\nconst DECAF_BASE_Y = /* @__PURE__ */ BigInt('0xae05e9634ad7048db359d6205086c2b0036ed7a035884dd7b7e36d728ad8c4b80d6565833a2a3098bbbcb2bed1cda06bdaeafbcdea9386ed');\nconst DECAF_BASE_T = /* @__PURE__ */ BigInt('0x696d84643374bace9d70983a12aa9d461da74d2d5c35e8d97ba72c3aba4450a5d29274229bd22c1d5e3a6474ee4ffb0e7a9e200a28eee402');\n/**\n * Each ed448/EdwardsPoint has 4 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Decaf was created to solve this.\n * Decaf point operates in X:Y:Z:T extended coordinates like EdwardsPoint,\n * but it should work in its own namespace: do not combine those two.\n * See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496).\n */\nclass _DecafPoint extends PrimeEdwardsPoint {\n // The following gymnastics is done because typescript strips comments otherwise\n // prettier-ignore\n static BASE = \n /* @__PURE__ */ (() => new _DecafPoint(new ed448_Point(DECAF_BASE_X, DECAF_BASE_Y, _1n, DECAF_BASE_T)))();\n // prettier-ignore\n static ZERO = \n /* @__PURE__ */ (() => new _DecafPoint(ed448_Point.ZERO))();\n // prettier-ignore\n static Fp = \n /* @__PURE__ */ (() => Fp448)();\n // prettier-ignore\n static Fn = \n /* @__PURE__ */ (() => Fn448)();\n constructor(ep) {\n super(ep);\n }\n /**\n * Create one Decaf448 point from affine Edwards coordinates.\n * This wraps the internal Edwards representative directly and is not a\n * canonical decaf448 decoding path.\n * Use `toBytes()` / `fromBytes()` if canonical decaf448 bytes matter.\n */\n static fromAffine(ap) {\n return new _DecafPoint(ed448_Point.fromAffine(ap));\n }\n assertSame(other) {\n if (!(other instanceof _DecafPoint))\n throw new Error('DecafPoint expected');\n }\n init(ep) {\n return new _DecafPoint(ep);\n }\n static fromBytes(bytes) {\n abytes(bytes, 56);\n const { d } = ed448_CURVE;\n const s = Fp448.fromBytes(bytes);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 2. Check that s is non-negative, or else abort\n if (!equalBytes(Fp448.toBytes(s), bytes) || Fp448.isOdd(s))\n throw new Error('invalid decaf448 encoding 1');\n const s2 = Fp448.sqr(s); // 1\n const u1 = Fp448.add(Fp448.ONE, s2); // 2\n const u1sq = Fp448.sqr(u1);\n const u2 = Fp448.sub(u1sq, Fp448.mulN(Fp448.mulN(_4n, d), s2)); // 3\n const { isValid, value: invsqrt } = invertSqrt(Fp448.mul(u2, u1sq)); // 4\n let u3 = Fp448.mul(Fp448.mulN(Fp448.mulN(Fp448.addN(s, s), invsqrt), u1), SQRT_MINUS_D); // 5\n if (Fp448.isOdd(u3))\n u3 = Fp448.neg(u3);\n const x = Fp448.mul(Fp448.mulN(Fp448.mulN(u3, invsqrt), u2), INVSQRT_MINUS_D); // 6\n const y = Fp448.mul(Fp448.mulN(Fp448.subN(_1n, s2), invsqrt), u1); // 7\n const t = Fp448.mul(x, y); // 8\n if (!isValid)\n throw new Error('invalid decaf448 encoding 2');\n return new _DecafPoint(new ed448_Point(x, y, Fp448.ONE, t));\n }\n /**\n * Converts decaf-encoded string to decaf point.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode-2).\n * @param hex - Decaf-encoded 56 bytes. Not every 56-byte string is valid decaf encoding\n */\n static fromHex(hex) {\n return _DecafPoint.fromBytes(hexToBytes(hex));\n }\n /**\n * Encodes decaf point to Uint8Array.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode-2).\n */\n toBytes() {\n const { X, Z, T } = this.ep;\n const u1 = Fp448.mul(Fp448.add(X, T), Fp448.sub(X, T)); // 1\n const x2 = Fp448.sqr(X);\n const { value: invsqrt } = invertSqrt(Fp448.mul(Fp448.mulN(u1, ONE_MINUS_D), x2)); // 2\n let ratio = Fp448.mul(Fp448.mulN(invsqrt, u1), SQRT_MINUS_D); // 3\n if (Fp448.isOdd(ratio))\n ratio = Fp448.neg(ratio);\n const u2 = Fp448.sub(Fp448.mulN(Fp448.mulN(INVSQRT_MINUS_D, ratio), Z), T); // 4\n let s = Fp448.mul(Fp448.mulN(Fp448.mulN(ONE_MINUS_D, invsqrt), X), u2); // 5\n if (Fp448.isOdd(s))\n s = Fp448.neg(s);\n return Fp448.toBytes(s);\n }\n /**\n * Compare one point to another.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals-2).\n */\n equals(other) {\n this.assertSame(other);\n const { X: X1, Y: Y1 } = this.ep;\n const { X: X2, Y: Y2 } = other.ep;\n // (x1 * y2 == y1 * x2)\n return Fp448.eql(Fp448.mul(X1, Y2), Fp448.mul(Y1, X2));\n }\n is0() {\n return this.equals(_DecafPoint.ZERO);\n }\n}\n/** Prime-order Decaf448 group bundle. */\nexport const decaf448 = /* @__PURE__ */ (() => {\n Object.freeze(_DecafPoint.BASE);\n Object.freeze(_DecafPoint.ZERO);\n Object.freeze(_DecafPoint.prototype);\n Object.freeze(_DecafPoint);\n return Object.freeze({ Point: _DecafPoint });\n})();\n/**\n * Hashing to decaf448 points / field. RFC 9380 methods.\n * `hashToCurve()` is RFC 9380 `hash_to_decaf448`, `deriveToCurve()` is RFC\n * 9496 element derivation, and `hashToScalar()` is a library helper layered on\n * top of RFC 9496 scalar reduction.\n * @example\n * Hash one message onto decaf448.\n *\n * ```ts\n * const point = decaf448_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const decaf448_hasher = /* @__PURE__ */ Object.freeze({\n Point: _DecafPoint,\n hashToCurve(msg, options) {\n // Preserve explicit empty/invalid DST overrides so expand_message_xof() can reject them.\n const DST = options?.DST === undefined ? 'decaf448_XOF:SHAKE256_D448MAP_RO_' : options.DST;\n return decaf448_hasher.deriveToCurve(expand_message_xof(msg, DST, 112, 224, shake256));\n },\n /**\n * Warning: has big modulo bias of 2^-64.\n * RFC is invalid. RFC says \"use 64-byte xof\", while for 2^-112 bias\n * it must use 84-byte xof (56+56/2), not 64.\n */\n hashToScalar(msg, options) {\n const DST = options?.DST === undefined ? _DST_scalar : options.DST;\n // Can't use `Fn448.fromBytes()`. 64-byte input => 56-byte field element\n const xof = expand_message_xof(msg, DST, 64, 256, shake256);\n return Fn448.create(bytesToNumberLE(xof));\n },\n /**\n * HashToCurve-like construction based on RFC 9496 (Element Derivation).\n * Converts 112 uniform random bytes into a curve point.\n *\n * WARNING: This represents an older hash-to-curve construction from before\n * RFC 9380 was finalized.\n * It was later reused as a component in the newer\n * `hash_to_decaf448` function defined in RFC 9380.\n */\n deriveToCurve(bytes) {\n abytes(bytes, 112);\n const skipValidation = true;\n // Note: Similar to the field element decoding described in\n // [RFC7748], and unlike the field element decoding described in\n // Section 5.3.1, non-canonical values are accepted.\n const r1 = Fp448.create(Fp448.fromBytes(bytes.subarray(0, 56), skipValidation));\n const R1 = calcElligatorDecafMap(r1);\n const r2 = Fp448.create(Fp448.fromBytes(bytes.subarray(56, 112), skipValidation));\n const R2 = calcElligatorDecafMap(r2);\n return new _DecafPoint(R1.add(R2));\n },\n});\n/**\n * decaf448 OPRF, defined in RFC 9497.\n * @example\n * Run one blind/evaluate/finalize OPRF round over decaf448.\n *\n * ```ts\n * const input = new TextEncoder().encode('hello noble');\n * const keys = decaf448_oprf.oprf.generateKeyPair();\n * const blind = decaf448_oprf.oprf.blind(input);\n * const evaluated = decaf448_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded);\n * const output = decaf448_oprf.oprf.finalize(input, blind.blind, evaluated);\n * ```\n */\nexport const decaf448_oprf = /* @__PURE__ */ (() => createOPRF({\n name: 'decaf448-SHAKE256',\n Point: _DecafPoint,\n hash: (msg) => shake256(msg, { dkLen: 64 }),\n hashToGroup: decaf448_hasher.hashToCurve,\n hashToScalar: decaf448_hasher.hashToScalar,\n}))();\n/**\n * Weird / bogus points, useful for debugging.\n * Unlike ed25519, there is no ed448 generator point which can produce full T subgroup.\n * Instead, the torsion subgroup here is cyclic of order 4, generated by\n * `(1, 0)`, and the array below lists that subgroup set.\n * @example\n * Decode one known torsion point for debugging.\n *\n * ```ts\n * import { ED448_TORSION_SUBGROUP, ed448 } from '@noble/curves/ed448.js';\n * const point = ed448.Point.fromHex(ED448_TORSION_SUBGROUP[1]);\n * ```\n */\nexport const ED448_TORSION_SUBGROUP = /* @__PURE__ */ Object.freeze([\n '010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',\n 'fefffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffffffffffffffffffffffffffffffffffffffffffffffffff00',\n '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',\n '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080',\n]);\n", "/**\n * ASN.1 DER (Distinguished Encoding Rules) helpers for ECDSA signatures.\n * Only implements the tiny subset needed for `SEQUENCE(INTEGER r, INTEGER s)`.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abignumber, abytes, asafenumber, astring, bytesToNumberBE, numberToHexUnpadded, validateObject, } from \"../utils.js\";\nconst _0n = /* @__PURE__ */ BigInt(0);\n/**\n * @param m - Error message.\n * @example\n * Throw a DER-specific error when signature parsing encounters invalid bytes.\n *\n * ```ts\n * new DERErr('bad der');\n * ```\n */\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\n// Plain const so the freezes can live inside the pure initializer of the `DER` export below:\n// bare top-level `Object.freeze(...)` calls would defeat tree-shaking for every importer.\nconst _DER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag, data) => {\n const { Err: E } = _DER;\n asafenumber(tag, 'tag');\n if (tag < 0 || tag > 255)\n throw new E('tlv.encode: wrong tag');\n astring(data, 'data');\n // Internal helper: callers hand this already-validated hex payload, so we only enforce\n // byte alignment here instead of re-validating every nibble.\n if (data.length & 1)\n throw new E('tlv.encode: unpadded data');\n const dataLen = data.length / 2;\n const len = numberToHexUnpadded(dataLen);\n if ((len.length / 2) & 0b1000_0000)\n throw new E('tlv.encode: long form length too big');\n // length of length with long form flag\n const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';\n const t = numberToHexUnpadded(tag);\n return t + lenLen + len + data;\n },\n // v - value, l - left bytes (unparsed)\n decode(tag, data) {\n const { Err: E } = _DER;\n data = abytes(data, undefined, 'DER data');\n let pos = 0;\n if (tag < 0 || tag > 255)\n throw new E('tlv.decode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag)\n throw new E('tlv.decode: wrong tlv');\n const first = data[pos++];\n // First bit of first length byte is the short/long form flag.\n const isLong = !!(first & 0b1000_0000);\n let length = 0;\n if (!isLong)\n length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 0b0111_1111;\n if (!lenLen)\n throw new E('tlv.decode(long): indefinite length not supported');\n // This would overflow u32 in JS.\n if (lenLen > 4)\n throw new E('tlv.decode(long): byte length is too big');\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen)\n throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0)\n throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes)\n length = (length << 8) | b;\n pos += lenLen;\n if (length < 128)\n throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length)\n throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) };\n },\n },\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 _int: {\n encode(num) {\n const { Err: E } = _DER;\n abignumber(num);\n if (num < _0n)\n throw new E('integer: negative integers are not allowed');\n let hex = numberToHexUnpadded(num);\n // Pad with zero byte if negative flag is present\n if (Number.parseInt(hex[0], 16) & 0b1000)\n hex = '00' + hex;\n if (hex.length & 1)\n throw new E('unexpected DER parsing assertion: unpadded hex');\n return hex;\n },\n decode(data) {\n const { Err: E } = _DER;\n if (data.length < 1)\n throw new E('invalid signature integer: empty');\n if (data[0] & 0b1000_0000)\n throw new E('invalid signature integer: negative');\n // Single-byte zero `00` is the canonical DER INTEGER encoding for zero.\n if (data.length > 1 && data[0] === 0x00 && !(data[1] & 0b1000_0000))\n throw new E('invalid signature integer: unnecessary leading zero');\n return bytesToNumberBE(data);\n },\n },\n toSig(bytes, maxScalarBytes) {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = _DER;\n if (maxScalarBytes !== undefined) {\n asafenumber(maxScalarBytes, 'maxScalarBytes');\n if (maxScalarBytes < 1)\n throw new E('invalid signature: maxScalarBytes must be positive');\n }\n const data = abytes(bytes, undefined, 'signature');\n const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n if (seqLeftBytes.length)\n throw new E('invalid signature: left bytes after parsing');\n const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n if (sLeftBytes.length)\n throw new E('invalid signature: left bytes after parsing');\n // Enforce curve-provided bounds before bytes-to-hex-to-BigInt conversion can amplify memory.\n if (maxScalarBytes !== undefined &&\n (rBytes.length > maxScalarBytes || sBytes.length > maxScalarBytes))\n throw new E('invalid signature: integer too large');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig) {\n const { _tlv: tlv, _int: int } = _DER;\n validateObject(sig, { r: 'bigint', s: 'bigint' }, {}, 'sig');\n const rs = tlv.encode(0x02, int.encode(sig.r));\n const ss = tlv.encode(0x02, int.encode(sig.s));\n const seq = rs + ss;\n return tlv.encode(0x30, seq);\n },\n};\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: {@link https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/ | Let's Encrypt ASN.1 guide} and\n * {@link https://luca.ntop.org/Teaching/Appunti/asn1.html | Luca Deri's ASN.1 notes}.\n * @example\n * ASN.1 DER encoding utilities.\n *\n * ```ts\n * const der = DER.hexFromSig({ r: 1n, s: 2n });\n * ```\n */\nexport const DER = /* @__PURE__ */ (() => {\n Object.freeze(_DER._tlv);\n Object.freeze(_DER._int);\n return Object.freeze(_DER);\n})();\n", "/**\n * Short Weierstrass curve methods. The formula is: y\u00B2 = x\u00B3 + ax + b.\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\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * 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 * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac as nobleHmac } from '@noble/hashes/hmac.js';\nimport { ahash } from '@noble/hashes/utils.js';\nimport { abool, abytes, aInRange, bitLen, bitMask, bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, hexToBytes, isBytes, validateObject, randomBytes as wcRandomBytes, } from \"../utils.js\";\nimport { createCurveFields, createKeygen, mulAddUnsafe, normalizeZ, probeRandomBytes, ScalarMultiplier, validatePointCons, } from \"./curve.js\";\nimport { DER } from \"./der.js\";\nimport { getMinHashLength, invertCt, mapHashToField } from \"./modular.js\";\n// DER codec lives in der.ts; re-exported here because ECDSA signatures are its main consumer.\nexport { DER, DERErr } from \"./der.js\";\n// We construct the basis so `den` is always positive and equals `n`,\n// but the `num` sign depends on the basis, not on the secret value.\n// Exact half-way cases round away from zero, which keeps the split symmetric\n// around the reduced-basis boundaries used by endomorphism decomposition.\nconst divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n) / den;\n/** Splits scalar for GLV endomorphism. */\nexport function _splitEndoScalar(k, basis, n) {\n // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`\n // Since part can be negative, we need to do this on point.\n // Callers must provide a reduced GLV basis whose vectors satisfy\n // `a + b * lambda \u2261 0 (mod n)`; this helper only sees the basis and `n`.\n // Reject unreduced scalars instead of silently treating them mod n.\n aInRange('scalar', k, _0n, n);\n // TODO: verifyScalar function which consumes lambda\n const [[a1, b1], [a2, b2]] = basis;\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n // |k1|/|k2| is < sqrt(N), but can be negative.\n // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.\n let k1 = k - c1 * a1 - c2 * a2;\n let k2 = -c1 * b1 - c2 * b2;\n const k1neg = k1 < _0n;\n const k2neg = k2 < _0n;\n if (k1neg)\n k1 = -k1;\n if (k2neg)\n k2 = -k2;\n // Double check that resulting scalar is less than half bits of N: the wNAF pair walk\n // relies on the halves being short. This should only happen on wrong bases.\n // Also, the math inside is complex enough that this guard is worth keeping.\n const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N\n if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {\n throw new Error('splitScalar (endomorphism): failed for k');\n }\n return { k1neg, k1, k2neg, k2 };\n}\nfunction validateSigFormat(format) {\n if (!['compact', 'recovered', 'der'].includes(format))\n throw new Error('Signature format must be \"compact\", \"recovered\", or \"der\"');\n return format;\n}\nfunction validateSigOpts(opts, def) {\n validateObject(opts);\n const optsn = {};\n // Normalize only the declared option subset from `def`; unknown keys are\n // intentionally ignored so shared / superset option bags stay valid here too.\n // `extraEntropy` stays an opaque payload until the signing path consumes it.\n for (let optName of Object.keys(def)) {\n // @ts-ignore\n optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];\n }\n abool(optsn.lowS, 'lowS');\n abool(optsn.prehash, 'prehash');\n if (optsn.format !== undefined)\n validateSigFormat(optsn.format);\n return optsn;\n}\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4);\n/**\n * Creates weierstrass Point constructor, based on specified curve options.\n *\n * See {@link WeierstrassOpts}.\n * @param params - Curve parameters. See {@link WeierstrassOpts}.\n * @param extraOpts - Optional helpers and overrides. See {@link WeierstrassExtraOpts}.\n * @returns Weierstrass point constructor.\n * @throws If the curve parameters, overrides, or point codecs are invalid. {@link Error}\n *\n * @example\n * Construct a point type from explicit Weierstrass curve parameters.\n *\n * ```js\n * const opts = {\n * p: 0xfffffffffffffffffffffffffffffffeffffac73n,\n * n: 0x100000000000000000001b8fa16dfab9aca16b6b3n,\n * h: 1n,\n * a: 0n,\n * b: 7n,\n * Gx: 0x3b4c382ce37aa192a4019e763036f4f5dd4d7ebbn,\n * Gy: 0x938cf935318fdced6bc28286531733c3f03c4feen,\n * };\n * const secp160k1_Point = weierstrass(opts);\n * ```\n */\nexport function weierstrass(params, extraOpts = {}) {\n const validated = createCurveFields('weierstrass', params, extraOpts);\n const Fp = validated.Fp;\n const Fn = validated.Fn;\n let CURVE = validated.CURVE;\n const { h: cofactor, n: CURVE_ORDER } = CURVE;\n validateObject(extraOpts, {}, {\n allowInfinityPoint: 'boolean',\n clearCofactor: 'function',\n isTorsionFree: 'function',\n fromBytes: 'function',\n toBytes: 'function',\n endo: 'object',\n randomBytes: 'function',\n });\n // Snapshot every hook and take an owned copy of nested GLV configuration. Later mutations of\n // the caller's options must not change arithmetic, subgroup, or codec policy.\n const { endo: endoOpts, allowInfinityPoint, clearCofactor, isTorsionFree, fromBytes, toBytes, } = extraOpts;\n const randomBytes = extraOpts.randomBytes === undefined ? wcRandomBytes : extraOpts.randomBytes;\n if (endoOpts) {\n if (!Fp.is0(CURVE.a) || typeof endoOpts.beta !== 'bigint' || !Array.isArray(endoOpts.basises)) {\n throw new Error('invalid endo: expected \"beta\": bigint and \"basises\": array');\n }\n }\n const endo = endoOpts\n ? {\n beta: endoOpts.beta,\n basises: endoOpts.basises.map((basis) => [...basis]),\n }\n : undefined;\n const lengths = getWLengths(Fp, Fn);\n function assertCompressionIsSupported() {\n if (!Fp.isOdd)\n throw new Error('compression is not supported: Field does not have .isOdd()');\n }\n // Implements IEEE P1363 point encoding\n function pointToBytes(_c, point, isCompressed) {\n // Handle infinity before toAffine(), which maps ZERO to (0, 0) silently: without this the\n // encoder would emit an all-zero byte string that decodes back as a different point. Only\n // curves that opt into infinity as a public point value get the SEC 1 byte form.\n if (point.is0()) {\n if (!allowInfinityPoint)\n throw new Error('bad point: ZERO');\n return Uint8Array.of(0); // SEC 1 v2.0 \u00A72.3.3\n }\n const { x, y } = point.toAffine();\n const bx = Fp.toBytes(x);\n abool(isCompressed, 'isCompressed');\n if (isCompressed) {\n assertCompressionIsSupported();\n const hasEvenY = !Fp.isOdd(y);\n return concatBytes(pprefix(hasEvenY), bx);\n }\n else {\n return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));\n }\n }\n function pointFromBytes(bytes) {\n abytes(bytes, undefined, 'Point');\n const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65\n const length = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // SEC 1 v2.0 \u00A72.3.4 decodes 0x00 as infinity, but \u00A73.2.2 rejects infinity as a public key.\n // Leaving 0x00 undecodable by default makes that rejection structural rather than a check:\n // callers reuse this parser as the strict key boundary, and infinity is simply not\n // expressible. Curves where infinity is a real wire value opt into the codec instead.\n // secp256k1 crosstests show OpenSSL raw point codecs accept 0x00 too.\n if (allowInfinityPoint && length === 1 && head === 0x00)\n return { x: Fp.ZERO, y: Fp.ZERO };\n // No actual validation is done here: use .assertValidity()\n if (length === comp && (head === 0x02 || head === 0x03)) {\n const x = Fp.fromBytes(tail);\n if (!Fp.isValid(x))\n throw new Error('bad point: is not on curve, wrong x');\n const y2 = weierstrassEquation(x); // y\u00B2 = x\u00B3 + ax + b\n let y;\n try {\n y = Fp.sqrt(y2); // y = y\u00B2 ^ (p+1)/4\n }\n catch (sqrtError) {\n const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('bad point: is not on curve, sqrt error' + err);\n }\n assertCompressionIsSupported();\n const evenY = Fp.isOdd(y);\n const evenH = (head & 1) === 1; // ECDSA-specific\n if (evenH !== evenY)\n y = Fp.neg(y);\n return { x, y };\n }\n else if (length === uncomp && head === 0x04) {\n // TODO: more checks\n const L = Fp.BYTES;\n const x = Fp.fromBytes(tail.subarray(0, L));\n const y = Fp.fromBytes(tail.subarray(L, L * 2));\n if (!isValidXY(x, y))\n throw new Error('bad point: is not on curve');\n return { x, y };\n }\n else {\n throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);\n }\n }\n const encodePoint = toBytes === undefined ? pointToBytes : toBytes;\n const decodePoint = fromBytes === undefined ? pointFromBytes : fromBytes;\n // Hoisted from double() / add(): curve params never change after construction.\n // Koblitz curves (a=0, e.g. secp256k1) skip the three a-multiplications per operation;\n // the selection depends only on public curve constants.\n const b3 = Fp.mul(CURVE.b, _3n);\n const mulA = Fp.is0(CURVE.a) ? (_) => Fp.ZERO : (x) => Fp.mul(CURVE.a, x);\n function weierstrassEquation(x) {\n const x2 = Fp.sqr(x);\n const x3 = Fp.mul(x2, x);\n return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x\u00B3 + a * x + b\n }\n // TODO: move top-level\n /** Checks whether equation holds for given x, y: y\u00B2 == x\u00B3 + ax + b */\n function isValidXY(x, y) {\n const left = Fp.sqr(y);\n const right = weierstrassEquation(x); // x\u00B3 + ax + b\n return Fp.eql(left, right);\n }\n // Keep constructor-time generator validation cheap: callers are responsible for supplying the\n // correct prime-order base point, while eager subgroup checks here would slow heavy module imports.\n // Test 1: equation y\u00B2 = x\u00B3 + ax + b should work for generator point.\n if (!isValidXY(CURVE.Gx, CURVE.Gy))\n throw new Error('bad curve params: generator point');\n // Test 2: discriminant \u0394 part should be non-zero: 4a\u00B3 + 27b\u00B2 != 0.\n // Guarantees curve is genus-1, smooth (non-singular).\n const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n if (Fp.is0(Fp.add(_4a3, _27b2)))\n throw new Error('bad curve params: a or b');\n /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */\n function acoord(title, n, banZero = false) {\n if (!Fp.isValid(n) || (banZero && Fp.is0(n)))\n throw new Error(`bad point coordinate ${title}`);\n // Extension-field elements are objects. Keep point coordinates detached from caller-owned\n // objects so their mutation cannot invalidate cached on-curve / subgroup checks. Primitive\n // field elements (bigints in shipped prime fields) are already immutable values.\n return typeof n === 'object' && n !== null ? Fp.create(n) : n;\n }\n function aprjpoint(other) {\n if (!(other instanceof Point))\n throw new Error('Weierstrass Point expected');\n }\n function splitEndoScalarN(k) {\n if (!endo || !endo.basises)\n throw new Error('no endo');\n return _splitEndoScalar(k, endo.basises, Fn.ORDER);\n }\n /**\n * Appends a (point, scalar) pair to the inputs of a vartime wNAF walk\n * ({@link mulAddUnsafe}). With GLV endomorphism the scalar is split into two half-width\n * pairs against P and \u03C8(P) = (\u03B2\u22C5x, y), halving the walk's shared doubling chain;\n * split signs fold into the points.\n */\n function pushWnafPair(points, scalars, p, k) {\n if (!Fn.isValid(k))\n throw new RangeError('invalid scalar: out of range'); // 0 is valid\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(k);\n const psi = new Point(Fp.mul(p.X, endo.beta), p.Y, p.Z);\n points.push(k1neg ? p.negate() : p, k2neg ? psi.negate() : psi);\n scalars.push(k1, k2);\n }\n else {\n points.push(p);\n scalars.push(k);\n }\n }\n // Successful assertValidity() results are cached: Point instances are frozen at construction,\n // so on-curve + subgroup facts cannot change afterwards. Only success is cached \u2014 invalid\n // points re-throw on every call. This matters most for pairing curves, where subgroup checks\n // cost a scalar multiplication and the same instance is re-validated across layers\n // (signature fromBytes, pairingBatch) or across repeated verifies with a cached public key.\n const validityCache = new WeakSet();\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 {\n static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n static Fp = Fp;\n static Fn = Fn;\n X;\n Y;\n Z;\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n constructor(X, Y, Z) {\n this.X = acoord('x', X);\n // This is not just about ZERO / infinity: ambient curves can have real\n // finite points with y=0. Those points are 2-torsion, so they cannot lie\n // in the odd prime-order subgroups this point type is meant to represent.\n this.Y = acoord('y', Y, true);\n this.Z = acoord('z', Z);\n Object.freeze(this);\n }\n static CURVE() {\n return CURVE;\n }\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n static fromAffine(p) {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('invalid affine point');\n if (p instanceof Point)\n throw new Error('projective point not allowed');\n // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)\n if (Fp.is0(x) && Fp.is0(y))\n return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n static fromBytes(bytes) {\n const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));\n P.assertValidity();\n return P;\n }\n static fromHex(hex) {\n return Point.fromBytes(hexToBytes(hex));\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n /**\n * @param isLazy - true will defer table computation until the first multiplication\n */\n precompute(windowSize = 6, isLazy = true) {\n wnaf.setWindowSize(this, windowSize);\n if (!isLazy)\n this.multiply(_3n); // random number\n return this;\n }\n // TODO: return `this`\n /** A point on curve is valid if it conforms to equation. */\n assertValidity() {\n const p = this;\n if (p.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // Keep the accepted infinity encoding canonical: projective-equivalent (X, Y, 0) points\n // like (1, 1, 0) compare equal to ZERO, but only (0, 1, 0) should pass this guard.\n if (allowInfinityPoint && Fp.is0(p.X) && Fp.eql(p.Y, Fp.ONE) && Fp.is0(p.Z))\n return;\n throw new Error('bad point: ZERO');\n }\n if (validityCache.has(p))\n return;\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = p.toAffine();\n if (!Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('bad point: x or y not field elements');\n if (!isValidXY(x, y))\n throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree())\n throw new Error('bad point: not in prime-order subgroup');\n validityCache.add(p);\n }\n hasEvenY() {\n const { y } = this.toAffine();\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't support isOdd\");\n return !Fp.isOdd(y);\n }\n /** Compare one point to another. */\n equals(other) {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: 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 /** Flips point to one corresponding to (x, -y) in Affine coordinates. */\n negate() {\n return new Point(this.X, Fp.neg(this.Y), this.Z);\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 { X: X1, Y: Y1, Z: 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 = mulA(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 = mulA(t2);\n t3 = Fp.sub(t0, t2);\n t3 = mulA(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 // 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) {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\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 = mulA(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 = mulA(t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = mulA(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 subtract(other) {\n // Validate before calling `negate()` so wrong inputs fail with the point guard\n // instead of leaking a foreign `negate()` error.\n aprjpoint(other);\n return this.add(other.negate());\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n /**\n * Constant time multiplication.\n * Uses precomputed tables (signed fixed-window wNAF) when available.\n * Uses scalar blinding and avoids endomorphism splitting in the secret-scalar path.\n * @param scalar - by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar) {\n // Keep the subgroup-scalar contract strict instead of reducing 0 / n to ZERO.\n // In key/signature-style callers, those values usually mean broken hash/scalar plumbing,\n // and failing closed is safer than silently producing the identity point.\n if (!Fn.isValidNot0(scalar))\n throw new RangeError('invalid scalar: out of range'); // 0 is invalid\n const { p, f } = wnaf.mulSecret(this, scalar, cofactor, normalize);\n return normalize([p, f])[0];\n }\n /**\n * Non-constant-time multiplication. Uses width-4 wNAF with GLV endomorphism splitting\n * when available (two half-width scalars sharing one halved doubling chain).\n * It's faster, but should only be used when you don't care about\n * an exposed secret key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(scalar) {\n const p = this;\n const sc = scalar;\n // Public-scalar callers may need 0, but n and larger values stay rejected here too.\n // Reducing them mod n would turn bad caller input into an accidental identity point.\n if (!Fn.isValid(sc))\n throw new RangeError('invalid scalar: out of range'); // 0 is valid\n if (sc === _0n || p.is0())\n return Point.ZERO;\n if (sc === _1n)\n return p;\n if (wnaf.hasWindowSize(this))\n return wnaf.mulUnsafe(p, sc, normalize); // precomputes\n const points = [];\n const scalars = [];\n pushWnafPair(points, scalars, p, sc);\n return mulAddUnsafe(Point, points, scalars);\n }\n /**\n * Non-constant-time double-scalar multiplication `a\u22C5this + b\u22C5other` (Strauss\u2013Shamir).\n * Both walks share one doubling chain via {@link mulAddUnsafe}, and GLV endomorphism\n * (when available) halves the chain again by splitting each scalar into two half-width\n * parts. Used by ECDSA verification and public-key recovery for `R = u1\u22C5G + u2\u22C5P`.\n * Only for public scalars.\n */\n mulAddUnsafe(a, other, b) {\n aprjpoint(other);\n const points = [];\n const scalars = [];\n pushWnafPair(points, scalars, this, a);\n pushWnafPair(points, scalars, other, b);\n return mulAddUnsafe(Point, points, scalars);\n }\n /**\n * Converts Projective point to affine (x, y) coordinates.\n * (X, Y, Z) \u220B (x=X/Z, y=Y/Z).\n * @param invertedZ - Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch\n */\n toAffine(invertedZ) {\n const p = this;\n let iz = invertedZ;\n if (iz != null && !Fp.isValid(iz))\n throw new RangeError('\"invertedZ\" expected valid field element');\n const { X, Y, Z } = p;\n // Fast-path for normalized points\n if (Fp.eql(Z, Fp.ONE))\n return { x: X, y: Y };\n const is0 = p.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)\n iz = is0 ? Fp.ONE : Fp.inv(Z);\n const x = Fp.mul(X, iz);\n const y = Fp.mul(Y, iz);\n const zz = Fp.mul(Z, iz);\n if (is0)\n return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE))\n throw new Error('invZ was invalid');\n return { x, y };\n }\n /**\n * Checks whether Point is free of torsion elements (is in prime subgroup).\n * Always torsion-free for cofactor=1 curves.\n */\n isTorsionFree() {\n if (cofactor === _1n)\n return true;\n if (isTorsionFree)\n return isTorsionFree(Point, this);\n // unsafe() will use the uncached wNAF path internally, since CURVE_ORDER >= Fn.ORDER\n return wnaf.mulUnsafe(this, CURVE_ORDER).is0();\n }\n clearCofactor() {\n if (cofactor === _1n)\n return this; // Fast-path\n if (clearCofactor)\n return clearCofactor(Point, this);\n // Default fallback assumes the cofactor fits the usual subgroup-scalar\n // multiplyUnsafe() contract. Curves with larger / structured cofactors\n // should define a clearCofactor override anyway (e.g. psi/Frobenius maps).\n return this.multiplyUnsafe(cofactor);\n }\n isSmallOrder() {\n if (cofactor === _1n)\n return this.is0(); // Fast-path\n return this.clearCofactor().is0();\n }\n toBytes(isCompressed = true) {\n abool(isCompressed, 'isCompressed');\n // assertValidity() covers on-curve and subgroup membership. The encoder below repeats the\n // infinity check rather than relying on this call, so it stays correct for any caller.\n this.assertValidity();\n return encodePoint(Point, this, isCompressed);\n }\n toHex(isCompressed = true) {\n return bytesToHex(this.toBytes(isCompressed));\n }\n toString() {\n return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n }\n }\n const normalize = (points) => normalizeZ(Point, points);\n const wnaf = new ScalarMultiplier(Point, randomBytes);\n // Enable W=6 wNAF precomputes. Slows down first publicKey computation.\n // Disable for tiny toy curves, with scalar fields < 6 bits.\n if (wnaf.bits >= 6)\n Point.BASE.precompute(6);\n Object.freeze(Point.prototype);\n Object.freeze(Point);\n return Point;\n}\n// Points start with byte 0x02 when y is even; otherwise 0x03\nfunction pprefix(hasEvenY) {\n return Uint8Array.of(hasEvenY ? 0x02 : 0x03);\n}\nfunction getWLengths(Fp, Fn) {\n return {\n secretKey: Fn.BYTES,\n publicKey: 1 + Fp.BYTES,\n publicKeyUncompressed: 1 + 2 * Fp.BYTES,\n publicKeyHasPrefix: true,\n // Raw compact `(r || s)` signature width; DER and recovered signatures use\n // different lengths outside this helper.\n signature: 2 * Fn.BYTES,\n };\n}\n/**\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n * This helper ensures no signature functionality is present. Less code, smaller bundle size.\n * @param Point - Weierstrass point constructor.\n * @param ecdhOpts - Optional randomness helpers:\n * - `randomBytes` (optional): Optional RNG override.\n * @returns ECDH helper namespace.\n * @example\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n *\n * ```ts\n * import { ecdh } from '@noble/curves/abstract/weierstrass.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const dh = ecdh(p256.Point);\n * const alice = dh.keygen();\n * const shared = dh.getSharedSecret(alice.secretKey, alice.publicKey);\n * ```\n */\nexport function ecdh(Point, ecdhOpts = {}) {\n validatePointCons(Point);\n const { Fn } = Point;\n const randomBytes_ = ecdhOpts.randomBytes === undefined ? wcRandomBytes : ecdhOpts.randomBytes;\n // Keep the advertised seed length aligned with mapHashToField(), which keeps a hard 16-byte\n // minimum even on toy curves.\n const lengths = Object.assign(getWLengths(Point.Fp, Fn), {\n seed: Math.max(getMinHashLength(Fn.ORDER), 16),\n });\n function isValidSecretKey(secretKey) {\n try {\n const num = Fn.fromBytes(secretKey);\n return Fn.isValidNot0(num);\n }\n catch (error) {\n return false;\n }\n }\n function isValidPublicKey(publicKey, isCompressed) {\n const { publicKey: comp, publicKeyUncompressed } = lengths;\n try {\n const l = publicKey.length;\n if (isCompressed === true && l !== comp)\n return false;\n if (isCompressed === false && l !== publicKeyUncompressed)\n return false;\n // SEC 1 \u00A73.2.2: the identity is never a valid public key, even on curves whose codec\n // can decode it.\n return !Point.fromBytes(publicKey).is0();\n }\n catch (error) {\n return false;\n }\n }\n /**\n * Produces cryptographically secure secret key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n function randomSecretKey(seed) {\n seed = seed === undefined ? randomBytes_(lengths.seed) : seed;\n return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);\n }\n /**\n * Computes public key for a secret key. Checks for validity of the secret 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(secretKey, isCompressed = true) {\n return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);\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) {\n const { secretKey, publicKey, publicKeyUncompressed } = lengths;\n const allowedLengths = Fn._lengths;\n if (!isBytes(item))\n return undefined;\n const l = abytes(item, undefined, 'key').length;\n const isPub = l === publicKey || l === publicKeyUncompressed;\n const isSec = l === secretKey || !!allowedLengths?.includes(l);\n // P-521 accepts both 65- and 66-byte secret keys, so overlapping lengths stay ambiguous.\n if (isPub && isSec)\n return undefined;\n return isPub;\n }\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes encoded shared point from secret key A and public key B.\n * Checks: 1) secret key validity 2) shared key is on-curve.\n * Does NOT hash the result or expose the SEC 1 x-coordinate-only `z`.\n * Returns the encoded shared point on purpose: callers that need `x_P`\n * can derive it from the encoded point, but `x_P` alone cannot recover the\n * point/parity back.\n * This helper only exposes the fully validated public-key path, not cofactor DH.\n * @param isCompressed - whether to return compact (default), or full key\n * @returns shared point encoding\n */\n function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {\n if (isProbPub(secretKeyA) === true)\n throw new Error('first arg must be private key');\n if (isProbPub(publicKeyB) === false)\n throw new Error('second arg must be public key');\n const s = Fn.fromBytes(secretKeyA);\n const b = Point.fromBytes(publicKeyB); // checks for being on-curve\n if (b.is0())\n throw new Error('invalid public key: point at infinity');\n return b.multiply(s).toBytes(isCompressed);\n }\n const utils = {\n isValidSecretKey,\n isValidPublicKey,\n randomSecretKey,\n };\n const keygen = createKeygen(randomSecretKey, getPublicKey);\n Object.freeze(utils);\n Object.freeze(lengths);\n return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });\n}\n/**\n * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.\n *\n * @param Point - created using {@link weierstrass} function\n * @param hash - used for 1) message prehash-ing 2) k generation in `sign`, using hmac_drbg(hash)\n * @param ecdsaOpts - rarely needed, see {@link ECDSAOpts}:\n * - `lowS`: Default low-S policy.\n * - `hmac`: HMAC implementation used by RFC6979 DRBG.\n * - `randomBytes`: Optional RNG override.\n * - `bits2int`: Optional hash-to-int conversion override.\n * - `bits2int_modN`: Optional hash-to-int-mod-n conversion override.\n *\n * @returns ECDSA helper namespace.\n * @example\n * Create an ECDSA signer/verifier bundle for one curve implementation.\n *\n * ```ts\n * import { ecdsa } from '@noble/curves/abstract/weierstrass.js';\n * import { p256 } from '@noble/curves/nist.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const p256ecdsa = ecdsa(p256.Point, sha256);\n * const { secretKey, publicKey } = p256ecdsa.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = p256ecdsa.sign(msg, secretKey);\n * const isValid = p256ecdsa.verify(sig, msg, publicKey);\n * ```\n */\nexport function ecdsa(Point, hash, ecdsaOpts = {}) {\n validatePointCons(Point);\n // Custom hash / bits2int hooks are treated as pure functions over validated caller-owned bytes.\n const hash_ = hash;\n ahash(hash_);\n validateObject(ecdsaOpts, {}, {\n hmac: 'function',\n lowS: 'boolean',\n randomBytes: 'function',\n bits2int: 'function',\n bits2int_modN: 'function',\n });\n const opts = Object.assign({}, ecdsaOpts);\n const randomBytes = opts.randomBytes === undefined ? wcRandomBytes : opts.randomBytes;\n const hmac = opts.hmac === undefined\n ? (key, msg) => nobleHmac(hash_, key, msg)\n : opts.hmac;\n const { Fp, Fn } = Point;\n const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;\n // Nonce-inversion blinding in k2sig draws `getMinHashLength(n)` bytes per sign. Probe the RNG\n // once (see {@link probeRandomBytes}, shared with ScalarMultiplier): in environments without\n // working randomness, signing downgrades to Fermat inversion (invertCt) instead of throwing on\n // every sign(). The shape of returned bytes is still validated (by mapHashToField) on every\n // blinded call, where breakage fails closed.\n const blindLength = getMinHashLength(CURVE_ORDER);\n const csprng = probeRandomBytes(randomBytes, blindLength);\n const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, opts);\n const defaultSigOpts = {\n prehash: true,\n lowS: typeof opts.lowS === 'boolean' ? opts.lowS : true,\n format: 'compact',\n extraEntropy: false,\n };\n // SEC 1 4.1.6 public-key recovery tries x = r + jn for j = 0..h. Our recovered-signature\n // format only stores one overflow bit, so it can only distinguish q.x = r from q.x = r + n.\n // A third lift would have the form q.x = r + 2n. Since valid ECDSA r is in 1..n-1, the\n // smallest such lift is 1 + 2n, not 2n.\n const hasLargeRecoveryLifts = CURVE_ORDER * _2n + _1n < Fp.ORDER;\n function isBiggerThanHalfOrder(number) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function validateRS(title, num) {\n if (!Fn.isValidNot0(num))\n throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);\n return num;\n }\n function assertFieldSignIsSupported() {\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't support isOdd\");\n }\n // Recovery id of an affine point (x, y) whose x reduces to signature `r` mod n:\n // bit 0 = y parity, bit 1 = x overflowed the group order (x = r + n).\n function getRecoveryBit(x, y, r) {\n assertFieldSignIsSupported();\n return (x === r ? 0 : 2) | Number(Fp.isOdd(y));\n }\n function assertRecoverableCurve() {\n // ECDSA recovery only supports curves where the current recovery id can distinguish\n // q.x = r and q.x = r + n; larger lifts may need additional `r + n*i` branches.\n // SEC 1 4.1.6 recovers candidates via x = r + jn, but this format only encodes j = 0 or 1.\n // The next possible candidate is q.x = r + 2n, and its smallest valid value is 1 + 2n.\n // To easily get i, we either need to:\n // a. increase amount of valid recid values (4, 5...); OR\n // b. prohibit recovered signatures for those curves.\n if (hasLargeRecoveryLifts)\n throw new Error('\"recovered\" sig type is not supported for cofactor >2 curves');\n }\n function validateSigLength(bytes, format) {\n validateSigFormat(format);\n const size = lengths.signature;\n const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;\n return abytes(bytes, sizer);\n }\n /**\n * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.\n */\n class Signature {\n r;\n s;\n recovery;\n constructor(r, s, recovery) {\n this.r = validateRS('r', r); // r in [1..N-1];\n this.s = validateRS('s', s); // s in [1..N-1];\n if (recovery != null) {\n assertRecoverableCurve();\n if (![0, 1, 2, 3].includes(recovery))\n throw new Error('invalid recovery id');\n this.recovery = recovery;\n }\n Object.freeze(this);\n }\n static fromBytes(bytes, format = defaultSigOpts.format) {\n validateSigLength(bytes, format);\n let recid;\n if (format === 'der') {\n // Valid scalar INTEGERs use at most Fn.BYTES plus one DER sign-padding byte. Keep the\n // total bound conservative so malformed inputs are rejected before parsing any INTEGER.\n if (bytes.length > 2 * Fn.BYTES + 16)\n throw new DER.Err('invalid signature: DER signature too long');\n const { r, s } = DER.toSig(abytes(bytes), Fn.BYTES + 1);\n return new Signature(r, s);\n }\n if (format === 'recovered') {\n recid = bytes[0];\n format = 'compact';\n bytes = bytes.subarray(1);\n }\n const L = lengths.signature / 2;\n const r = bytes.subarray(0, L);\n const s = bytes.subarray(L, L * 2);\n return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);\n }\n static fromHex(hex, format) {\n return this.fromBytes(hexToBytes(hex), format);\n }\n assertRecovery() {\n const { recovery } = this;\n if (recovery == null)\n throw new Error('invalid recovery id: must be present');\n return recovery;\n }\n addRecoveryBit(recovery) {\n return new Signature(this.r, this.s, recovery);\n }\n // Unlike the top-level helper below, this method expects a digest that has\n // already been hashed to the curve's message representative.\n recoverPublicKey(messageHash) {\n const { r, s } = this;\n const recovery = this.assertRecovery();\n const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r;\n if (!Fp.isValid(radj))\n throw new Error('invalid recovery id: sig.r+curve.n != R.x');\n const x = Fp.toBytes(radj);\n const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));\n const ir = Fn.inv(radj); // r^-1\n const h = bits2int_modN(abytes(messageHash, undefined, 'msgHash')); // Truncate hash\n const u1 = Fn.create(-h * ir); // -hr^-1\n const u2 = Fn.create(s * ir); // sr^-1\n // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.\n const Q = Point.BASE.mulAddUnsafe(u1, R, u2);\n if (Q.is0())\n throw new Error('invalid recovery: point at infinify');\n Q.assertValidity();\n return Q;\n }\n // Signatures should be low-s, to prevent malleability.\n hasHighS() {\n return isBiggerThanHalfOrder(this.s);\n }\n toBytes(format = defaultSigOpts.format) {\n validateSigFormat(format);\n if (format === 'der')\n return hexToBytes(DER.hexFromSig(this));\n const { r, s } = this;\n const rb = Fn.toBytes(r);\n const sb = Fn.toBytes(s);\n if (format === 'recovered') {\n assertRecoverableCurve();\n return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);\n }\n return concatBytes(rb, sb);\n }\n toHex(format) {\n return bytesToHex(this.toBytes(format));\n }\n }\n Object.freeze(Signature.prototype);\n Object.freeze(Signature);\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 = opts.bits2int === undefined\n ? function bits2int_def(bytes) {\n // Our custom check \"just in case\", for protection against DoS\n if (bytes.length > 8192)\n throw new Error('input is too large');\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 = bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n }\n : opts.bits2int;\n const bits2int_modN = opts.bits2int_modN === undefined\n ? function bits2int_modN_def(bytes) {\n return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here\n }\n : opts.bits2int_modN;\n const ORDER_MASK = bitMask(fnBits);\n // Pads output with zero as per spec.\n /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */\n function int2octets(num) {\n aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);\n return Fn.toBytes(num);\n }\n function validateMsgAndHash(message, prehash) {\n abytes(message, undefined, 'message');\n return (prehash ? abytes(hash_(message), undefined, 'prehashed message') : message);\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 *\n * Warning: we cannot assume here that message has same amount of bytes as curve order,\n * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.\n */\n function prepSig(message, secretKey, opts) {\n const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with fnBits % 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(message);\n const d = Fn.fromBytes(secretKey); // validate secret key, convert to bigint\n if (!Fn.isValidNot0(d))\n throw new Error('invalid private key');\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (extraEntropy != null && extraEntropy !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n // gen random bytes OR pass as-is\n const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;\n seedArgs.push(abytes(e, undefined, 'extraEntropy')); // check for being bytes\n }\n const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // 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 // To transform k => Signature:\n // q = k\u22C5G\n // r = q.x mod n\n // s = k^-1(m + rd) mod n\n // The nonce inversion is blinded: with random b \u2208 [1,n\u22121], s = (bk)^-1(bm + bdr) per\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. Fn.inv()'s extended-Euclidean\n // loop count depends on its input (cf. Minerva), but here it only ever sees b\u00B7k \u2014 uniformly\n // random, independent of k \u2014 so its timing reveals nothing about the nonce; b also masks d in\n // the products. Without a CSPRNG (probed in ecdsa()) we fall back to Fermat inversion\n // (invertCt), whose control flow is data-independent, at ~4x the inversion cost.\n function k2sig(kBytes) {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n // Important: all mod() calls here must be done over N\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!Fn.isValidNot0(k))\n return; // Valid scalars (including k) must be in 1..N-1\n const q = Point.BASE.multiply(k).toAffine(); // q = k\u22C5G\n const r = Fn.create(q.x); // r = q.x mod n\n if (r === _0n)\n return;\n let s;\n if (csprng !== undefined) {\n // mapHashToField maps 1.5x-order-length uniform bytes into [1, n-1], negligible bias.\n const b = bytesToNumberBE(mapHashToField(csprng(blindLength), CURVE_ORDER));\n const ibk = Fn.inv(Fn.mul(b, k)); // (bk)^-1: inversion input is decorrelated from k\n const bm = Fn.mul(b, m);\n const bd = Fn.mul(b, d);\n s = Fn.create(ibk * Fn.create(bm + bd * r)); // s = (bk)^-1(bm + bdr) = k^-1(m + rd) mod n\n }\n else {\n const ik = invertCt(k, CURVE_ORDER); // k^-1 mod n with data-independent control flow\n s = Fn.create(ik * Fn.create(m + r * d)); // s = k^-1(m + rd) mod n\n }\n if (s === _0n)\n return;\n let recovery = getRecoveryBit(q.x, q.y, r); // recovery bit (2 or 3 when q.x>n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = Fn.neg(s); // if lowS was passed, ensure s is always in the bottom half of N\n recovery ^= 1;\n }\n return new Signature(r, normS, hasLargeRecoveryLifts ? undefined : recovery);\n }\n return { seed, k2sig };\n }\n /**\n * Signs a message or message hash with a secret key.\n * With the default `prehash: true`, raw message bytes are hashed internally;\n * only `{ prehash: false }` expects a caller-supplied digest.\n *\n * ```\n * sign(m, d) where\n * k = rfc6979_hmac_drbg(m, d)\n * (x, y) = G \u00D7 k\n * r = x mod n\n * s = (m + dr) / k mod n\n * ```\n */\n function sign(message, secretKey, opts = {}) {\n const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.\n const drbg = createHmacDrbg(hash_.outputLen, Fn.BYTES, hmac);\n const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G\n return sig.toBytes(opts.format);\n }\n /**\n * Verifies a signature against message and public key.\n * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.\n * 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(signature, message, publicKey, opts = {}) {\n const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);\n publicKey = abytes(publicKey, undefined, 'publicKey');\n message = validateMsgAndHash(message, prehash);\n if (!isBytes(signature)) {\n const end = signature instanceof Signature ? ', use sig.toBytes()' : '';\n throw new Error('verify expects Uint8Array signature' + end);\n }\n validateSigLength(signature, format); // execute this twice because we want loud error\n try {\n const sig = Signature.fromBytes(signature, format);\n const P = Point.fromBytes(publicKey);\n // SEC 1 verification keys must not be the identity, even when the generic point decoder\n // permits infinity for another protocol (for example, a pairing curve).\n if (P.is0())\n return false;\n if (lowS && sig.hasHighS())\n return false;\n const { r, s } = sig;\n const h = bits2int_modN(message); // mod n, not mod p\n const is = Fn.inv(s); // s^-1 mod n\n const u1 = Fn.create(h * is); // u1 = hs^-1 mod n\n const u2 = Fn.create(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.mulAddUnsafe(u1, P, u2); // u1\u22C5G + u2\u22C5P, joint Strauss\u2013Shamir\n if (R.is0())\n return false;\n const q = R.toAffine();\n const v = Fn.create(q.x); // v = R.x mod n\n if (v !== r)\n return false;\n // R is the exact point `recoverPublicKey(r, recid)` reconstructs (sR = hG + rP),\n // so binding the signature to its recovery id only needs R's parity/overflow bits.\n if (format === 'recovered' && sig.recovery !== getRecoveryBit(q.x, q.y, r))\n return false;\n return true;\n }\n catch (e) {\n return false;\n }\n }\n function recoverPublicKey(signature, message, opts = {}) {\n // Top-level recovery mirrors `sign()` / `verify()`: it hashes raw message\n // bytes first unless the caller passes `{ prehash: false }`.\n const { prehash } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash);\n return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();\n }\n // utils.isValidPublicKey() already rejects the identity, so ECDSA needs no shadow copy.\n return Object.freeze({\n keygen,\n getPublicKey,\n getSharedSecret,\n utils,\n lengths,\n Point,\n sign,\n verify,\n recoverPublicKey,\n Signature,\n hash: hash_,\n });\n}\n", "/**\n * NIST P256, P384, P521 curves.\n * https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-256\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256, sha384, sha512 } from '@noble/hashes/sha2.js';\nimport { createFROST } from \"./abstract/frost.js\";\nimport { createHasher, mapToCurveSimpleSWU } from \"./abstract/hash-to-curve.js\";\nimport { createOPRF } from \"./abstract/oprf.js\";\nimport { ecdsa, weierstrass, } from \"./abstract/weierstrass.js\";\nimport {} from \"./utils.js\";\n// p = 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n - 1n\n// a = Fp256.create(BigInt('-3'));\nconst p256_CURVE = /* @__PURE__ */ (() => ({\n p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),\n n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),\n h: BigInt(1),\n a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),\n b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),\n Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),\n Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),\n}))();\n// p = 2n**384n - 2n**128n - 2n**96n + 2n**32n - 1n\nconst p384_CURVE = /* @__PURE__ */ (() => ({\n p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff'),\n n: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'),\n h: BigInt(1),\n a: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc'),\n b: BigInt('0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef'),\n Gx: BigInt('0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'),\n Gy: BigInt('0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'),\n}))();\n// p = 2n**521n - 1n\nconst p521_CURVE = /* @__PURE__ */ (() => ({\n p: BigInt('0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'),\n n: BigInt('0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409'),\n h: BigInt(1),\n a: BigInt('0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc'),\n b: BigInt('0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00'),\n Gx: BigInt('0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66'),\n Gy: BigInt('0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650'),\n}))();\nfunction createSWU(Point, opts) {\n let map;\n // RFC 9380's NIST suites here all use m = 1, so createHasher passes one field element per map.\n // Building the SWU sqrt-ratio helper eagerly adds noticeable `nist.js` import cost, so defer it\n // to first use; after that the cached mapper is reused directly.\n return (scalars) => (map || (map = mapToCurveSimpleSWU(Point.Fp, opts)))(scalars[0]);\n}\n// NIST P256\nconst p256_Point = /* @__PURE__ */ weierstrass(p256_CURVE);\n/**\n * NIST P256 (aka secp256r1, prime256v1) curve, ECDSA and ECDH methods.\n * Hashes inputs with sha256 by default.\n *\n * @example\n * Generate one P-256 keypair, sign a message, and verify it.\n *\n * ```js\n * import { p256 } from '@noble/curves/nist.js';\n * const { secretKey, publicKey } = p256.keygen();\n * const recovered = p256.getPublicKey(secretKey);\n * const peer = p256.keygen();\n * const shared = p256.getSharedSecret(secretKey, peer.publicKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = p256.sign(msg, secretKey, { lowS: true, prehash: true });\n * const isValid = p256.verify(sig, msg, publicKey);\n * // const sigKeccak = p256.sign(keccak256(msg), secretKey, { prehash: false });\n * ```\n */\nexport const p256 = /* @__PURE__ */ ecdsa(p256_Point, sha256);\n/**\n * Hashing / encoding to p256 points / field. RFC 9380 methods.\n * @example\n * Hash one message onto the P-256 curve.\n *\n * ```ts\n * const point = p256_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const p256_hasher = /* @__PURE__ */ (() => {\n return createHasher(p256_Point, createSWU(p256_Point, {\n A: p256_CURVE.a,\n B: p256_CURVE.b,\n Z: p256_Point.Fp.neg(BigInt(10)),\n }), {\n DST: 'P256_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'P256_XMD:SHA-256_SSWU_NU_',\n p: p256_CURVE.p,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n });\n})();\n/**\n * p256 OPRF, defined in RFC 9497.\n * @example\n * Run one blind/evaluate/finalize OPRF round over P-256.\n *\n * ```ts\n * const input = new TextEncoder().encode('hello noble');\n * const keys = p256_oprf.oprf.generateKeyPair();\n * const blind = p256_oprf.oprf.blind(input);\n * const evaluated = p256_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded);\n * const output = p256_oprf.oprf.finalize(input, blind.blind, evaluated);\n * ```\n */\nexport const p256_oprf = /* @__PURE__ */ (() => createOPRF({\n name: 'P256-SHA256',\n Point: p256_Point,\n hash: sha256,\n hashToGroup: p256_hasher.hashToCurve,\n hashToScalar: p256_hasher.hashToScalar,\n}))();\n/**\n * FROST threshold signatures over p256. RFC 9591.\n * @example\n * Create one trusted-dealer package for 2-of-3 p256 signing.\n *\n * ```ts\n * const alice = p256_FROST.Identifier.derive('alice@example.com');\n * const bob = p256_FROST.Identifier.derive('bob@example.com');\n * const carol = p256_FROST.Identifier.derive('carol@example.com');\n * const deal = p256_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const p256_FROST = /* @__PURE__ */ (() => createFROST({\n name: 'FROST-P256-SHA256-v1',\n Point: p256_Point,\n hashToScalar: p256_hasher.hashToScalar,\n hash: sha256,\n}))();\nconst p384_Point = /* @__PURE__ */ weierstrass(p384_CURVE);\n/**\n * NIST P384 (aka secp384r1) curve, ECDSA and ECDH methods. Hashes inputs with sha384 by default.\n * @example\n * Generate one P-384 keypair, sign a message, and verify it.\n *\n * ```ts\n * const { secretKey, publicKey } = p384.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = p384.sign(msg, secretKey);\n * const isValid = p384.verify(sig, msg, publicKey);\n * ```\n */\nexport const p384 = /* @__PURE__ */ ecdsa(p384_Point, sha384);\n/**\n * Hashing / encoding to p384 points / field. RFC 9380 methods.\n * @example\n * Hash one message onto the P-384 curve.\n *\n * ```ts\n * const point = p384_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const p384_hasher = /* @__PURE__ */ (() => {\n return createHasher(p384_Point, createSWU(p384_Point, {\n A: p384_CURVE.a,\n B: p384_CURVE.b,\n Z: p384_Point.Fp.neg(BigInt(12)),\n }), {\n DST: 'P384_XMD:SHA-384_SSWU_RO_',\n encodeDST: 'P384_XMD:SHA-384_SSWU_NU_',\n p: p384_CURVE.p,\n m: 1,\n k: 192,\n expand: 'xmd',\n hash: sha384,\n });\n})();\n/**\n * p384 OPRF, defined in RFC 9497.\n * @example\n * Run one blind/evaluate/finalize OPRF round over P-384.\n *\n * ```ts\n * const input = new TextEncoder().encode('hello noble');\n * const keys = p384_oprf.oprf.generateKeyPair();\n * const blind = p384_oprf.oprf.blind(input);\n * const evaluated = p384_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded);\n * const output = p384_oprf.oprf.finalize(input, blind.blind, evaluated);\n * ```\n */\nexport const p384_oprf = /* @__PURE__ */ (() => createOPRF({\n name: 'P384-SHA384',\n Point: p384_Point,\n hash: sha384,\n hashToGroup: p384_hasher.hashToCurve,\n hashToScalar: p384_hasher.hashToScalar,\n}))();\n// NIST P521\n// RFC 7518 fixes the canonical JWK/JOSE width at 66 bytes:\n// - Section 3.4 says ECDSA octet strings must not omit leading zero octets\n// - Sections 6.2.1.2/6.2.1.3 say P-521 coordinates \"x\"/\"y\" must be 66 octets\n// - Section 6.2.2.1 says private scalar \"d\" must be ceil(log2(n)/8) octets, i.e. 66 for P-521\n// NIST FIPS 186-5 Appendix A.3.3 also routes deterministic ECDSA private keys through Appendix\n// B.2.3, whose Integer-to-Octet-String output has explicit fixed length L; for P-521 that is the\n// same 66-byte order width.\n// RFC 6979 matches that width too: private key x is an integer, while `int2octets(x)` uses\n// rlen = 8 * ceil(qlen/8); for P-521, qlen = 521 so the canonical octet width is 66 bytes.\n// Wycheproof ECDH stores private values as integers, not fixed-width scalar bytes, so it does not\n// require a dedicated 65-byte parser path; the repo tests now normalize those integer fixtures to\n// the canonical 66-byte width before use. There is no good standards or oracle reason to accept\n// exactly 65 bytes here: the coherent choices are canonical 66 only, or a broader integer-style\n// parser across many widths. Since this field parser is fixed-width, keep it canonical and use the\n// default exact-66-byte scalar field path.\n// A dedicated MersenneField primitive would allow speed-ups here: +40% getPublicKey, +23% sign,\n// +53% verify, +53% getSharedSecret.\nconst p521_Point = /* @__PURE__ */ weierstrass(p521_CURVE);\n/**\n * NIST P521 (aka secp521r1) curve, ECDSA and ECDH methods. Hashes inputs with sha512 by default.\n * Deterministic `keygen(seed)` expects 99 seed bytes here because the generic scalar-derivation\n * helper uses `getMinHashLength(n)`, not the 66-byte canonical secret-key width.\n * @example\n * Generate one P-521 keypair, sign a message, and verify it.\n *\n * ```ts\n * const { secretKey, publicKey } = p521.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = p521.sign(msg, secretKey);\n * const isValid = p521.verify(sig, msg, publicKey);\n * ```\n */\nexport const p521 = /* @__PURE__ */ ecdsa(p521_Point, sha512);\n/**\n * Hashing / encoding to p521 points / field. RFC 9380 methods.\n * @example\n * Hash one message onto the P-521 curve.\n *\n * ```ts\n * const point = p521_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const p521_hasher = /* @__PURE__ */ (() => {\n return createHasher(p521_Point, createSWU(p521_Point, {\n A: p521_CURVE.a,\n B: p521_CURVE.b,\n Z: p521_Point.Fp.neg(BigInt(4)),\n }), {\n DST: 'P521_XMD:SHA-512_SSWU_RO_',\n encodeDST: 'P521_XMD:SHA-512_SSWU_NU_',\n p: p521_CURVE.p,\n m: 1,\n k: 256,\n expand: 'xmd',\n hash: sha512,\n });\n})();\n/**\n * p521 OPRF, defined in RFC 9497.\n * @example\n * Run one blind/evaluate/finalize OPRF round over P-521.\n *\n * ```ts\n * const input = new TextEncoder().encode('hello noble');\n * const keys = p521_oprf.oprf.generateKeyPair();\n * const blind = p521_oprf.oprf.blind(input);\n * const evaluated = p521_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded);\n * const output = p521_oprf.oprf.finalize(input, blind.blind, evaluated);\n * ```\n */\nexport const p521_oprf = /* @__PURE__ */ (() => createOPRF({\n name: 'P521-SHA512',\n Point: p521_Point,\n hash: sha512,\n hashToGroup: p521_hasher.hashToCurve,\n hashToScalar: p521_hasher.hashToScalar, // produces L=98 just like in RFC\n}))();\n", "import { LabeledDerive, LabeledExtract, LabeledExpand, concat, encode, I2OSP } from 'hpke'\n \n\nimport { chacha20poly1305 } from '@noble/ciphers/chacha.js'\nimport { gcm } from '@noble/ciphers/aes.js'\nimport { shake128, shake256 } from '@noble/hashes/sha3.js'\nimport { turboshake128, turboshake256 } from '@noble/hashes/sha3-addons.js'\nimport { extract, expand } from '@noble/hashes/hkdf.js'\nimport { sha256, sha384, sha512 } from '@noble/hashes/sha2.js'\nimport { ml_kem512, ml_kem768, ml_kem1024 } from '@noble/post-quantum/ml-kem.js'\nimport { ml_kem768_p256, ml_kem1024_p384, ml_kem768_x25519 } from '@noble/post-quantum/hybrid.js'\nimport { } from '@noble/post-quantum/utils.js'\nimport { x25519 } from '@noble/curves/ed25519.js'\nimport { x448 } from '@noble/curves/ed448.js'\nimport { p256, p384, p521 } from '@noble/curves/nist.js'\n\nconst AES_GCM_P_MAX = 2 ** 36 - 31\nconst CHACHA20_POLY1305_P_MAX = 2 ** 38 - 64\n\n\n\n\n\n\n\n\n\n\nexport const AEAD_AES_128_GCM = () =>\n createAead(0x0001, 'AES-128-GCM', 16, AES_GCM_P_MAX, gcm)\n\n\n\n\n\n\n\n\n\n\nexport const AEAD_AES_256_GCM = () =>\n createAead(0x0002, 'AES-256-GCM', 32, AES_GCM_P_MAX, gcm)\n\n\n\n\n\n\n\n\n\n\nexport const AEAD_ChaCha20Poly1305 = () =>\n createAead(0x0003, 'ChaCha20Poly1305', 32, CHACHA20_POLY1305_P_MAX, chacha20poly1305)\n\nfunction createAead(\n id ,\n name ,\n Nk ,\n P_MAX ,\n cipher ,\n) {\n return {\n id,\n type: 'AEAD',\n name,\n Nk,\n Nn: 12,\n Nt: 16,\n async Seal(key, nonce, aad, pt) {\n if (pt.byteLength > P_MAX) {\n throw new RangeError('\"pt\" exceeds P_MAX')\n }\n return cipher(key, nonce, aad).encrypt(pt)\n },\n async Open(key, nonce, aad, ct) {\n return cipher(key, nonce, aad).decrypt(ct)\n },\n }\n}\n\n\n\n\n\n\n\n\n\n\n\nexport const KDF_HKDF_SHA256 = () =>\n createTwoStageKdf(0x0001, 'HKDF-SHA256', 32, sha256)\n\n\n\n\n\n\n\n\n\n\n\nexport const KDF_HKDF_SHA384 = () =>\n createTwoStageKdf(0x0002, 'HKDF-SHA384', 48, sha384)\n\n\n\n\n\n\n\n\n\n\n\nexport const KDF_HKDF_SHA512 = () =>\n createTwoStageKdf(0x0003, 'HKDF-SHA512', 64, sha512)\n\n\n\n\n\n\n\n\n\n\n\nexport const KDF_SHAKE128 = () =>\n createOneStageKdf(0x0010, 'SHAKE128', 32, shake128)\n\n\n\n\n\n\n\n\n\n\n\nexport const KDF_SHAKE256 = () =>\n createOneStageKdf(0x0011, 'SHAKE256', 64, shake256)\n\n\n\n\n\n\n\n\n\n\n\nexport const KDF_TurboSHAKE128 = () =>\n createOneStageKdf(0x0012, 'TurboSHAKE128', 32, turboshake128, 0x1f)\n\n\n\n\n\n\n\n\n\n\n\nexport const KDF_TurboSHAKE256 = () =>\n createOneStageKdf(0x0013, 'TurboSHAKE256', 64, turboshake256, 0x1f)\n\nfunction createTwoStageKdf(\n id ,\n name ,\n Nh ,\n hash ,\n) {\n return {\n id,\n type: 'KDF',\n name,\n Nh,\n stages: 2,\n async Extract(salt, ikm) {\n return extract(hash, ikm, salt)\n },\n async Expand(prk, info, L) {\n return expand(hash, prk, info, L)\n },\n Derive: Unreachable,\n }\n}\n\nfunction createOneStageKdf(\n id ,\n name ,\n Nh ,\n derive ,\n D ,\n) {\n return {\n id,\n type: 'KDF',\n name,\n Nh,\n stages: 1,\n async Derive(labeled_ikm, L) {\n return derive(labeled_ikm, { dkLen: L, D })\n },\n Extract: Unreachable,\n Expand: Unreachable,\n }\n}\n\nconst Unreachable = () => {\n throw new Error('unreachable')\n}\n\n\n\n\n\n\n\n\n\n\n\nexport const KEM_DHKEM_P256_HKDF_SHA256 = () =>\n createDhKemNist({\n id: 0x0010,\n name: 'DHKEM(P-256, HKDF-SHA256)',\n Nsecret: 32,\n Nenc: 65,\n Npk: 65,\n Nsk: 32,\n curve: p256,\n kdf: KDF_HKDF_SHA256,\n order: 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n,\n bitmask: 0xff,\n })\n\n\n\n\n\n\n\n\n\n\n\nexport const KEM_DHKEM_P384_HKDF_SHA384 = () =>\n createDhKemNist({\n id: 0x0011,\n name: 'DHKEM(P-384, HKDF-SHA384)',\n Nsecret: 48,\n Nenc: 97,\n Npk: 97,\n Nsk: 48,\n curve: p384,\n kdf: KDF_HKDF_SHA384,\n order:\n 0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973n,\n bitmask: 0xff,\n })\n\n\n\n\n\n\n\n\n\n\n\nexport const KEM_DHKEM_P521_HKDF_SHA512 = () =>\n createDhKemNist({\n id: 0x0012,\n name: 'DHKEM(P-521, HKDF-SHA512)',\n Nsecret: 64,\n Nenc: 133,\n Npk: 133,\n Nsk: 66,\n curve: p521,\n kdf: KDF_HKDF_SHA512,\n order:\n 0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409n,\n bitmask: 0x01,\n })\n\n\n\n\n\n\n\n\n\n\n\nexport const KEM_DHKEM_X25519_HKDF_SHA256 = () =>\n createDhKemX({\n id: 0x0020,\n name: 'DHKEM(X25519, HKDF-SHA256)',\n Nsecret: 32,\n Nenc: 32,\n Npk: 32,\n Nsk: 32,\n curve: x25519,\n kdf: KDF_HKDF_SHA256,\n })\n\n\n\n\n\n\n\n\n\n\n\nexport const KEM_DHKEM_X448_HKDF_SHA512 = () =>\n createDhKemX({\n id: 0x0021,\n name: 'DHKEM(X448, HKDF-SHA512)',\n Nsecret: 64,\n Nenc: 56,\n Npk: 56,\n Nsk: 56,\n curve: x448,\n kdf: KDF_HKDF_SHA512,\n })\n\n\n\n\n\n\n\n\n\n\nexport const KEM_ML_KEM_512 = () =>\n createPqKem({\n id: 0x0040,\n name: 'ML-KEM-512',\n Nsecret: 32,\n Nenc: 768,\n Npk: 800,\n Nsk: 64,\n kem: ml_kem512,\n })\n\n\n\n\n\n\n\n\n\n\nexport const KEM_ML_KEM_768 = () =>\n createPqKem({\n id: 0x0041,\n name: 'ML-KEM-768',\n Nsecret: 32,\n Nenc: 1088,\n Npk: 1184,\n Nsk: 64,\n kem: ml_kem768,\n })\n\n\n\n\n\n\n\n\n\n\nexport const KEM_ML_KEM_1024 = () =>\n createPqKem({\n id: 0x0042,\n name: 'ML-KEM-1024',\n Nsecret: 32,\n Nenc: 1568,\n Npk: 1568,\n Nsk: 64,\n kem: ml_kem1024,\n })\n\n\n\n\n\n\n\n\nexport const KEM_MLKEM768_X25519 = () =>\n createPqKem({\n id: 0x647a,\n name: 'MLKEM768-X25519',\n Nsecret: 32,\n Nenc: 1120,\n Npk: 1216,\n Nsk: 32,\n kem: ml_kem768_x25519,\n })\n\n\n\n\n\n\n\n\nexport const KEM_MLKEM768_P256 = () =>\n createPqKem({\n id: 0x0050,\n name: 'MLKEM768-P256',\n Nsecret: 32,\n Nenc: 1153,\n Npk: 1249,\n Nsk: 32,\n kem: ml_kem768_p256,\n })\n\n\n\n\n\n\n\n\nexport const KEM_MLKEM1024_P384 = () =>\n createPqKem({\n id: 0x0051,\n name: 'MLKEM1024-P384',\n Nsecret: 32,\n Nenc: 1665,\n Npk: 1665,\n Nsk: 32,\n kem: ml_kem1024_p384,\n })\n\nfunction createPqKem(config \n \n \n \n \n \n \n \n ) {\n const { id, name, Nsecret, Nenc, Npk, Nsk, kem: nobleKem } = config\n const suite_id = concat(encode('KEM'), I2OSP(id, 2))\n\n Object.freeze(NobleKey.prototype)\n const algorithm = { name }\n\n return {\n id,\n type: 'KEM',\n name,\n Nsecret,\n Nenc,\n Npk,\n Nsk,\n async DeriveKeyPair(ikm, extractable) {\n const seed = await LabeledDerive(\n {\n async Derive(ikm, L) {\n return shake256(ikm, { dkLen: L })\n },\n },\n suite_id,\n ikm,\n encode('DeriveKeyPair'),\n new Uint8Array(),\n Nsk,\n )\n const { secretKey, publicKey } = nobleKem.keygen(seed)\n\n return {\n privateKey: new NobleKey(priv, 'private', secretKey, extractable, algorithm, seed),\n publicKey: new NobleKey(priv, 'public', publicKey, true, algorithm),\n }\n },\n async GenerateKeyPair(extractable) {\n const ikm = crypto.getRandomValues(new Uint8Array(Nsk))\n return await this.DeriveKeyPair(ikm, extractable)\n },\n async SerializePublicKey(key) {\n NobleKey.validate(key, algorithm, true)\n return key.value(priv)\n },\n async DeserializePublicKey(key) {\n return new NobleKey(priv, 'public', slice(key), true, algorithm)\n },\n async SerializePrivateKey(key) {\n NobleKey.validate(key, algorithm, true)\n return (key ).seed(priv)\n },\n async DeserializePrivateKey(key, extractable) {\n const { secretKey } = nobleKem.keygen(key)\n return new NobleKey(priv, 'private', secretKey, extractable, algorithm, slice(key))\n },\n async Encap(pkR) {\n NobleKey.validate(pkR, algorithm)\n const { cipherText, sharedSecret } = nobleKem.encapsulate((pkR ).value(priv))\n return { shared_secret: sharedSecret, enc: cipherText }\n },\n async Decap(enc, skR) {\n NobleKey.validate(skR, algorithm)\n return nobleKem.decapsulate(enc, (skR ).value(priv))\n },\n }\n}\n\nasync function deriveSharedSecret(\n kdf ,\n suite_id ,\n Nsecret ,\n dh ,\n enc ,\n pkRm ,\n) {\n const kem_context = concat(enc, pkRm)\n const eae_prk = await LabeledExtract(kdf, suite_id, new Uint8Array(), encode('eae_prk'), dh)\n return LabeledExpand(kdf, suite_id, eae_prk, encode('shared_secret'), kem_context, Nsecret)\n}\n\nfunction createDhKemNist(config \n \n \n \n \n \n \n \n \n \n \n ) {\n const { id, name, Nsecret, Nenc, Npk, Nsk, curve, kdf: kdfFactory, order, bitmask } = config\n const kdf = kdfFactory()\n const suite_id = concat(encode('KEM'), I2OSP(id, 2))\n const algorithm = { name }\n\n async function deriveKeyPair(ikm , extractable ) {\n const dkp_prk = await LabeledExtract(kdf, suite_id, new Uint8Array(), encode('dkp_prk'), ikm)\n\n \n let sk = 0n\n let counter = 0\n let bytes \n\n do {\n if (counter > 255) throw new Error('Key derivation failed')\n bytes = await LabeledExpand(\n kdf,\n suite_id,\n dkp_prk,\n encode('candidate'),\n Uint8Array.of(counter),\n Nsk,\n )\n bytes[0] &= bitmask\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n sk = 0n\n \n \n \n \n \n for (let i = 0; i < Nsk; i += 8) {\n const remaining = Nsk - i\n if (remaining >= 8) {\n sk = (sk << 64n) | view.getBigUint64(i, false)\n } else {\n sk = (sk << BigInt(remaining * 8)) | BigInt(view.getUint16(i, false))\n }\n }\n counter++\n } while (sk === 0n || sk >= order)\n\n const secretKey = bytes \n const publicKey = curve.getPublicKey(secretKey, false)\n\n curve.Point.fromBytes(publicKey).assertValidity()\n\n return {\n privateKey: new NobleKey(priv, 'private', secretKey, extractable, { name }),\n publicKey: new NobleKey(priv, 'public', publicKey, true, { name }),\n }\n }\n\n Object.freeze(NobleKey.prototype)\n return {\n id,\n type: 'KEM',\n name,\n Nsecret,\n Nenc,\n Npk,\n Nsk,\n async DeriveKeyPair(ikm, extractable) {\n return await deriveKeyPair(ikm, extractable)\n },\n async GenerateKeyPair(extractable) {\n const ikm = crypto.getRandomValues(new Uint8Array(Nsk))\n return await this.DeriveKeyPair(ikm, extractable)\n },\n async SerializePublicKey(key) {\n NobleKey.validate(key, algorithm, true)\n return key.value(priv)\n },\n async DeserializePublicKey(key) {\n curve.Point.fromBytes(key).assertValidity()\n return new NobleKey(priv, 'public', slice(key), true, algorithm)\n },\n async SerializePrivateKey(key) {\n NobleKey.validate(key, algorithm, true)\n return (key ).value(priv)\n },\n async DeserializePrivateKey(key, extractable) {\n if (!curve.utils.isValidSecretKey(key)) {\n throw new Error('Invalid scalar')\n }\n return new NobleKey(priv, 'private', slice(key), extractable, algorithm)\n },\n async Encap(pkR) {\n NobleKey.validate(pkR, algorithm)\n\n const pkRValue = (pkR ).value(priv)\n curve.Point.fromBytes(pkRValue).assertValidity()\n\n const ekp = await this.GenerateKeyPair(false)\n const skE = (ekp.privateKey ).value(priv)\n const enc = (ekp.publicKey ).value(priv)\n\n const dh = slice(curve.getSharedSecret(skE, pkRValue), 1)\n\n return {\n shared_secret: await deriveSharedSecret(kdf, suite_id, Nsecret, dh, enc, pkRValue),\n enc,\n }\n },\n async Decap(enc, skR, pkR) {\n NobleKey.validate(skR, algorithm)\n\n const skRValue = (skR ).value(priv)\n pkR ??= (await this.DeserializePublicKey(curve.getPublicKey(skRValue, false))) \n NobleKey.validate(pkR, algorithm)\n\n const pkE = (await this.DeserializePublicKey(enc)) \n const pkEValue = pkE.value(priv)\n const dh = slice(curve.getSharedSecret(skRValue, pkEValue), 1)\n\n return await deriveSharedSecret(\n kdf,\n suite_id,\n Nsecret,\n dh,\n enc,\n (pkR ).value(priv),\n )\n },\n }\n}\n\nfunction createDhKemX(config \n \n \n \n \n \n \n \n \n ) {\n const { id, name, Nsecret, Nenc, Npk, Nsk, curve, kdf: kdfFactory } = config\n const kdf = kdfFactory()\n const suite_id = concat(encode('KEM'), I2OSP(id, 2))\n const algorithm = { name }\n\n Object.freeze(NobleKey.prototype)\n return {\n id,\n type: 'KEM',\n name,\n Nsecret,\n Nenc,\n Npk,\n Nsk,\n async DeriveKeyPair(ikm, extractable) {\n const dkp_prk = await LabeledExtract(kdf, suite_id, new Uint8Array(), encode('dkp_prk'), ikm)\n const sk = await LabeledExpand(kdf, suite_id, dkp_prk, encode('sk'), new Uint8Array(), Nsk)\n const pk = curve.getPublicKey(sk)\n\n return {\n privateKey: new NobleKey(priv, 'private', sk, extractable, algorithm),\n publicKey: new NobleKey(priv, 'public', pk, true, algorithm),\n }\n },\n async GenerateKeyPair(extractable) {\n const ikm = crypto.getRandomValues(new Uint8Array(Nsk))\n return await this.DeriveKeyPair(ikm, extractable)\n },\n async SerializePublicKey(key) {\n NobleKey.validate(key, algorithm, true)\n return key.value(priv)\n },\n async DeserializePublicKey(key) {\n return new NobleKey(priv, 'public', slice(key), true, algorithm)\n },\n async SerializePrivateKey(key) {\n NobleKey.validate(key, algorithm, true)\n return (key ).value(priv)\n },\n async DeserializePrivateKey(key, extractable) {\n return new NobleKey(priv, 'private', slice(key), extractable, algorithm)\n },\n async Encap(pkR) {\n NobleKey.validate(pkR, algorithm)\n\n const ekp = await this.GenerateKeyPair(false)\n const enc = (ekp.publicKey ).value(priv)\n const dh = curve.getSharedSecret(\n (ekp.privateKey ).value(priv),\n (pkR ).value(priv),\n )\n\n return {\n shared_secret: await deriveSharedSecret(\n kdf,\n suite_id,\n Nsecret,\n dh,\n enc,\n (pkR ).value(priv),\n ),\n enc,\n }\n },\n async Decap(enc, skR, pkR) {\n NobleKey.validate(skR, algorithm)\n\n const skRValue = (skR ).value(priv)\n pkR ??= (await this.DeserializePublicKey(curve.getPublicKey(skRValue))) \n NobleKey.validate(pkR, algorithm)\n\n const pkE = (await this.DeserializePublicKey(enc)) \n const dh = curve.getSharedSecret(skRValue, pkE.value(priv))\n\n return await deriveSharedSecret(\n kdf,\n suite_id,\n Nsecret,\n dh,\n enc,\n (pkR ).value(priv),\n )\n },\n }\n}\n\nconst InvalidInvocation = (_ ) => {\n if (_ !== priv) {\n throw new Error('invalid invocation')\n }\n}\nconst priv = /* @__PURE__ */ Symbol()\nclass NobleKey {\n #type \n #extractable \n #algorithm \n #value \n #seed \n\n static #isValid(key ) {\n return key.#algorithm !== undefined\n }\n\n static validate(\n key ,\n algorithm ,\n extractable ,\n ) {\n if ((key ).algorithm?.name !== algorithm.name) {\n throw new TypeError(`key algorithm must be ${algorithm.name}`)\n }\n try {\n if (!NobleKey.#isValid(key )) {\n throw new TypeError('unexpected key constructor')\n }\n } catch {\n throw new TypeError('unexpected key constructor')\n }\n if (extractable && !(key ).extractable) {\n throw new TypeError('key must be extractable')\n }\n }\n\n constructor(\n _ ,\n type ,\n value ,\n extractable ,\n algorithm ,\n seed ,\n ) {\n InvalidInvocation(_)\n this.#type = type\n this.#value = value\n this.#extractable = extractable\n this.#algorithm = algorithm\n this.#seed = seed\n }\n\n get algorithm() {\n return { name: this.#algorithm.name }\n }\n\n get extractable() {\n return this.#extractable\n }\n\n get type() {\n return this.#type\n }\n\n value(_ ) {\n InvalidInvocation(_)\n return slice(this.#value)\n }\n\n seed(_ ) {\n InvalidInvocation(_)\n return slice(this.#seed )\n }\n}\n\nfunction slice(buffer , start , end ) {\n return Uint8Array.prototype.slice.call(buffer, start, end)\n}\n", "/**\n * ML-DSA: Module Lattice-based Digital Signature Algorithm from\n * [FIPS-204](https://csrc.nist.gov/pubs/fips/204/ipd). A.k.a. CRYSTALS-Dilithium.\n *\n * Has similar internals to ML-KEM, but their keys and params are different.\n * Check out [official site](https://www.pq-crystals.org/dilithium/index.shtml),\n * [repo](https://github.com/pq-crystals/dilithium).\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { abool } from '@noble/curves/utils.js';\nimport { shake256 } from '@noble/hashes/sha3.js';\nimport { genCrystals, XOF128, XOF256 } from \"./_crystals.js\";\nimport { abytes, checkHash, cleanBytes, equalBytes, getMessage, getMessagePrehash, randomBytes, splitCoder, validateSigOpts, validateVerOpts, checkOptKeys, vecCoder, } from \"./utils.js\";\n/**\n * Keys each internal surface accepts.\n *\n * `context` is deliberately absent from both. The internal functions never read it: the\n * public wrappers consume it when they format `M'` and must not pass it down, because a\n * key that is accepted and then not acted on is the same silent downgrade this validation\n * exists to prevent. `externalMu` is the mirror case, existing here and rejected above.\n * `extraEntropy` is signing-only, so verification does not take it either.\n */\nconst INTERNAL_SIG_OPT_KEYS = /* @__PURE__ */ Object.freeze([\n 'extraEntropy',\n 'externalMu',\n]);\nconst INTERNAL_VER_OPT_KEYS = /* @__PURE__ */ Object.freeze(['externalMu']);\nfunction validateInternalOpts(opts, allowed) {\n const normalized = checkOptKeys(opts, allowed);\n if (normalized.externalMu !== undefined)\n abool(normalized.externalMu, 'opts.externalMu');\n return normalized;\n}\n// Constants\n// FIPS 204 fixes ML-DSA over R = Z[X]/(X^256 + 1), so every polynomial has 256 coefficients.\nconst N = 256;\n// 2**23 \u2212 2**13 + 1, 23 bits: multiply will be 46. We have enough precision in JS to avoid bigints\nconst Q = 8380417;\n// FIPS 204 \u00A72.5 / Table 1 fixes zeta = 1753 as the 512th root of unity used by ML-DSA's NTT.\nconst ROOT_OF_UNITY = 1753;\n// f = 256**\u22121 mod q, pow(256, -1, q) = 8347681 (python3)\nconst F = 8347681;\n// FIPS 204 Table 1 / \u00A77.4 fixes d = 13 dropped low bits for Power2Round on t.\nconst D = 13;\n// FIPS 204 Table 1 fixes gamma2 to (q-1)/88 for ML-DSA-44 and (q-1)/32 for ML-DSA-65/87;\n// \u00A77.4 then uses alpha = 2*gamma2 for Decompose / MakeHint / UseHint.\n// Dilithium is kinda parametrized over GAMMA2, but everything will break with any other value.\nconst GAMMA2_1 = Math.floor((Q - 1) / 88) | 0;\nconst GAMMA2_2 = Math.floor((Q - 1) / 32) | 0;\n/** Internal params for different versions of ML-DSA */\n// prettier-ignore\n/** Built-in ML-DSA parameter presets keyed by security categories `2/3/5`\n * for `ml_dsa44` / `ml_dsa65` / `ml_dsa87`.\n * This is only the Table 1 subset used directly here: `BETA = TAU * ETA` is derived later,\n * while `C_TILDE_BYTES`, `TR_BYTES`, `CRH_BYTES`, and `securityLevel` live in the preset wrappers.\n */\nexport const PARAMS = /* @__PURE__ */ (() => Object.freeze({\n 2: Object.freeze({\n K: 4, L: 4, D, GAMMA1: 2 ** 17, GAMMA2: GAMMA2_1, TAU: 39, ETA: 2, OMEGA: 80\n }),\n 3: Object.freeze({\n K: 6, L: 5, D, GAMMA1: 2 ** 19, GAMMA2: GAMMA2_2, TAU: 49, ETA: 4, OMEGA: 55\n }),\n 5: Object.freeze({\n K: 8, L: 7, D, GAMMA1: 2 ** 19, GAMMA2: GAMMA2_2, TAU: 60, ETA: 2, OMEGA: 75\n }),\n}))();\nconst newPoly = (n) => new Int32Array(n);\n// Shared CRYSTALS helper in the ML-DSA branch: non-Kyber mode, 8-bit bit-reversal,\n// and Int32Array polys because ordinary-form coefficients can be negative / centered.\nconst crystals = /* @__PURE__ */ genCrystals({\n N,\n Q,\n F,\n ROOT_OF_UNITY,\n newPoly,\n isKyber: false,\n brvBits: 8,\n});\nconst id = (n) => n;\n// compress()/verify() must be compatible in both directions:\n// wrap the shared d-bit packer with the FIPS 204 SimpleBitPack / BitPack coefficient maps.\n// malformed-input rejection only happens through the optional verify hook.\nconst polyCoder = (d, compress = id, verify = id) => crystals.bitsCoder(d, {\n encode: (i) => compress(verify(i)),\n decode: (i) => verify(compress(i)),\n});\n// Mutates `a` in place; callers must pass same-length polynomials.\n// NOTE: conditional-reduction variants (as in ml-kem) were measured performance-neutral here \u2014\n// int32 `%` with 23-bit Q is already cheap \u2014 so the simpler mod() form is kept for audit.\nconst polyAdd = (a_, b_) => {\n const a = a_;\n const b = b_;\n for (let i = 0; i < a.length; i++)\n a[i] = crystals.mod(a[i] + b[i]);\n return a;\n};\n// Mutates `a` in place; callers must pass same-length polynomials.\nconst polySub = (a_, b_) => {\n const a = a_;\n const b = b_;\n for (let i = 0; i < a.length; i++)\n a[i] = crystals.mod(a[i] - b[i]);\n return a;\n};\n// Mutates `p` in place and assumes it is a decoded `t1`-range polynomial.\nconst polyShiftl = (p_) => {\n const p = p_;\n for (let i = 0; i < N; i++)\n p[i] <<= D;\n return p;\n};\nconst polyChknorm = (p_, B) => {\n const p = p_;\n // FIPS 204 Algorithms 7 and 8 express the same centered-norm check with explicit inequalities.\n for (let i = 0; i < N; i++)\n if (Math.abs(crystals.smod(p[i])) >= B)\n return true;\n return false;\n};\n// Both inputs must already be in NTT / `T_q` form.\nconst MultiplyNTTs = (a_, b_) => {\n const a = a_;\n const b = b_;\n // NOTE: we don't use montgomery reduction in code, since it requires 64 bit ints,\n // which is not available in JS. mod(a[i] * b[i]) is ok, since Q is 23 bit,\n // which means a[i] * b[i] is 46 bit, which is safe to use in JS. (number is 53 bits).\n // Barrett reduction is slower than mod :(\n const c = newPoly(N);\n for (let i = 0; i < a.length; i++)\n c[i] = crystals.mod(a[i] * b[i]);\n return c;\n};\n// Return poly in NTT representation\nfunction RejNTTPoly(xof_) {\n const xof = xof_;\n // Samples a polynomial \u2208 Tq. xof() must return byte lengths divisible by 3.\n const r = newPoly(N);\n // NOTE: we can represent 3xu24 as 4xu32, but it doesn't improve perf :(\n for (let j = 0; j < N;) {\n const b = xof();\n if (b.length % 3)\n throw new Error('RejNTTPoly: unaligned block');\n for (let i = 0; j < N && i <= b.length - 3; i += 3) {\n // FIPS 204 Algorithm 14 clears the top bit of b2 before forming the 23-bit candidate.\n const t = (b[i + 0] | (b[i + 1] << 8) | (b[i + 2] << 16)) & 0x7fffff; // 3 bytes\n if (t < Q)\n r[j++] = t;\n }\n }\n return r;\n}\n// Instantiate one ML-DSA parameter set from the Table 1 lattice constants plus the\n// Table 2 byte lengths / hash-width choices used by the public wrappers below.\nfunction getDilithium(opts_) {\n const opts = opts_;\n const { K, L, GAMMA1, GAMMA2, TAU, ETA, OMEGA } = opts;\n const { CRH_BYTES, TR_BYTES, C_TILDE_BYTES, XOF128, XOF256, securityLevel } = opts;\n if (![2, 4].includes(ETA))\n throw new Error('Wrong ETA');\n if (![1 << 17, 1 << 19].includes(GAMMA1))\n throw new Error('Wrong GAMMA1');\n if (![GAMMA2_1, GAMMA2_2].includes(GAMMA2))\n throw new Error('Wrong GAMMA2');\n const BETA = TAU * ETA;\n const decompose = (r) => {\n // Decomposes r into (r1, r0) such that r \u2261 r1(2\u03B32) + r0 mod q.\n const rPlus = crystals.mod(r);\n const r0 = crystals.smod(rPlus, 2 * GAMMA2) | 0;\n // FIPS 204 Algorithm 36 folds the top bucket `q-1` back to `(r1, r0) = (0, r0-1)`.\n if (rPlus - r0 === Q - 1)\n return { r1: 0 | 0, r0: (r0 - 1) | 0 };\n const r1 = Math.floor((rPlus - r0) / (2 * GAMMA2)) | 0;\n return { r1, r0 }; // r1 = HighBits, r0 = LowBits\n };\n const HighBits = (r) => decompose(r).r1;\n const LowBits = (r) => decompose(r).r0;\n const MakeHint = (z, r) => {\n // Compute hint bit indicating whether adding z to r alters the high bits of r.\n // FIPS 204 \u00A76.2 also permits the Section 5.1 alternative from [6], which uses the\n // transformed low-bits/high-bits state at this call site instead of Algorithm 39 literally.\n // This optimized predicate only applies to those transformed Section 5.1 inputs; it is\n // not a drop-in replacement for Algorithm 39 on arbitrary `(z, r)` pairs.\n // From dilithium code\n const res0 = z <= GAMMA2 || z > Q - GAMMA2 || (z === Q - GAMMA2 && r === 0) ? 0 : 1;\n // from FIPS204:\n // // const r1 = HighBits(r);\n // // const v1 = HighBits(r + z);\n // // const res1 = +(r1 !== v1);\n // But they return different results! However, decompose is same.\n // So, either there is a bug in Dilithium ref implementation or in FIPS204.\n // For now, lets use dilithium one, so test vectors can be passed.\n // The round-3 Dilithium / ML-DSA code uses the same low-bits / high-bits convention after\n // `r0 += ct0`.\n // See dilithium-py README section \"Optimising decomposition and making hints\".\n return res0;\n };\n // m = (q-1)/(2\u03B32): 44 for ML-DSA-44, 16 for 65/87. Hoisted out of UseHint, which runs\n // per coefficient during verification.\n const HINT_M = Math.floor((Q - 1) / (2 * GAMMA2));\n const UseHint = (h, r) => {\n // Returns the high bits of r adjusted according to hint h\n const { r1, r0 } = decompose(r);\n // 3: if h = 1 and r0 > 0 return (r1 + 1) mod m\n // 4: if h = 1 and r0 \u2264 0 return (r1 \u2212 1) mod m\n if (h === 1)\n return r0 > 0 ? crystals.mod(r1 + 1, HINT_M) | 0 : crystals.mod(r1 - 1, HINT_M) | 0;\n return r1 | 0;\n };\n const Power2Round = (r) => {\n // Decomposes r into (r1, r0) such that r \u2261 r1*(2**d) + r0 mod q.\n const rPlus = crystals.mod(r);\n const r0 = crystals.smod(rPlus, 2 ** D) | 0;\n return { r1: Math.floor((rPlus - r0) / 2 ** D) | 0, r0 };\n };\n const hintCoder = {\n bytesLen: OMEGA + K,\n encode: (h_) => {\n const h = h_;\n if (h === false)\n throw new Error('hint.encode: hint is false'); // should never happen\n const res = new Uint8Array(OMEGA + K);\n for (let i = 0, k = 0; i < K; i++) {\n for (let j = 0; j < N; j++)\n if (h[i][j] !== 0)\n res[k++] = j;\n res[OMEGA + i] = k;\n }\n return res;\n },\n decode: (buf) => {\n const h = [];\n let k = 0;\n for (let i = 0; i < K; i++) {\n const hi = newPoly(N);\n if (buf[OMEGA + i] < k || buf[OMEGA + i] > OMEGA)\n return false;\n for (let j = k; j < buf[OMEGA + i]; j++) {\n if (j > k && buf[j] <= buf[j - 1])\n return false;\n hi[buf[j]] = 1;\n }\n k = buf[OMEGA + i];\n h.push(hi);\n }\n for (let j = k; j < OMEGA; j++)\n if (buf[j] !== 0)\n return false;\n return h;\n },\n };\n const ETACoder = polyCoder(ETA === 2 ? 3 : 4, (i) => ETA - i, (i) => {\n if (!(-ETA <= i && i <= ETA))\n throw new Error(`malformed key s1/s3 ${i} outside of ETA range [${-ETA}, ${ETA}]`);\n return i;\n });\n const T0Coder = polyCoder(13, (i) => (1 << (D - 1)) - i);\n const T1Coder = polyCoder(10);\n // Requires smod. Need to fix!\n const ZCoder = polyCoder(GAMMA1 === 1 << 17 ? 18 : 20, (i) => crystals.smod(GAMMA1 - i));\n const W1Coder = polyCoder(GAMMA2 === GAMMA2_1 ? 6 : 4);\n const W1Vec = vecCoder(W1Coder, K);\n // Main structures\n const publicCoder = splitCoder('publicKey', 32, vecCoder(T1Coder, K));\n const secretCoder = splitCoder('secretKey', 32, 32, TR_BYTES, vecCoder(ETACoder, L), vecCoder(ETACoder, K), vecCoder(T0Coder, K));\n const sigCoder = splitCoder('signature', C_TILDE_BYTES, vecCoder(ZCoder, L), hintCoder);\n const CoefFromHalfByte = ETA === 2\n ? (n) => (n < 15 ? 2 - (n % 5) : false)\n : (n) => (n < 9 ? 4 - n : false);\n // Return poly in ordinary representation.\n // This helper returns ordinary-form `[-ETA, ETA]` coefficients for ExpandS; callers apply\n // `NTT.encode()` later when needed.\n function RejBoundedPoly(xof_) {\n const xof = xof_;\n // Samples an element a \u2208 Rq with coeffcients in [\u2212\u03B7, \u03B7] computed via rejection sampling from \u03C1.\n const r = newPoly(N);\n for (let j = 0; j < N;) {\n const b = xof();\n for (let i = 0; j < N && i < b.length; i += 1) {\n // half byte. Should be superfast with vector instructions. But very slow with js :(\n const d1 = CoefFromHalfByte(b[i] & 0x0f);\n const d2 = CoefFromHalfByte((b[i] >> 4) & 0x0f);\n if (d1 !== false)\n r[j++] = d1;\n if (j < N && d2 !== false)\n r[j++] = d2;\n }\n }\n return r;\n }\n const SampleInBall = (seed) => {\n // Samples a polynomial c \u2208 Rq with coeffcients from {\u22121, 0, 1} and Hamming weight \u03C4\n const pre = newPoly(N);\n const s = shake256.create({}).update(seed);\n const buf = new Uint8Array(shake256.blockLen);\n s.xofInto(buf);\n // FIPS 204 Algorithm 29 uses the first 8 squeezed bytes as the 64 sign bits `h`,\n // then rejection-samples coefficient positions from the remaining XOF stream.\n const masks = buf.slice(0, 8);\n for (let i = N - TAU, pos = 8, maskPos = 0, maskBit = 0; i < N; i++) {\n let b = i + 1;\n for (; b > i;) {\n b = buf[pos++];\n if (pos < shake256.blockLen)\n continue;\n s.xofInto(buf);\n pos = 0;\n }\n pre[i] = pre[b];\n pre[b] = 1 - (((masks[maskPos] >> maskBit++) & 1) << 1);\n if (maskBit >= 8) {\n maskPos++;\n maskBit = 0;\n }\n }\n return pre;\n };\n const polyPowerRound = (p_) => {\n const p = p_;\n const res0 = newPoly(N);\n const res1 = newPoly(N);\n for (let i = 0; i < p.length; i++) {\n const { r0, r1 } = Power2Round(p[i]);\n res0[i] = r0;\n res1[i] = r1;\n }\n return { r0: res0, r1: res1 };\n };\n const polyUseHint = (u_, h_) => {\n const u = u_;\n const h = h_;\n // In-place on `u`: verification only needs the recovered high bits, so reuse the\n // temporary `wApprox` buffer instead of allocating another polynomial.\n for (let i = 0; i < N; i++)\n u[i] = UseHint(h[i], u[i]);\n return u;\n };\n const polyMakeHint = (a_, b_) => {\n const a = a_;\n const b = b_;\n const v = newPoly(N);\n let cnt = 0;\n for (let i = 0; i < N; i++) {\n const h = MakeHint(a[i], b[i]);\n v[i] = h;\n cnt += h;\n }\n return { v, cnt };\n };\n const signRandBytes = 32;\n const seedCoder = splitCoder('seed', 32, 64, 32);\n // API & argument positions are exactly as in FIPS204.\n const internal = Object.freeze({\n info: Object.freeze({ type: 'internal-ml-dsa' }),\n lengths: Object.freeze({\n secretKey: secretCoder.bytesLen,\n publicKey: publicCoder.bytesLen,\n seed: 32,\n signature: sigCoder.bytesLen,\n signRand: signRandBytes,\n }),\n keygen: (seed) => {\n // H(\uD835\uDF09||IntegerToBytes(\uD835\uDC58, 1)||IntegerToBytes(\u2113, 1), 128) 2: \u25B7 expand seed\n const seedDst = new Uint8Array(32 + 2);\n const randSeed = seed === undefined;\n if (randSeed)\n seed = randomBytes(32);\n abytes(seed, 32, 'seed');\n seedDst.set(seed);\n if (randSeed)\n cleanBytes(seed);\n seedDst[32] = K;\n seedDst[33] = L;\n const [rho, rhoPrime, K_] = seedCoder.decode(shake256(seedDst, { dkLen: seedCoder.bytesLen }));\n const xofPrime = XOF256(rhoPrime);\n const s1 = [];\n for (let i = 0; i < L; i++)\n s1.push(RejBoundedPoly(xofPrime.get(i & 0xff, (i >> 8) & 0xff)));\n const s2 = [];\n for (let i = L; i < L + K; i++)\n s2.push(RejBoundedPoly(xofPrime.get(i & 0xff, (i >> 8) & 0xff)));\n const s1Hat = s1.map((i) => crystals.NTT.encode(i.slice()));\n const t0 = [];\n const t1 = [];\n const xof = XOF128(rho);\n const t = newPoly(N);\n for (let i = 0; i < K; i++) {\n // t \u2190 NTT\u22121(A*NTT(s1)) + s2\n cleanBytes(t); // don't-reallocate\n for (let j = 0; j < L; j++) {\n const aij = RejNTTPoly(xof.get(j, i)); // super slow!\n polyAdd(t, MultiplyNTTs(aij, s1Hat[j]));\n }\n crystals.NTT.decode(t);\n const { r0, r1 } = polyPowerRound(polyAdd(t, s2[i])); // (t1, t0) \u2190 Power2Round(t, d)\n t0.push(r0);\n t1.push(r1);\n }\n const publicKey = publicCoder.encode([rho, t1]); // pk \u2190 pkEncode(\u03C1, t1)\n const tr = shake256(publicKey, { dkLen: TR_BYTES }); // tr \u2190 H(BytesToBits(pk), 512)\n // sk \u2190 skEncode(\u03C1, K,tr, s1, s2, t0)\n const secretKey = secretCoder.encode([rho, K_, tr, s1, s2, t0]);\n xof.clean();\n xofPrime.clean();\n // STATS\n // Kyber512: { calls: 4, xofs: 12 }, Kyber768: { calls: 9, xofs: 27 },\n // Kyber1024: { calls: 16, xofs: 48 }\n // DSA44: { calls: 24, xofs: 24 }, DSA65: { calls: 41, xofs: 41 },\n // DSA87: { calls: 71, xofs: 71 }\n cleanBytes(rho, rhoPrime, K_, s1, s2, s1Hat, t, t0, t1, tr, seedDst);\n return {\n publicKey: publicKey,\n secretKey: secretKey,\n };\n },\n getPublicKey: (secretKey) => {\n // (\u03C1, K,tr, s1, s2, t0) \u2190 skDecode(sk)\n const [rho, _K, _tr, s1, s2, _t0] = secretCoder.decode(secretKey);\n const xof = XOF128(rho);\n const s1Hat = s1.map((p) => crystals.NTT.encode(p.slice()));\n const t1 = [];\n const tmp = newPoly(N);\n for (let i = 0; i < K; i++) {\n tmp.fill(0);\n for (let j = 0; j < L; j++) {\n const aij = RejNTTPoly(xof.get(j, i)); // A_ij in NTT\n polyAdd(tmp, MultiplyNTTs(aij, s1Hat[j])); // += A_ij * s1_j\n }\n crystals.NTT.decode(tmp); // NTT\u207B\u00B9\n polyAdd(tmp, s2[i]); // t_i = A\u00B7s1 + s2\n const { r1 } = polyPowerRound(tmp); // r1 = t1, r0 \u2248 t0\n t1.push(r1);\n }\n xof.clean();\n cleanBytes(tmp, s1Hat, _t0, s1, s2);\n return publicCoder.encode([rho, t1]);\n },\n // NOTE: random is optional.\n sign: (msg, secretKey, opts = {}) => {\n opts = validateSigOpts(opts, INTERNAL_SIG_OPT_KEYS);\n opts = validateInternalOpts(opts, INTERNAL_SIG_OPT_KEYS);\n const { extraEntropy: random, externalMu = false } = opts;\n // FIPS 204 external-mu mode expects the 64-byte message representative \u00B5 = H(tr || M).\n if (externalMu)\n abytes(msg, CRH_BYTES, 'mu');\n // Prepare entropy before touching decoded secrets: randomBytes() may throw, and an RNG\n // failure must not leave expanded secret-polynomial copies behind.\n const ownRnd = random === false || random === undefined;\n const rnd = random === false\n ? new Uint8Array(32)\n : random === undefined\n ? randomBytes(signRandBytes)\n : random;\n abytes(rnd, 32, 'extraEntropy');\n // This part can be pre-cached per secretKey, but there is only minor performance improvement,\n // since we re-use a lot of variables to computation.\n // (\u03C1, K,tr, s1, s2, t0) \u2190 skDecode(sk)\n const decoded = (() => {\n try {\n return secretCoder.decode(secretKey);\n }\n catch (error) {\n // A malformed key must not strand entropy owned by the library.\n if (ownRnd)\n cleanBytes(rnd);\n throw error;\n }\n })();\n const [rho, _K, tr, s1, s2, t0] = decoded;\n // Cache matrix to avoid re-compute later\n const A = []; // A \u2190 ExpandA(\u03C1)\n const xof = XOF128(rho);\n for (let i = 0; i < K; i++) {\n const pv = [];\n for (let j = 0; j < L; j++)\n pv.push(RejNTTPoly(xof.get(j, i)));\n A.push(pv);\n }\n xof.clean();\n for (let i = 0; i < L; i++)\n crystals.NTT.encode(s1[i]); // s\u02C61 \u2190 NTT(s1)\n for (let i = 0; i < K; i++) {\n crystals.NTT.encode(s2[i]); // s\u02C62 \u2190 NTT(s2)\n crystals.NTT.encode(t0[i]); // t\u02C60 \u2190 NTT(t0)\n }\n // This part is per msg\n const mu = externalMu\n ? msg\n : // 6: \u00B5 \u2190 H(tr||M, 512)\n // \u25B7 Compute message representative \u00B5\n shake256.create({ dkLen: CRH_BYTES }).update(tr).update(msg).digest();\n const rhoprime = shake256\n .create({ dkLen: CRH_BYTES })\n .update(_K)\n .update(rnd)\n .update(mu)\n .digest(); // \u03C1\u2032\u2190 H(K||rnd||\u00B5, 512)\n // Only wipe entropy we generated; caller-provided extraEntropy stays caller-owned.\n if (ownRnd)\n cleanBytes(rnd);\n abytes(rhoprime, CRH_BYTES);\n const x256 = XOF256(rhoprime, ZCoder.bytesLen);\n // Rejection sampling loop\n main_loop: for (let kappa = 0;;) {\n const y = [];\n // y \u2190 ExpandMask(\u03C1 , \u03BA)\n for (let i = 0; i < L; i++, kappa++)\n y.push(ZCoder.decode(x256.get(kappa & 0xff, kappa >> 8)()));\n const z = y.map((i) => crystals.NTT.encode(i.slice()));\n const w = [];\n for (let i = 0; i < K; i++) {\n // w \u2190 NTT\u22121(A \u25E6 NTT(y))\n const wi = newPoly(N);\n for (let j = 0; j < L; j++)\n polyAdd(wi, MultiplyNTTs(A[i][j], z[j]));\n crystals.NTT.decode(wi);\n w.push(wi);\n }\n const w1 = w.map((j) => j.map(HighBits)); // w1 \u2190 HighBits(w)\n // Commitment hash: c\u02DC \u2208{0, 1 2\u03BB } \u2190 H(\u00B5||w1Encode(w1), 2\u03BB)\n const cTilde = shake256\n .create({ dkLen: C_TILDE_BYTES })\n .update(mu)\n .update(W1Vec.encode(w1))\n .digest();\n // Verifer\u2019s challenge\n // c \u2190 SampleInBall(c\u02DC1); c\u02C6 \u2190 NTT(c)\n const cHat = crystals.NTT.encode(SampleInBall(cTilde));\n // \u27E8\u27E8cs1\u27E9\u27E9 \u2190 NTT\u22121(c\u02C6\u25E6 s\u02C61)\n const cs1 = s1.map((i) => MultiplyNTTs(i, cHat));\n for (let i = 0; i < L; i++) {\n polyAdd(crystals.NTT.decode(cs1[i]), y[i]); // z \u2190 y + \u27E8\u27E8cs1\u27E9\u27E9\n if (polyChknorm(cs1[i], GAMMA1 - BETA)) {\n // Rejected. Wipe this iteration's secret-derived buffers before retrying; the\n // accepted path wipes the same set, and only the persistent key material (s1, s2,\n // t0, A, rhoprime) is kept for the next iteration and cleaned at the very end.\n cleanBytes(cTilde, cs1, cHat, w1, w, z, y);\n continue main_loop; // ||z||\u221E \u2265 \u03B31 \u2212 \u03B2\n }\n }\n // cs1 is now z (\u25B7 Signer\u2019s response)\n let cnt = 0;\n const h = [];\n for (let i = 0; i < K; i++) {\n const cs2 = crystals.NTT.decode(MultiplyNTTs(s2[i], cHat)); // \u27E8\u27E8cs2\u27E9\u27E9 \u2190 NTT\u22121(c\u02C6\u25E6 s\u02C62)\n const r0 = polySub(w[i], cs2).map(LowBits); // r0 \u2190 LowBits(w \u2212 \u27E8\u27E8cs2\u27E9\u27E9)\n if (polyChknorm(r0, GAMMA2 - BETA)) {\n cleanBytes(cTilde, cs1, cHat, w1, w, z, y, h, cs2, r0);\n continue main_loop; // ||r0||\u221E \u2265 \u03B32 \u2212 \u03B2\n }\n const ct0 = crystals.NTT.decode(MultiplyNTTs(t0[i], cHat)); // \u27E8\u27E8ct0\u27E9\u27E9 \u2190 NTT\u22121(c\u02C6\u25E6 t\u02C60)\n if (polyChknorm(ct0, GAMMA2)) {\n cleanBytes(cTilde, cs1, cHat, w1, w, z, y, h, cs2, r0, ct0);\n continue main_loop;\n }\n polyAdd(r0, ct0);\n // \u25B7 Signer\u2019s hint\n const hint = polyMakeHint(r0, w1[i]); // h \u2190 MakeHint(\u2212\u27E8\u27E8ct0\u27E9\u27E9, w\u2212 \u27E8\u27E8cs2\u27E9\u27E9 + \u27E8\u27E8ct0\u27E9\u27E9)\n h.push(hint.v);\n cnt += hint.cnt;\n }\n if (cnt > OMEGA) {\n cleanBytes(cTilde, cs1, cHat, w1, w, z, y, h);\n continue; // the number of 1\u2019s in h is greater than \u03C9\n }\n x256.clean();\n const res = sigCoder.encode([cTilde, cs1, h]); // \u03C3 \u2190 sigEncode(c\u02DC, z mod\u00B1q, h)\n // rho, _K, tr is subarray of secretKey, cannot clean.\n cleanBytes(cTilde, cs1, h, cHat, w1, w, z, y, rhoprime, s1, s2, t0, ...A);\n // `externalMu` hands ownership of `mu` to the caller,\n // so only wipe the internally derived digest form here;\n // zeroizing caller memory would break the caller's own reuse / verify path.\n if (!externalMu)\n cleanBytes(mu);\n return res;\n }\n // @ts-ignore\n throw new Error('Unreachable code path reached, report this error');\n },\n verify: (sig, msg, publicKey, opts = {}) => {\n opts = validateInternalOpts(opts, INTERNAL_VER_OPT_KEYS);\n const { externalMu = false } = opts;\n // FIPS 204 external-mu mode expects the 64-byte message representative \u00B5 = H(tr || M).\n if (externalMu)\n abytes(msg, CRH_BYTES, 'mu');\n // ML-DSA.Verify(pk, M, \u03C3): Verifes a signature \u03C3 for a message M.\n const [rho, t1] = publicCoder.decode(publicKey); // (\u03C1, t1) \u2190 pkDecode(pk)\n const tr = shake256(publicKey, { dkLen: TR_BYTES }); // 6: tr \u2190 H(BytesToBits(pk), 512)\n if (sig.length !== sigCoder.bytesLen)\n return false; // return false instead of exception\n // (c\u02DC, z, h) \u2190 sigDecode(\u03C3)\n // \u25B7 Signer\u2019s commitment hash c \u02DC, response z and hint\n const [cTilde, z, h] = sigCoder.decode(sig);\n if (h === false)\n return false; // if h = \u22A5 then return false\n for (let i = 0; i < L; i++)\n if (polyChknorm(z[i], GAMMA1 - BETA))\n return false;\n const mu = externalMu\n ? msg\n : // 7: \u00B5 \u2190 H(tr||M, 512)\n shake256.create({ dkLen: CRH_BYTES }).update(tr).update(msg).digest();\n // Compute verifer\u2019s challenge from c\u02DC\n const c = crystals.NTT.encode(SampleInBall(cTilde)); // c \u2190 SampleInBall(c\u02DC1)\n const zNtt = z.map((i) => i.slice()); // zNtt = NTT(z)\n for (let i = 0; i < L; i++)\n crystals.NTT.encode(zNtt[i]);\n const wTick1 = [];\n const xof = XOF128(rho);\n for (let i = 0; i < K; i++) {\n const ct12d = MultiplyNTTs(crystals.NTT.encode(polyShiftl(t1[i])), c); //c * t1 * (2**d)\n const Az = newPoly(N); // // A * z\n for (let j = 0; j < L; j++) {\n const aij = RejNTTPoly(xof.get(j, i)); // A[i][j] inplace\n polyAdd(Az, MultiplyNTTs(aij, zNtt[j]));\n }\n // wApprox = A*z - c*t1 * (2**d)\n const wApprox = crystals.NTT.decode(polySub(Az, ct12d));\n // Reconstruction of signer\u2019s commitment\n wTick1.push(polyUseHint(wApprox, h[i])); // w \u2032 \u2190 UseHint(h, w'approx )\n }\n xof.clean();\n // c\u02DC\u2032\u2190 H (\u00B5||w1Encode(w\u20321), 2\u03BB), Hash it; this should match c\u02DC\n const c2 = shake256\n .create({ dkLen: C_TILDE_BYTES })\n .update(mu)\n .update(W1Vec.encode(wTick1))\n .digest();\n // Additional checks in FIPS-204:\n // [[ ||z||\u221E < \u03B31 \u2212 \u03B2 ]] and [[c \u02DC = c\u02DC\u2032]] and [[number of 1\u2019s in h is \u2264 \u03C9]]\n for (const t of h) {\n const sum = t.reduce((acc, i) => acc + i, 0);\n if (!(sum <= OMEGA))\n return false;\n }\n for (const t of z)\n if (polyChknorm(t, GAMMA1 - BETA))\n return false;\n return equalBytes(cTilde, c2);\n },\n });\n return Object.freeze({\n info: Object.freeze({ type: 'ml-dsa' }),\n internal,\n securityLevel: securityLevel,\n keygen: internal.keygen,\n lengths: internal.lengths,\n getPublicKey: internal.getPublicKey,\n sign: (msg, secretKey, opts = {}) => {\n opts = validateSigOpts(opts);\n const M = getMessage(msg, opts.context);\n // `context` is consumed by getMessage() above; forwarding it would make the internal\n // surface accept a key it never reads.\n const res = internal.sign(M, secretKey, {\n extraEntropy: opts.extraEntropy,\n externalMu: false,\n });\n cleanBytes(M);\n return res;\n },\n verify: (sig, msg, publicKey, opts = {}) => {\n opts = validateVerOpts(opts);\n abytes(sig, undefined, 'signature');\n return internal.verify(sig, getMessage(msg, opts.context), publicKey, { externalMu: false });\n },\n prehash: (hash) => {\n checkHash(hash, securityLevel);\n const rawHash = hash;\n return Object.freeze({\n info: Object.freeze({ type: 'hashml-dsa' }),\n securityLevel: securityLevel,\n lengths: internal.lengths,\n keygen: internal.keygen,\n getPublicKey: internal.getPublicKey,\n sign: (msg, secretKey, opts = {}) => {\n opts = validateSigOpts(opts);\n const M = getMessagePrehash(rawHash, msg, opts.context);\n // As above: getMessagePrehash() consumes `context`, so it must not travel further.\n const res = internal.sign(M, secretKey, {\n extraEntropy: opts.extraEntropy,\n externalMu: false,\n });\n cleanBytes(M);\n return res;\n },\n verify: (sig, msg, publicKey, opts = {}) => {\n opts = validateVerOpts(opts);\n abytes(sig, undefined, 'signature');\n return internal.verify(sig, getMessagePrehash(rawHash, msg, opts.context), publicKey, {\n externalMu: false,\n });\n },\n });\n },\n });\n}\n/**\n * ML-DSA-44 for 128-bit security level. Not recommended after 2030, as per ASD.\n * @example\n * Generate deterministic ML-DSA-44 keys, sign one message, and verify the signature.\n * ```ts\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { ml_dsa44 } from '@noble/post-quantum/ml-dsa.js';\n * const seed = new Uint8Array(ml_dsa44.lengths.seed!);\n * const { secretKey, publicKey } = ml_dsa44.keygen(seed);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ml_dsa44.sign(msg, secretKey);\n * const isValid = ml_dsa44.verify(sig, msg, publicKey);\n * const recovered = ml_dsa44.getPublicKey(secretKey);\n * const context = new Uint8Array([1, 2, 3]);\n * const prehash = ml_dsa44.prehash(sha256);\n * const preSig = prehash.sign(msg, secretKey, { context });\n * const preValid = prehash.verify(preSig, msg, publicKey, { context });\n * const internalSig = ml_dsa44.internal.sign(msg, secretKey);\n * ```\n */\nexport const ml_dsa44 = /* @__PURE__ */ (() => getDilithium({\n ...PARAMS[2],\n CRH_BYTES: 64,\n TR_BYTES: 64,\n C_TILDE_BYTES: 32,\n XOF128,\n XOF256,\n securityLevel: 128,\n}))();\n/** ML-DSA-65 for 192-bit security level. Not recommended after 2030, as per ASD. */\nexport const ml_dsa65 = /* @__PURE__ */ (() => getDilithium({\n ...PARAMS[3],\n CRH_BYTES: 64,\n TR_BYTES: 64,\n C_TILDE_BYTES: 48,\n XOF128,\n XOF256,\n securityLevel: 192,\n}))();\n/** ML-DSA-87 for 256-bit security level. OK after 2030, as per ASD. */\nexport const ml_dsa87 = /* @__PURE__ */ (() => getDilithium({\n ...PARAMS[5],\n CRH_BYTES: 64,\n TR_BYTES: 64,\n C_TILDE_BYTES: 64,\n XOF128,\n XOF256,\n securityLevel: 256,\n}))();\n", "/**\n * The `records-crypto` bundle the SDK and the checker publish: the blinded\n * fingerprint and records encryption (records-crypto) with level 2's\n * asymmetric layer. Every import below is relative, so the declarations\n * emitted from here never name @pacspace/shared or the pinned libraries.\n */\nexport * from './index';\nexport * from './asymmetric';\n", "import type { PayloadByteSource } from '../proof/payload-ref-v1';\n\nexport const BLINDING_VALUE_BYTES = 32;\n\nconst BLINDING_VALUE_MESSAGE = 'A blinding value is exactly 32 bytes.';\n\n/** A refusal of a blinding value or file. The message is fixed and names no value. */\nexport class BlindingError extends Error {\n constructor(message: string = BLINDING_VALUE_MESSAGE) {\n super(message);\n this.name = 'BlindingError';\n }\n}\n\n/**\n * HMAC zero-pads a short key and hashes a long one, so two different values\n * could give the same MAC; every entry point refuses anything but 32 bytes\n * before HMAC runs (slot-encoding-v1 section 6.2).\n */\nexport function assertBlindingValue(value: unknown): asserts value is Uint8Array {\n if (!(value instanceof Uint8Array) || value.length !== BLINDING_VALUE_BYTES) {\n throw new BlindingError();\n }\n}\n\nfunction isAsyncIterable(v: unknown): v is AsyncIterable<Uint8Array> {\n return !!v && typeof (v as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === 'function';\n}\nfunction isIterable(v: unknown): v is Iterable<Uint8Array> {\n return !!v && typeof (v as { [Symbol.iterator]?: unknown })[Symbol.iterator] === 'function' && !(v instanceof Uint8Array);\n}\n\n/**\n * Every chunk as a Uint8Array view of its bytes. A chunk that is not a byte\n * view (a string, a number) is refused, so the two implementations never\n * count or hash it differently; a Uint8Array from another realm is a view.\n */\nfunction bytesOf(chunk: unknown): Uint8Array {\n if (!ArrayBuffer.isView(chunk)) throw new TypeError();\n return new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);\n}\n\nexport async function* chunksOf(source: PayloadByteSource): AsyncGenerator<Uint8Array> {\n if (ArrayBuffer.isView(source)) {\n yield bytesOf(source);\n } else if (isAsyncIterable(source)) {\n for await (const c of source) yield bytesOf(c);\n } else if (isIterable(source)) {\n for (const c of source) yield bytesOf(c);\n } else {\n throw new TypeError();\n }\n}\n\nexport function isNodeRuntime(): boolean {\n return typeof process !== 'undefined' && !!(process as { versions?: { node?: string } }).versions?.node;\n}\n\n/** `node:crypto`, loaded so browser bundlers leave it alone (see payload-ref-v1's digestPayload). */\nexport async function loadNodeCrypto(): Promise<typeof import('node:crypto')> {\n const specifier = 'node:crypto';\n return import(/* @vite-ignore */ /* webpackIgnore: true */ specifier);\n}\n\nexport const toHex = (bytes: Uint8Array): string =>\n Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\n", "import type { PayloadByteSource, PayloadRefV1 } from '../proof/payload-ref-v1';\nimport { assertBlindingValue, chunksOf, loadNodeCrypto } from './blinding-value';\n\n/** HMAC-SHA256 through `node:crypto`, streaming. */\nexport const hmacNode = {\n async hmacSha256(key: Uint8Array, source: PayloadByteSource): Promise<{ digest: string; byteLength: string }> {\n const { createHmac } = await loadNodeCrypto();\n const mac = createHmac('sha256', key);\n let byteLength = 0n;\n for await (const chunk of chunksOf(source)) {\n mac.update(chunk);\n byteLength += BigInt(chunk.length);\n }\n return { digest: mac.digest('hex'), byteLength: byteLength.toString() };\n },\n\n async blindedDigest(source: PayloadByteSource, value: Uint8Array): Promise<PayloadRefV1> {\n assertBlindingValue(value);\n const { digest, byteLength } = await hmacNode.hmacSha256(value, source);\n return { alg: 'hmac-sha-256', digest, byteLength };\n },\n};\n", "import type { PayloadByteSource, PayloadRefV1 } from '../proof/payload-ref-v1';\nimport { assertBlindingValue, chunksOf, toHex } from './blinding-value';\n\n/** HMAC-SHA256 through WebCrypto. `sign` is one-shot, so the chunks are joined first. */\nexport const hmacWeb = {\n async hmacSha256(key: Uint8Array, source: PayloadByteSource): Promise<{ digest: string; byteLength: string }> {\n const parts: Uint8Array[] = [];\n let length = 0;\n for await (const chunk of chunksOf(source)) {\n parts.push(chunk);\n length += chunk.length;\n }\n const joined = new Uint8Array(length);\n let offset = 0;\n for (const part of parts) {\n joined.set(part, offset);\n offset += part.length;\n }\n const subtle = globalThis.crypto.subtle;\n const cryptoKey = await subtle.importKey('raw', Uint8Array.from(key), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);\n const mac = await subtle.sign('HMAC', cryptoKey, joined);\n return { digest: toHex(new Uint8Array(mac)), byteLength: String(length) };\n },\n\n async blindedDigest(source: PayloadByteSource, value: Uint8Array): Promise<PayloadRefV1> {\n assertBlindingValue(value);\n const { digest, byteLength } = await hmacWeb.hmacSha256(value, source);\n return { alg: 'hmac-sha-256', digest, byteLength };\n },\n};\n", "import { ethers } from 'ethers';\nimport { canonicalizeJcs } from './jcs';\n\n/**\n * layout-document/v1 (ADR 0012 section 4; slot-encoding-v1 sections 4 and 5).\n *\n * A layout document is the public description of a record type's state\n * region: typed fields packed most significant first, a lifecycle table, and\n * the name of the sealed record schema. Its digest, keccak256 over the JCS\n * bytes, is what the operator registers on the contract. This module packs\n * and decodes state words under a layout and validates well-formedness only;\n * it never scores plausibility (PacSpace records and never decides).\n */\n\nexport const LAYOUT_DOCUMENT_SCHEMA_V1 = 'layout-document/v1';\n\nexport type LayoutFieldType = 'enum' | 'flags' | 'counter' | 'quantity' | 'reserved';\n\nexport interface LayoutFieldBase {\n name: string;\n type: LayoutFieldType;\n bits: number;\n}\nexport interface LayoutEnumField extends LayoutFieldBase {\n type: 'enum';\n values: Record<string, number>;\n}\nexport interface LayoutFlagsField extends LayoutFieldBase {\n type: 'flags';\n bitNames: Record<string, number>;\n}\nexport interface LayoutCounterField extends LayoutFieldBase {\n type: 'counter';\n fixed?: number;\n}\nexport interface LayoutQuantityField extends LayoutFieldBase {\n type: 'quantity';\n unitCode: string;\n scale: number;\n semantics: 'perRecord' | 'cumulative';\n}\nexport interface LayoutReservedField extends LayoutFieldBase {\n type: 'reserved';\n}\nexport type LayoutField =\n | LayoutEnumField\n | LayoutFlagsField\n | LayoutCounterField\n | LayoutQuantityField\n | LayoutReservedField;\n\nexport interface LayoutLifecycle {\n field: string;\n genesis: string[];\n terminal: string[];\n transitions: Record<string, string[]>;\n}\n\nexport interface LayoutDocumentV1 {\n schema: typeof LAYOUT_DOCUMENT_SCHEMA_V1;\n layoutId: number;\n layoutVersion: number;\n name: string;\n recordTypeId: string;\n encodingVersion: number;\n stateBits: number;\n sealBits: number;\n public: boolean;\n recordAttempts: boolean;\n fields: LayoutField[];\n lifecycle: LayoutLifecycle;\n sealedRecordSchema: string;\n notes?: string[];\n}\n\n/** Registered error codes for intake rejections (well-formedness only). */\nexport type RecordIntakeErrorCode =\n | 'LAYOUT_NOT_FOUND'\n | 'RECORD_LAYOUT_MISMATCH'\n | 'RECORD_STATE_UNKNOWN'\n | 'RECORD_RESERVED_BITS_SET'\n | 'RECORD_QUANTITY_OVERFLOW'\n | 'RECORD_FLAG_UNKNOWN'\n | 'RECORD_TRANSITION_FORBIDDEN'\n | 'RECORD_GENESIS_MISMATCH'\n | 'RECORD_PAYLOAD_ALG_UNSUPPORTED'\n | 'RECORD_CONTENT_INVALID'\n | 'RECORD_LAYOUT_INVALID'\n // Records buyer posture plan, Slice B: the sealed-content minimums of the\n // general layout (record-content/machine-action-record/v1).\n | 'RECORD_PAYLOADS_REQUIRED'\n | 'RECORD_TITLE_TOO_LONG'\n | 'RECORD_BLINDING_INCLUDED';\n\n/** The part of Rule B (slot-encoding-v1 section 6.1) that refused blinding material. */\nexport type BlindingMaterialRule = 'B1' | 'B2' | 'B3';\n\nexport class RecordIntakeError extends Error {\n readonly code: RecordIntakeErrorCode;\n /** Set only by Rule B. */\n readonly rule?: BlindingMaterialRule;\n constructor(code: RecordIntakeErrorCode, message?: string, rule?: BlindingMaterialRule) {\n super(message || code);\n this.name = 'RecordIntakeError';\n this.code = code;\n if (rule) this.rule = rule;\n }\n}\n\n/** Values a caller supplies for the state fields (enum by name, flags by name list, counters/quantities as integers). */\nexport type StateFieldValues = Record<string, string | number | bigint | string[] | undefined>;\n\n/** Decoded state: enum names, flag name lists, counters and quantities as decimal strings. */\nexport type DecodedState = Record<string, string | string[]>;\n\nexport function computeLayoutDigestV1(doc: LayoutDocumentV1): string {\n return ethers.keccak256(ethers.toUtf8Bytes(canonicalizeJcs(doc)));\n}\n\nexport function validateLayoutDocumentV1(doc: LayoutDocumentV1): void {\n if (!doc || doc.schema !== LAYOUT_DOCUMENT_SCHEMA_V1) {\n throw new RecordIntakeError('RECORD_LAYOUT_INVALID', 'layout document schema must be layout-document/v1');\n }\n if (!Number.isInteger(doc.layoutId) || doc.layoutId <= 0 || doc.layoutId > 0xffff) {\n throw new RecordIntakeError('RECORD_LAYOUT_INVALID', 'layoutId must be a uint16 greater than zero');\n }\n if (!Number.isInteger(doc.layoutVersion) || doc.layoutVersion <= 0 || doc.layoutVersion > 0xff) {\n throw new RecordIntakeError('RECORD_LAYOUT_INVALID', 'layoutVersion must be a uint8 greater than zero');\n }\n if (doc.stateBits + doc.sealBits !== 256) {\n throw new RecordIntakeError('RECORD_LAYOUT_INVALID', 'stateBits and sealBits must total 256');\n }\n const total = doc.fields.reduce((n, f) => n + f.bits, 0);\n if (total !== doc.stateBits) {\n throw new RecordIntakeError('RECORD_LAYOUT_INVALID', `fields total ${total} bits, layout declares ${doc.stateBits}`);\n }\n const names = new Set<string>();\n for (const f of doc.fields) {\n if (names.has(f.name)) throw new RecordIntakeError('RECORD_LAYOUT_INVALID', `duplicate field ${f.name}`);\n names.add(f.name);\n if (!Number.isInteger(f.bits) || f.bits <= 0) {\n throw new RecordIntakeError('RECORD_LAYOUT_INVALID', `field ${f.name} has an invalid width`);\n }\n if (f.type === 'enum') {\n for (const [name, value] of Object.entries(f.values)) {\n if (!Number.isInteger(value) || value < 0 || value >= 2 ** f.bits) {\n throw new RecordIntakeError('RECORD_LAYOUT_INVALID', `enum ${f.name}.${name} does not fit ${f.bits} bits`);\n }\n }\n }\n if (f.type === 'flags') {\n for (const [name, bit] of Object.entries(f.bitNames)) {\n if (!Number.isInteger(bit) || bit < 0 || bit >= f.bits) {\n throw new RecordIntakeError('RECORD_LAYOUT_INVALID', `flag ${f.name}.${name} is outside ${f.bits} bits`);\n }\n }\n }\n }\n const lifecycleField = doc.fields.find((f) => f.name === doc.lifecycle.field);\n if (!lifecycleField || lifecycleField.type !== 'enum') {\n throw new RecordIntakeError('RECORD_LAYOUT_INVALID', 'lifecycle.field must name an enum field');\n }\n const states = new Set(Object.keys(lifecycleField.values));\n for (const s of [...doc.lifecycle.genesis, ...doc.lifecycle.terminal]) {\n if (!states.has(s)) throw new RecordIntakeError('RECORD_LAYOUT_INVALID', `lifecycle state ${s} is not in the enum`);\n }\n for (const [from, tos] of Object.entries(doc.lifecycle.transitions)) {\n if (!states.has(from)) throw new RecordIntakeError('RECORD_LAYOUT_INVALID', `transition source ${from} is not a state`);\n for (const to of tos) {\n if (!states.has(to)) throw new RecordIntakeError('RECORD_LAYOUT_INVALID', `transition target ${to} is not a state`);\n }\n }\n for (const t of doc.lifecycle.terminal) {\n if ((doc.lifecycle.transitions[t] ?? []).length > 0) {\n throw new RecordIntakeError('RECORD_LAYOUT_INVALID', `terminal state ${t} has outgoing transitions`);\n }\n }\n}\n\nexport function getLayoutField(doc: LayoutDocumentV1, name: string): LayoutField | undefined {\n return doc.fields.find((f) => f.name === name);\n}\n\nexport function lifecycleValues(doc: LayoutDocumentV1): Record<string, number> {\n const f = getLayoutField(doc, doc.lifecycle.field);\n if (!f || f.type !== 'enum') return {};\n return f.values;\n}\n\nexport function isTransitionAllowedV1(doc: LayoutDocumentV1, from: string, to: string): boolean {\n return (doc.lifecycle.transitions[from] ?? []).includes(to);\n}\n\nfunction toBigInt(value: string | number | bigint | undefined, field: string): bigint {\n if (value === undefined) return 0n;\n if (typeof value === 'bigint') return value;\n if (typeof value === 'number') {\n if (!Number.isInteger(value)) throw new RecordIntakeError('RECORD_QUANTITY_OVERFLOW', `${field} must be an integer`);\n return BigInt(value);\n }\n if (!/^-?\\d+$/.test(value)) throw new RecordIntakeError('RECORD_QUANTITY_OVERFLOW', `${field} must be a decimal integer`);\n return BigInt(value);\n}\n\n/**\n * Pack named field values into the state region. Rejects malformed input\n * with a registered code; never wraps or saturates.\n */\nexport function packStateV1(doc: LayoutDocumentV1, values: StateFieldValues): bigint {\n let state = 0n;\n for (const f of doc.fields) {\n let v: bigint;\n const width = BigInt(f.bits);\n switch (f.type) {\n case 'reserved': {\n v = toBigInt(values[f.name] as string | number | bigint | undefined, f.name);\n if (v !== 0n) throw new RecordIntakeError('RECORD_RESERVED_BITS_SET', `${f.name} must be zero`);\n break;\n }\n case 'enum': {\n const name = values[f.name];\n if (typeof name !== 'string' || !(name in f.values)) {\n throw new RecordIntakeError('RECORD_STATE_UNKNOWN', `${f.name}=${String(name)} is not in the layout`);\n }\n v = BigInt(f.values[name]);\n break;\n }\n case 'flags': {\n const names = (values[f.name] ?? []) as string[];\n if (!Array.isArray(names)) throw new RecordIntakeError('RECORD_FLAG_UNKNOWN', `${f.name} must be a list of flag names`);\n v = 0n;\n for (const n of names) {\n if (!(n in f.bitNames)) throw new RecordIntakeError('RECORD_FLAG_UNKNOWN', `${f.name}:${n} is not in the layout`);\n v |= 1n << BigInt(f.bitNames[n]);\n }\n break;\n }\n case 'counter':\n case 'quantity': {\n const fixed = f.type === 'counter' ? f.fixed : undefined;\n v = toBigInt((values[f.name] ?? fixed) as string | number | bigint | undefined, f.name);\n if (fixed !== undefined && v !== BigInt(fixed)) {\n throw new RecordIntakeError('RECORD_LAYOUT_MISMATCH', `${f.name} must be ${fixed}`);\n }\n if (v < 0n || v >= 1n << width) {\n throw new RecordIntakeError('RECORD_QUANTITY_OVERFLOW', `${f.name}=${v} exceeds ${f.bits} bits`);\n }\n break;\n }\n default:\n throw new RecordIntakeError('RECORD_LAYOUT_INVALID', `unknown field type`);\n }\n state = (state << width) | v;\n }\n return state;\n}\n\n/** Decode a state region under a layout. Unknown enum values decode as `unknown(n)`. */\nexport function decodeStateV1(doc: LayoutDocumentV1, state96: bigint): DecodedState {\n const out: DecodedState = {};\n let remaining = BigInt(state96);\n for (const f of [...doc.fields].reverse()) {\n const mask = (1n << BigInt(f.bits)) - 1n;\n const raw = remaining & mask;\n remaining >>= BigInt(f.bits);\n if (f.type === 'enum') {\n const found = Object.entries(f.values).find(([, n]) => BigInt(n) === raw);\n out[f.name] = found ? found[0] : `unknown(${raw})`;\n } else if (f.type === 'flags') {\n out[f.name] = Object.entries(f.bitNames)\n .filter(([, bit]) => ((raw >> BigInt(bit)) & 1n) === 1n)\n .map(([n]) => n);\n } else {\n out[f.name] = raw.toString();\n }\n }\n const ordered: DecodedState = {};\n for (const f of doc.fields) ordered[f.name] = out[f.name];\n return ordered;\n}\n\n/** Read the layout id and version from the top 24 bits of a state region. */\nexport function readLayoutIdFromState(state96: bigint): { layoutId: number; layoutVersion: number } {\n const s = BigInt(state96);\n return { layoutId: Number(s >> 80n), layoutVersion: Number((s >> 72n) & 0xffn) };\n}\n\n/** Format a quantity field for display, e.g. `250 api_call` or `12.50 USD`. */\nexport function formatQuantityV1(field: LayoutQuantityField, raw: string | bigint): string {\n const v = BigInt(raw);\n if (field.scale === 0) return `${v.toString()} ${field.unitCode}`;\n const divisor = 10n ** BigInt(field.scale);\n const whole = v / divisor;\n const frac = (v % divisor).toString().padStart(field.scale, '0');\n return `${whole.toString()}.${frac} ${field.unitCode}`;\n}\n", "/**\n * RFC 8785 JSON Canonicalization Scheme (JCS), restricted to the JSON value\n * space: null, boolean, finite number, string, array, plain object.\n *\n * Object keys are sorted by UTF-16 code units; strings and numbers are\n * serialized as ECMAScript JSON.stringify does, which is what RFC 8785\n * specifies. No whitespace. Used for layout documents (`layoutDigest`) and\n * record content (`recordHash`) so two honest serializations of the same\n * record hash the same (slot-encoding-v1 sections 4 and 6).\n */\nexport class JcsError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'JcsError';\n }\n}\n\nfunction compareUtf16(a: string, b: string): number {\n const n = Math.min(a.length, b.length);\n for (let i = 0; i < n; i += 1) {\n const d = a.charCodeAt(i) - b.charCodeAt(i);\n if (d !== 0) return d;\n }\n return a.length - b.length;\n}\n\nexport function canonicalizeJcs(value: unknown): string {\n if (value === null) return 'null';\n const type = typeof value;\n if (type === 'string' || type === 'boolean') return JSON.stringify(value);\n if (type === 'number') {\n if (!Number.isFinite(value as number)) {\n throw new JcsError('JCS cannot encode a non-finite number.');\n }\n return JSON.stringify(value);\n }\n if (type === 'bigint') {\n throw new JcsError('JCS cannot encode a bigint; use a decimal string.');\n }\n if (type === 'undefined' || type === 'function' || type === 'symbol') {\n throw new JcsError(`JCS cannot encode a value of type ${type}.`);\n }\n if (Array.isArray(value)) {\n return `[${value.map((item) => canonicalizeJcs(item)).join(',')}]`;\n }\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record).sort(compareUtf16);\n const parts: string[] = [];\n for (const key of keys) {\n const item = record[key];\n if (item === undefined) continue; // JSON.stringify drops undefined members\n parts.push(`${JSON.stringify(key)}:${canonicalizeJcs(item)}`);\n }\n return `{${parts.join(',')}}`;\n}\n", "import { RecordIntakeError } from './layout-document-v1';\n\n/**\n * payload-ref/v1 (slot-encoding-v1 section 6.1).\n *\n * Bulk bytes never pass through PacSpace. The tenant digests them where they\n * live and places `{ alg, digest, byteLength }` in the record content. The\n * storage locator is never part of the record. `digestPayload` is the\n * streaming helper every tenant can use so the same bytes give the same\n * reference regardless of chunking; it runs in Node (crypto.subtle or\n * node:crypto) and in browsers (crypto.subtle for one-shot digests).\n */\n\n/**\n * The list only grows: an alg is never removed or redefined (section 6.1).\n * `hmac-sha-256` is a blinded fingerprint, HMAC-SHA256 of the bytes keyed by\n * a 32-byte blinding value the tenant keeps.\n */\nexport const PAYLOAD_REF_ALGS = ['sha-256', 'hmac-sha-256'] as const;\nexport type PayloadRefAlg = (typeof PAYLOAD_REF_ALGS)[number];\n\nexport interface PayloadRefV1 {\n alg: PayloadRefAlg;\n /** Lowercase hex, no 0x prefix. */\n digest: string;\n /** Decimal string. */\n byteLength: string;\n}\n\nexport const BLINDING_FILE_SCHEMA_V1 = 'pacspace-blinding/v1';\n\n/**\n * RECORD_BLINDING_INCLUDED's sentences: B1 and B2 found blinding material; B3\n * found an extra field on a blinded fingerprint, which may be an ordinary note.\n */\nexport const RECORD_BLINDING_INCLUDED_SENTENCES = {\n material:\n \"This write includes a blinding file or its value. Send only the fingerprint's alg, digest and byteLength; the blinding file stays with you.\",\n extraField: 'A blinded fingerprint carries only alg, digest and byteLength. Move any other field out of it.',\n} as const;\n\nconst PAYLOAD_REF_FIELDS = new Set(['alg', 'digest', 'byteLength']);\n\nexport function validatePayloadRefV1(ref: unknown): PayloadRefV1 {\n if (!ref || typeof ref !== 'object') {\n throw new RecordIntakeError('RECORD_CONTENT_INVALID', 'payload reference must be an object');\n }\n const r = ref as Record<string, unknown>;\n if (!PAYLOAD_REF_ALGS.includes(r.alg as PayloadRefAlg)) {\n throw new RecordIntakeError(\n 'RECORD_PAYLOAD_ALG_UNSUPPORTED',\n `payload alg is not supported; use one of ${PAYLOAD_REF_ALGS.join(', ')}`,\n );\n }\n if (typeof r.digest !== 'string' || !/^[0-9a-f]{64}$/.test(r.digest)) {\n throw new RecordIntakeError('RECORD_CONTENT_INVALID', 'payload digest must be 64 lowercase hex characters');\n }\n if (typeof r.byteLength !== 'string' || !/^\\d+$/.test(r.byteLength)) {\n throw new RecordIntakeError('RECORD_CONTENT_INVALID', 'payload byteLength must be a decimal string');\n }\n if (r.alg === 'hmac-sha-256' && !/^(0|[1-9][0-9]*)$/.test(r.byteLength)) {\n throw new RecordIntakeError('RECORD_CONTENT_INVALID', 'payload byteLength must be a decimal string with no leading zero');\n }\n return { alg: r.alg as PayloadRefAlg, digest: r.digest, byteLength: r.byteLength };\n}\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n !!value && typeof value === 'object' && !Array.isArray(value);\n\n/** Rule B at one object, in order B1, B2, B3, B4 (slot-encoding-v1 section 6.1). */\nfunction applyRuleB(obj: Record<string, unknown>): void {\n if (obj.schema === BLINDING_FILE_SCHEMA_V1) {\n throw new RecordIntakeError('RECORD_BLINDING_INCLUDED', RECORD_BLINDING_INCLUDED_SENTENCES.material, 'B1');\n }\n if (\n isPlainObject(obj.ref) &&\n obj.ref.alg === 'hmac-sha-256' &&\n Object.prototype.hasOwnProperty.call(obj, 'blinding') &&\n obj.blinding !== null\n ) {\n throw new RecordIntakeError('RECORD_BLINDING_INCLUDED', RECORD_BLINDING_INCLUDED_SENTENCES.material, 'B2');\n }\n if (obj.alg === 'hmac-sha-256') {\n if (Object.keys(obj).some((key) => !PAYLOAD_REF_FIELDS.has(key))) {\n throw new RecordIntakeError('RECORD_BLINDING_INCLUDED', RECORD_BLINDING_INCLUDED_SENTENCES.extraField, 'B3');\n }\n validatePayloadRefV1(obj);\n }\n}\n\nconst isReferenceShaped = (obj: Record<string, unknown>): boolean =>\n 'alg' in obj && 'digest' in obj && 'byteLength' in obj;\n\n/**\n * Walk a record content object: Rule B at every object and every depth, then\n * today's rule for each payload reference. A validated reference's own three\n * fields are not descended into; its other fields are, under Rule B only.\n * Inside those other fields a reference-shaped object is not validated, so\n * all of its fields are walked, as assertNoBlindingMaterial walks them.\n */\nexport function validatePayloadRefsInContent(content: unknown): void {\n const visit = (value: unknown, insideReferenceExtras: boolean): void => {\n if (!value || typeof value !== 'object') return;\n if (Array.isArray(value)) {\n for (const item of value) visit(item, insideReferenceExtras);\n return;\n }\n const obj = value as Record<string, unknown>;\n applyRuleB(obj);\n if (isReferenceShaped(obj)) {\n if (!insideReferenceExtras) validatePayloadRefV1(obj);\n for (const [key, field] of Object.entries(obj)) {\n if (insideReferenceExtras || !PAYLOAD_REF_FIELDS.has(key)) visit(field, true);\n }\n return;\n }\n for (const field of Object.values(obj)) visit(field, insideReferenceExtras);\n };\n visit(content, false);\n}\n\n/** Rule B alone, at every object and every depth; the SDKs call it before any request. */\nexport function assertNoBlindingMaterial(value: unknown): void {\n if (!value || typeof value !== 'object') return;\n if (Array.isArray(value)) {\n for (const item of value) assertNoBlindingMaterial(item);\n return;\n }\n const obj = value as Record<string, unknown>;\n applyRuleB(obj);\n for (const field of Object.values(obj)) assertNoBlindingMaterial(field);\n}\n\nexport type PayloadByteSource = Uint8Array | Iterable<Uint8Array> | AsyncIterable<Uint8Array>;\n\nfunction isAsyncIterable(v: unknown): v is AsyncIterable<Uint8Array> {\n return !!v && typeof (v as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === 'function';\n}\nfunction isIterable(v: unknown): v is Iterable<Uint8Array> {\n return !!v && typeof (v as { [Symbol.iterator]?: unknown })[Symbol.iterator] === 'function' && !(v instanceof Uint8Array);\n}\n\n/**\n * Digest a payload with constant memory over any chunking. In Node the\n * incremental `node:crypto` hash is used; in a browser the chunks are\n * concatenated for `crypto.subtle.digest` (one-shot API).\n */\nexport async function digestPayload(source: PayloadByteSource, alg: 'sha-256' = 'sha-256'): Promise<PayloadRefV1> {\n if ((alg as string) === 'hmac-sha-256') {\n throw new RecordIntakeError(\n 'RECORD_PAYLOAD_ALG_UNSUPPORTED',\n 'digestPayload makes sha-256 fingerprints only; a blinded fingerprint is made with blindedDigest and its blinding value',\n );\n }\n if (alg !== 'sha-256') {\n throw new RecordIntakeError('RECORD_PAYLOAD_ALG_UNSUPPORTED', 'digestPayload supports sha-256 only');\n }\n let byteLength = 0n;\n const chunks = async function* (): AsyncGenerator<Uint8Array> {\n if (source instanceof Uint8Array) {\n yield source;\n } else if (isAsyncIterable(source)) {\n for await (const c of source) yield c;\n } else if (isIterable(source)) {\n for (const c of source) yield c;\n } else {\n throw new RecordIntakeError('RECORD_CONTENT_INVALID', 'digestPayload needs bytes or an iterable of bytes');\n }\n };\n\n let nodeCrypto: typeof import('node:crypto') | null = null;\n const isNode = typeof process !== 'undefined' && !!(process as { versions?: { node?: string } }).versions?.node;\n if (isNode) {\n try {\n // Prefer the incremental Node hash when available (constant memory).\n // The specifier is a variable so browser bundlers leave it alone.\n const specifier = 'node:crypto';\n nodeCrypto = await import(/* @vite-ignore */ /* webpackIgnore: true */ specifier);\n } catch {\n nodeCrypto = null;\n }\n }\n\n if (nodeCrypto && typeof nodeCrypto.createHash === 'function') {\n const hash = nodeCrypto.createHash('sha256');\n for await (const c of chunks()) {\n hash.update(c);\n byteLength += BigInt(c.length);\n }\n return { alg, digest: hash.digest('hex'), byteLength: byteLength.toString() };\n }\n\n const parts: Uint8Array[] = [];\n for await (const c of chunks()) {\n parts.push(c);\n byteLength += BigInt(c.length);\n }\n const joined = new Uint8Array(Number(byteLength));\n let offset = 0;\n for (const p of parts) {\n joined.set(p, offset);\n offset += p.length;\n }\n const digest = await globalThis.crypto.subtle.digest('SHA-256', joined);\n const hex = Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('');\n return { alg, digest: hex, byteLength: byteLength.toString() };\n}\n", "import { BLINDING_FILE_SCHEMA_V1 } from '../proof/payload-ref-v1';\nimport { BLINDING_VALUE_BYTES, BlindingError, assertBlindingValue, toHex } from './blinding-value';\n\n/** A reader refuses a file longer than this; the largest valid file is 259 bytes. */\nexport const BLINDING_FILE_MAX_BYTES = 1024;\n\nconst BLINDING_FILE_MESSAGE = 'This is not a valid blinding file.';\nconst HEX_64 = /^[0-9a-f]{64}$/;\nconst DECIMAL = /^(0|[1-9][0-9]*)$/;\nconst FIELDS = ['schema', 'alg', 'value', 'digest', 'byteLength'];\n\nexport interface BlindingFileV1 {\n /** The 32-byte blinding value. It never leaves the holder. */\n value: Uint8Array;\n /** The blinded digest the file was made for (lowercase hex). */\n digest: string;\n /** The file's length, as a decimal string. */\n byteLength: string;\n}\n\nexport type BlindingFileRefusal =\n | 'over-cap'\n | 'not-utf8'\n | 'not-json'\n | 'not-object'\n | 'fields'\n | 'schema'\n | 'alg'\n | 'value'\n | 'digest'\n | 'byteLength'\n | 'not-canonical';\n\nexport type ParsedBlindingFile = { ok: true; blinding: BlindingFileV1 } | { ok: false; reason: BlindingFileRefusal };\n\nconst isDecimalWithinSafeRange = (text: string) => DECIMAL.test(text) && BigInt(text) <= BigInt(Number.MAX_SAFE_INTEGER);\n\nfunction canonicalText(fields: { value: string; digest: string; byteLength: string }): string {\n return (\n JSON.stringify(\n { schema: BLINDING_FILE_SCHEMA_V1, alg: 'hmac-sha-256', value: fields.value, digest: fields.digest, byteLength: fields.byteLength },\n null,\n 2,\n ) + '\\n'\n );\n}\n\n/** The canonical bytes of a blinding file (slot-encoding-v1 section 6.2). */\nexport function serializeBlindingFile(blinding: BlindingFileV1): string {\n assertBlindingValue(blinding.value);\n if (typeof blinding.digest !== 'string' || !HEX_64.test(blinding.digest)) throw new BlindingError(BLINDING_FILE_MESSAGE);\n if (typeof blinding.byteLength !== 'string' || !isDecimalWithinSafeRange(blinding.byteLength)) {\n throw new BlindingError(BLINDING_FILE_MESSAGE);\n }\n return canonicalText({ value: toHex(blinding.value), digest: blinding.digest, byteLength: blinding.byteLength });\n}\n\n/**\n * The exact reader: strict UTF-8, the five string fields, then the canonical\n * form rewritten from the parsed fields must equal the input byte for byte,\n * which refuses duplicate keys, other whitespace, key order and line ends.\n */\nexport function parseBlindingFile(bytes: Uint8Array): ParsedBlindingFile {\n if (bytes.length > BLINDING_FILE_MAX_BYTES) return { ok: false, reason: 'over-cap' };\n let text: string;\n try {\n text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);\n } catch {\n return { ok: false, reason: 'not-utf8' };\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return { ok: false, reason: 'not-json' };\n }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return { ok: false, reason: 'not-object' };\n const obj = parsed as Record<string, unknown>;\n const keys = Object.keys(obj);\n if (keys.length !== FIELDS.length || !FIELDS.every((field) => keys.includes(field))) return { ok: false, reason: 'fields' };\n if (obj.schema !== BLINDING_FILE_SCHEMA_V1) return { ok: false, reason: 'schema' };\n if (obj.alg !== 'hmac-sha-256') return { ok: false, reason: 'alg' };\n if (typeof obj.value !== 'string' || !HEX_64.test(obj.value)) return { ok: false, reason: 'value' };\n if (typeof obj.digest !== 'string' || !HEX_64.test(obj.digest)) return { ok: false, reason: 'digest' };\n if (typeof obj.byteLength !== 'string' || !isDecimalWithinSafeRange(obj.byteLength)) {\n return { ok: false, reason: 'byteLength' };\n }\n if (canonicalText({ value: obj.value, digest: obj.digest, byteLength: obj.byteLength }) !== text) {\n return { ok: false, reason: 'not-canonical' };\n }\n const value = new Uint8Array(BLINDING_VALUE_BYTES);\n for (let i = 0; i < BLINDING_VALUE_BYTES; i += 1) value[i] = parseInt(obj.value.slice(i * 2, i * 2 + 2), 16);\n return { ok: true, blinding: { value, digest: obj.digest, byteLength: obj.byteLength } };\n}\n", "/**\n * What is known about a file the reader holds. Digests are computed from the\n * file's bytes, never from decoded text. `hmac` is present only when a\n * blinding file is given: the file's HMAC under its value, and the blinding\n * file's own `digest` and `byteLength`. The value itself is never here.\n */\nexport interface HeldFile {\n sha256: string;\n byteLength: string;\n hmac?: { digest: string; blindingDigest: string; blindingByteLength: string };\n}\n\nexport interface HeldFileMatch {\n matched: boolean;\n matchedIndex: number | null;\n /** The match was an `hmac-sha-256` item. */\n blinded: boolean;\n /** No match, no blinding given, and some item is blinded: a blinding file could decide it. */\n blindingNeeded: boolean;\n /** The blinding file does not describe the held file. */\n refused: null | 'blinding-length' | 'blinding-digest';\n}\n\n/**\n * The held-file rule for the SDK's `check` with files, the checker's\n * `--held-file` and the Shared Record. `items` is the record content's\n * top-level `payloads`; nested references are never matched.\n */\nexport function matchHeldFile(items: unknown, held: HeldFile): HeldFileMatch {\n const none = { matched: false, matchedIndex: null, blinded: false, blindingNeeded: false };\n if (held.hmac) {\n if (held.hmac.blindingByteLength !== held.byteLength) return { ...none, refused: 'blinding-length' };\n if (held.hmac.blindingDigest !== held.hmac.digest) return { ...none, refused: 'blinding-digest' };\n }\n const list = Array.isArray(items) ? items : [];\n for (let i = 0; i < list.length; i += 1) {\n const item = list[i];\n if (!item || typeof item !== 'object') continue;\n const { alg, digest, byteLength } = item as Record<string, unknown>;\n if (alg === 'hmac-sha-256') {\n if (held.hmac && digest === held.hmac.digest && String(byteLength) === held.byteLength) {\n return { matched: true, matchedIndex: i, blinded: true, blindingNeeded: false, refused: null };\n }\n continue;\n }\n if (digest === held.sha256 && (byteLength === undefined || byteLength === null || String(byteLength) === held.byteLength)) {\n return { matched: true, matchedIndex: i, blinded: false, blindingNeeded: false, refused: null };\n }\n }\n const blindingNeeded =\n !held.hmac && list.some((item) => !!item && typeof item === 'object' && (item as { alg?: unknown }).alg === 'hmac-sha-256');\n return { ...none, blindingNeeded, refused: null };\n}\n", "import { isNodeRuntime, loadNodeCrypto } from './blinding-value';\n\n/**\n * The platform's WebCrypto: `globalThis.crypto` where the runtime has it\n * (browsers, Node 19 and later), else `node:crypto`'s `webcrypto` (Node 18).\n * Record hash v2 and the disclosure envelope use only SHA-256, HMAC-SHA256\n * and AES-256-GCM through it (ADR 0016).\n */\nexport async function platformCrypto(): Promise<Crypto> {\n const global = (globalThis as { crypto?: Crypto }).crypto;\n if (global?.subtle && typeof global.getRandomValues === 'function') return global;\n if (isNodeRuntime()) {\n const nodeCrypto = await loadNodeCrypto();\n return nodeCrypto.webcrypto as unknown as Crypto;\n }\n throw new Error('This runtime has no WebCrypto.');\n}\n\n/** Random bytes, synchronously, from the global WebCrypto (every supported runtime has one). */\nexport function randomBytes(length: number): Uint8Array {\n const global = (globalThis as { crypto?: Crypto }).crypto;\n if (!global || typeof global.getRandomValues !== 'function') throw new Error('This runtime has no WebCrypto.');\n return global.getRandomValues(new Uint8Array(length));\n}\n\nexport async function sha256(bytes: Uint8Array): Promise<Uint8Array> {\n const { subtle } = await platformCrypto();\n return new Uint8Array(await subtle.digest('SHA-256', Uint8Array.from(bytes)));\n}\n\nexport async function hmacSha256(key: Uint8Array, bytes: Uint8Array): Promise<Uint8Array> {\n const { subtle } = await platformCrypto();\n const cryptoKey = await subtle.importKey('raw', Uint8Array.from(key), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);\n return new Uint8Array(await subtle.sign('HMAC', cryptoKey, Uint8Array.from(bytes)));\n}\n\nexport function concatBytes(...parts: Uint8Array[]): Uint8Array {\n const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n\nexport const utf8 = (s: string): Uint8Array => new TextEncoder().encode(s);\n\nexport const toHex0x = (bytes: Uint8Array): string =>\n '0x' + Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\n\nconst HEX32 = /^0x[0-9a-f]{64}$/;\nexport const isHex32 = (value: unknown): value is string => typeof value === 'string' && HEX32.test(value);\n\n/** Decodes `0x` plus 64 lowercase hex; the caller has checked the form. */\nexport function fromHex32(value: string): Uint8Array {\n const out = new Uint8Array(32);\n for (let i = 0; i < 32; i += 1) out[i] = parseInt(value.slice(2 + i * 2, 4 + i * 2), 16);\n return out;\n}\n", "import { canonicalizeJcs } from '../proof/jcs';\nimport { RecordIntakeError } from '../proof/layout-document-v1';\nimport { concatBytes, fromHex32, hmacSha256, isHex32, randomBytes, sha256, toHex0x, utf8 } from './platform-crypto';\n\n/**\n * Record hash v2 (ADR 0016; docs/spec/records/record-hash-v2.md): each\n * top-level member of an entry's content, and each element of a top-level\n * array, is one leaf with its own salt, and the record hash is SHA-256 over\n * the leaf count and the sorted leaf hashes. Everything after the record hash\n * (the opening, the seal, the word, the item hash) is slot-encoding-v1.\n */\nexport const RECORD_HASH_VERSION_V1 = 1 as const;\nexport const RECORD_HASH_VERSION_V2 = 2 as const;\nexport type RecordHashVersion = 1 | 2;\nexport const RECORD_LEAVES_MAX_V2 = 65535;\n\nexport interface RecordLeafV2 {\n pointer: string;\n value: unknown;\n}\n/** A leaf with its salt: `0x` plus 64 lowercase hex. */\nexport interface RevealedLeafV2 {\n pointer: string;\n value: unknown;\n salt: string;\n}\n\nconst LABEL_SALT = 'pacspace:record-leaf-salt:v2';\nconst LABEL_LEAF = 'pacspace:record-leaf:v2';\nconst LABEL_RECORD = 'pacspace:record:v2';\nconst SEP = new Uint8Array([0]);\n\nconst TOO_MANY_LEAVES = 'This entry has more than 65535 fields and list items. Split it across entries.';\nconst NOT_CANONICAL = \"This entry's sealed fields are not in their canonical form.\";\n/** The refusal for more leaves than a record hash can count (W-1). */\nexport const RECORD_LEAVES_TOO_MANY_V2 = TOO_MANY_LEAVES;\n/** The refusal for content that has no canonical v2 form (W-2b). */\nexport const RECORD_CONTENT_NOT_CANONICAL_V2 = NOT_CANONICAL;\n\nconst LONE_SURROGATE = /[\\ud800-\\udbff](?![\\udc00-\\udfff])|(?<![\\ud800-\\udbff])[\\udc00-\\udfff]/;\nconst CANONICAL_INDEX = /^(0|[1-9][0-9]*)$/;\nconst FIRST_SEGMENT = /^(?:[^~]|~[01])*$/;\n\nconst isPlainObject = (v: unknown): v is Record<string, unknown> =>\n !!v && typeof v === 'object' && !Array.isArray(v) &&\n (Object.getPrototypeOf(v) === Object.prototype || Object.getPrototypeOf(v) === null);\n\n/** True when a member name or string at any depth holds a lone UTF-16 surrogate. */\nfunction hasLoneSurrogate(value: unknown): boolean {\n if (typeof value === 'string') return LONE_SURROGATE.test(value);\n if (Array.isArray(value)) return value.some(hasLoneSurrogate);\n if (value && typeof value === 'object') {\n for (const [k, v] of Object.entries(value)) {\n if (LONE_SURROGATE.test(k) || hasLoneSurrogate(v)) return true;\n }\n }\n return false;\n}\n\nconst escapeSegment = (key: string) => key.replace(/~/g, '~0').replace(/\\//g, '~1');\nconst unescapeSegment = (segment: string) => segment.replace(/~1/g, '/').replace(/~0/g, '~');\n\n/** UTF-16 code-unit order, the order JCS uses for member names. */\nconst byPointer = (a: { pointer: string }, b: { pointer: string }) => (a.pointer < b.pointer ? -1 : a.pointer > b.pointer ? 1 : 0);\n\n/** A pointer's key and, for an array element, its index; null when not well-formed. */\n/** A v2 pointer's member name and element index, or null when it is not a canonical v2 pointer. */\nexport function parsePointerV2(pointer: unknown): { key: string; index: number | null } | null {\n if (typeof pointer !== 'string' || !pointer.startsWith('/') || LONE_SURROGATE.test(pointer)) return null;\n const segments = pointer.slice(1).split('/');\n if (segments.length > 2 || !FIRST_SEGMENT.test(segments[0])) return null;\n if (segments.length === 1) return { key: unescapeSegment(segments[0]), index: null };\n if (!CANONICAL_INDEX.test(segments[1]) || segments[1].length > 5) return null;\n return { key: unescapeSegment(segments[0]), index: Number(segments[1]) };\n}\n\n/** Leaves of one content object, sorted by pointer. Throws RecordIntakeError RECORD_CONTENT_INVALID. */\nexport function recordLeavesV2(content: Record<string, unknown>): RecordLeafV2[] {\n if (!isPlainObject(content)) throw new RecordIntakeError('RECORD_CONTENT_INVALID', 'content must be an object');\n if (hasLoneSurrogate(content)) throw new RecordIntakeError('RECORD_CONTENT_INVALID', NOT_CANONICAL);\n const leaves: RecordLeafV2[] = [];\n for (const [key, value] of Object.entries(content)) {\n if (value === undefined) continue;\n const base = '/' + escapeSegment(key);\n if (Array.isArray(value) && value.length > 0) {\n if (leaves.length + value.length > RECORD_LEAVES_MAX_V2) throw new RecordIntakeError('RECORD_CONTENT_INVALID', TOO_MANY_LEAVES);\n value.forEach((element, i) => leaves.push({ pointer: `${base}/${i}`, value: element }));\n } else {\n leaves.push({ pointer: base, value });\n }\n if (leaves.length > RECORD_LEAVES_MAX_V2) throw new RecordIntakeError('RECORD_CONTENT_INVALID', TOO_MANY_LEAVES);\n }\n return leaves.sort(byPointer);\n}\n\n/** The content rebuilt from a canonical full leaf set, or null when the set is not canonical. */\nexport function recordContentFromLeavesV2(leaves: readonly RecordLeafV2[]): Record<string, unknown> | null {\n const whole = new Map<string, unknown>();\n const arrays = new Map<string, Map<number, unknown>>();\n for (const leaf of leaves) {\n const parsed = parsePointerV2(leaf?.pointer);\n if (!parsed || leaf.value === undefined) return null;\n if (parsed.index === null) {\n if (whole.has(parsed.key) || arrays.has(parsed.key)) return null;\n whole.set(parsed.key, leaf.value);\n } else {\n if (whole.has(parsed.key)) return null;\n const elements = arrays.get(parsed.key) ?? new Map<number, unknown>();\n if (elements.has(parsed.index)) return null;\n elements.set(parsed.index, leaf.value);\n arrays.set(parsed.key, elements);\n }\n }\n const content: Record<string, unknown> = {};\n for (const [key, value] of whole) content[key] = value;\n for (const [key, elements] of arrays) {\n const list: unknown[] = [];\n for (let i = 0; i < elements.size; i += 1) {\n if (!elements.has(i)) return null;\n list.push(elements.get(i));\n }\n content[key] = list;\n }\n let again: RecordLeafV2[];\n try {\n again = recordLeavesV2(content);\n } catch {\n return null;\n }\n const given = [...leaves].sort(byPointer);\n if (again.length !== given.length) return null;\n for (let i = 0; i < again.length; i += 1) {\n if (again[i].pointer !== given[i].pointer) return null;\n try {\n if (canonicalizeJcs(again[i].value) !== canonicalizeJcs(given[i].value)) return null;\n } catch {\n return null;\n }\n }\n return content;\n}\n\n/** 32 fresh random bytes, as `0x` plus 64 lowercase hex. */\nexport function newSaltKeyV2(): string {\n return toHex0x(randomBytes(32));\n}\n\n/**\n * Queue items with every `saltKey` removed (ADR 0016). An overflow payload,\n * a settled job and a log line never hold one; anything that is not an array\n * of objects is returned as it is.\n */\nexport function withoutSaltKeysV2<T>(records: T): T {\n if (!Array.isArray(records)) return records;\n return records.map((record) => {\n if (!record || typeof record !== 'object' || !('saltKey' in record)) return record;\n const { saltKey: _omit, ...rest } = record as Record<string, unknown>;\n return rest;\n }) as unknown as T;\n}\n\n/** True when any queue item carries a `saltKey` member. */\nexport function carriesSaltKeyV2(records: unknown): boolean {\n return Array.isArray(records) && records.some((r) => !!r && typeof r === 'object' && 'saltKey' in r);\n}\n\nexport async function deriveLeafSaltV2(saltKey: string, pointer: string): Promise<string> {\n if (!isHex32(saltKey)) throw new RecordIntakeError('RECORD_CONTENT_INVALID', 'a salt key is 0x plus 64 lowercase hex');\n return toHex0x(await hmacSha256(fromHex32(saltKey), concatBytes(utf8(LABEL_SALT), SEP, utf8(pointer))));\n}\n\nexport async function computeLeafHashV2(leaf: RevealedLeafV2): Promise<string> {\n if (!isHex32(leaf.salt)) throw new RecordIntakeError('RECORD_CONTENT_INVALID', 'a leaf salt is 0x plus 64 lowercase hex');\n const message = canonicalizeJcs([leaf.pointer, leaf.value]);\n return toHex0x(await sha256(concatBytes(utf8(LABEL_LEAF), SEP, fromHex32(leaf.salt), utf8(message))));\n}\n\n/** Takes leaf hashes in strictly ascending order (0x lowercase hex); throws otherwise. */\nexport async function computeRecordHashV2(leaves: readonly string[]): Promise<string> {\n if (!Array.isArray(leaves) || leaves.length > RECORD_LEAVES_MAX_V2) {\n throw new RecordIntakeError('RECORD_CONTENT_INVALID', 'a record hash takes 0 to 65535 leaves');\n }\n for (let i = 0; i < leaves.length; i += 1) {\n if (!isHex32(leaves[i]) || (i > 0 && !(leaves[i - 1] < leaves[i]))) {\n throw new RecordIntakeError('RECORD_CONTENT_INVALID', 'leaf hashes must be 0x lowercase hex, strictly ascending');\n }\n }\n const count = new Uint8Array([(leaves.length >> 8) & 0xff, leaves.length & 0xff]);\n return toHex0x(await sha256(concatBytes(utf8(LABEL_RECORD), SEP, count, ...leaves.map(fromHex32))));\n}\n\n/** Everything a v2 entry needs: the record hash, every leaf hash (sorted), every leaf with its salt (by pointer). */\nexport async function commitRecordContentV2(\n content: Record<string, unknown>,\n saltKey: string,\n): Promise<{ recordHash: string; leaves: string[]; revealed: RevealedLeafV2[] }> {\n const fields = recordLeavesV2(content);\n const revealed: RevealedLeafV2[] = [];\n const leaves: string[] = [];\n for (const field of fields) {\n const leaf = { pointer: field.pointer, value: field.value, salt: await deriveLeafSaltV2(saltKey, field.pointer) };\n revealed.push(leaf);\n leaves.push(await computeLeafHashV2(leaf));\n }\n leaves.sort();\n return { recordHash: await computeRecordHashV2(leaves), leaves, revealed };\n}\n\nexport type OpenRecordEntryV2Result =\n | { ok: true; recordHash: string; fields: RecordLeafV2[]; withheld: number; content: Record<string, unknown> | null }\n | { ok: false; failure: 'malformed' | 'leaf-mismatch' | 'not-canonical'; reason: string };\n\nconst SHOWN_FIELD_MISMATCH = 'A shown field of this entry does not match the fields sealed for it.';\nconst MALFORMED = NOT_CANONICAL;\n\n/** Opens an entry: every revealed leaf must recompute and appear in `leaves`. `every` requires all leaves revealed. */\nexport async function openRecordEntryV2(\n entry: { leaves: readonly string[]; revealed: readonly RevealedLeafV2[] },\n options: { every: boolean },\n): Promise<OpenRecordEntryV2Result> {\n const malformed = { ok: false as const, failure: 'malformed' as const, reason: MALFORMED };\n const leaves = entry?.leaves;\n const revealed = entry?.revealed;\n if (!Array.isArray(leaves) || leaves.length > RECORD_LEAVES_MAX_V2 || !Array.isArray(revealed)) return malformed;\n for (let i = 0; i < leaves.length; i += 1) {\n if (!isHex32(leaves[i]) || (i > 0 && !(leaves[i - 1] < leaves[i]))) return malformed;\n }\n for (let i = 0; i < revealed.length; i += 1) {\n const leaf = revealed[i];\n if (!isPlainObject(leaf) || !parsePointerV2(leaf.pointer) || !isHex32(leaf.salt) || leaf.value === undefined) return malformed;\n if (i > 0 && !(revealed[i - 1].pointer < (leaf.pointer as string))) return malformed;\n if (hasLoneSurrogate(leaf.value)) return malformed;\n try {\n canonicalizeJcs(leaf.value);\n } catch {\n return malformed;\n }\n }\n const known = new Set(leaves);\n for (const leaf of revealed) {\n if (!known.has(await computeLeafHashV2(leaf))) return { ok: false, failure: 'leaf-mismatch', reason: SHOWN_FIELD_MISMATCH };\n }\n const fields = revealed.map((l) => ({ pointer: l.pointer, value: l.value }));\n const full = revealed.length === leaves.length;\n const content = full ? recordContentFromLeavesV2(fields) : null;\n if (options.every && (!full || content === null)) return { ok: false, failure: 'not-canonical', reason: NOT_CANONICAL };\n return { ok: true, recordHash: await computeRecordHashV2(leaves), fields, withheld: leaves.length - revealed.length, content };\n}\n", "import { canonicalizeJcs } from '../proof/jcs';\nimport { RecordIntakeError } from '../proof/layout-document-v1';\nimport { concatBytes, fromHex32, hmacSha256, isHex32, sha256, toHex0x, utf8 } from './platform-crypto';\nimport { recordContentFromLeavesV2, recordLeavesV2, type RecordLeafV2, type RevealedLeafV2 } from './record-hash-v2';\n\n/**\n * Record hash v3 (card 10, F1; docs/spec/records/record-hash-v3.md): members,\n * not pointers. Each leaf is committed as an item (memberTag, slot, leafHash):\n * the member tag names the top-level member, the slot is 0xFFFF for a whole\n * member or the element's index, and every group of items with one tag is\n * either one whole item or slots exactly 0..m-1. A member therefore has\n * exactly one committed value, which a partial disclosure cannot double.\n * Leaves are the same as v2's (recordLeavesV2); only the labels, the items\n * and the hash over them differ. The seal is over sealInputHash(3, hash).\n */\nexport const RECORD_HASH_VERSION_V3 = 3 as const;\nexport const RECORD_ITEMS_MAX_V3 = 65535;\nexport const RECORD_SLOT_WHOLE_V3 = 0xffff;\nconst ELEMENT_INDEX_MAX_V3 = 65534;\n\n/** [memberTag, slot, leafHash]: tag and leaf hash `0x` plus 64 lowercase hex, slot an integer 0..65535. */\nexport type RecordItemV3 = [string, number, string];\n\nconst LABEL_MEMBER = 'pacspace:record-member:v3';\nconst LABEL_SALT = 'pacspace:record-leaf-salt:v3';\nconst LABEL_LEAF = 'pacspace:record-leaf:v3';\nconst LABEL_RECORD = 'pacspace:record:v3';\nconst SEP = new Uint8Array([0]);\n\nconst NOT_CANONICAL = \"This entry's sealed fields are not in their canonical form.\";\nconst SHOWN_FIELD_MISMATCH = 'A shown field of this entry does not match the fields sealed for it.';\n\nconst LONE_SURROGATE = /[\\ud800-\\udbff](?![\\udc00-\\udfff])|(?<![\\ud800-\\udbff])[\\udc00-\\udfff]/;\nconst CANONICAL_INDEX = /^(0|[1-9][0-9]{0,4})$/;\nconst FIRST_SEGMENT = /^(?:[^~]|~[01])*$/;\n\nconst escapeSegment = (key: string) => key.replace(/~/g, '~0').replace(/\\//g, '~1');\nconst unescapeSegment = (segment: string) => segment.replace(/~1/g, '/').replace(/~0/g, '~');\n\nconst isPlainObject = (v: unknown): v is Record<string, unknown> =>\n !!v && typeof v === 'object' && !Array.isArray(v) &&\n (Object.getPrototypeOf(v) === Object.prototype || Object.getPrototypeOf(v) === null);\n\nfunction hasLoneSurrogate(value: unknown): boolean {\n if (typeof value === 'string') return LONE_SURROGATE.test(value);\n if (Array.isArray(value)) return value.some(hasLoneSurrogate);\n if (value && typeof value === 'object') {\n return Object.entries(value).some(([k, v]) => LONE_SURROGATE.test(k) || hasLoneSurrogate(v));\n }\n return false;\n}\n\n/** A v3 pointer's member name and element index (at most 65534), or null. */\nexport function parsePointerV3(pointer: unknown): { key: string; index: number | null } | null {\n if (typeof pointer !== 'string' || !pointer.startsWith('/') || LONE_SURROGATE.test(pointer)) return null;\n const segments = pointer.slice(1).split('/');\n if (segments.length > 2 || !FIRST_SEGMENT.test(segments[0])) return null;\n if (segments.length === 1) return { key: unescapeSegment(segments[0]), index: null };\n if (!CANONICAL_INDEX.test(segments[1])) return null;\n const index = Number(segments[1]);\n if (index > ELEMENT_INDEX_MAX_V3) return null;\n return { key: unescapeSegment(segments[0]), index };\n}\n\n/** SHA-256(\"pacspace:record-member:v3\" || 0x00 || UTF-8(escaped member name)); unsalted, so a partial reader can recompute it. */\nexport async function memberTagV3(key: string): Promise<string> {\n return toHex0x(await sha256(concatBytes(utf8(LABEL_MEMBER), SEP, utf8(escapeSegment(key)))));\n}\n\nexport async function deriveLeafSaltV3(saltKey: string, pointer: string): Promise<string> {\n if (!isHex32(saltKey)) throw new RecordIntakeError('RECORD_CONTENT_INVALID', 'a salt key is 0x plus 64 lowercase hex');\n return toHex0x(await hmacSha256(fromHex32(saltKey), concatBytes(utf8(LABEL_SALT), SEP, utf8(pointer))));\n}\n\nexport async function computeLeafHashV3(leaf: RevealedLeafV2): Promise<string> {\n if (!isHex32(leaf.salt)) throw new RecordIntakeError('RECORD_CONTENT_INVALID', 'a leaf salt is 0x plus 64 lowercase hex');\n const message = canonicalizeJcs([leaf.pointer, leaf.value]);\n return toHex0x(await sha256(concatBytes(utf8(LABEL_LEAF), SEP, fromHex32(leaf.salt), utf8(message))));\n}\n\nconst isSlot = (v: unknown): v is number => typeof v === 'number' && Number.isInteger(v) && v >= 0 && v <= RECORD_SLOT_WHOLE_V3;\n\n/** Bytewise order of the 34-byte (tag, u16be slot) prefix. Tags are same-length lowercase hex. */\nconst comparePrefix = (a: RecordItemV3, b: RecordItemV3) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : a[1] - b[1]);\n\n/** True when the items are well formed, strictly ascending, and every group is one whole item or slots 0..m-1. */\nexport function validateRecordItemsV3(items: unknown): items is RecordItemV3[] {\n if (!Array.isArray(items) || items.length > RECORD_ITEMS_MAX_V3) return false;\n let groupTag: string | null = null;\n let groupWhole = false;\n let nextSlot = 0;\n for (let i = 0; i < items.length; i += 1) {\n const item = items[i];\n if (!Array.isArray(item) || item.length !== 3) return false;\n const [tag, slot, leafHash] = item;\n if (!isHex32(tag) || !isSlot(slot) || !isHex32(leafHash)) return false;\n if (i > 0 && comparePrefix(items[i - 1] as RecordItemV3, item as RecordItemV3) >= 0) return false;\n if (tag !== groupTag) {\n groupTag = tag;\n groupWhole = slot === RECORD_SLOT_WHOLE_V3;\n if (!groupWhole && slot !== 0) return false;\n nextSlot = 1;\n continue;\n }\n if (groupWhole || slot === RECORD_SLOT_WHOLE_V3 || slot !== nextSlot) return false;\n nextSlot += 1;\n }\n return true;\n}\n\n/** SHA-256(\"pacspace:record:v3\" || 0x00 || u16be(n) || item_1 || ... || item_n); throws on items that do not validate. */\nexport async function computeRecordHashV3(items: readonly RecordItemV3[]): Promise<string> {\n if (!validateRecordItemsV3(items)) {\n throw new RecordIntakeError('RECORD_CONTENT_INVALID', 'record items must be well formed, strictly ascending and grouped');\n }\n const count = new Uint8Array([(items.length >> 8) & 0xff, items.length & 0xff]);\n return toHex0x(await sha256(concatBytes(utf8(LABEL_RECORD), SEP, count, ...items.map(itemBytes))));\n}\n\nfunction itemBytes([tag, slot, leafHash]: RecordItemV3): Uint8Array {\n return concatBytes(fromHex32(tag), new Uint8Array([(slot >> 8) & 0xff, slot & 0xff]), fromHex32(leafHash));\n}\n\nasync function itemOf(leaf: RevealedLeafV2): Promise<RecordItemV3 | null> {\n const parsed = parsePointerV3(leaf.pointer);\n if (!parsed) return null;\n return [await memberTagV3(parsed.key), parsed.index ?? RECORD_SLOT_WHOLE_V3, await computeLeafHashV3(leaf)];\n}\n\n/** Everything a v3 entry needs: the record hash, every item (sorted), every leaf with its salt (by pointer). */\nexport async function commitRecordContentV3(\n content: Record<string, unknown>,\n saltKey: string,\n): Promise<{ recordHash: string; items: RecordItemV3[]; revealed: RevealedLeafV2[] }> {\n const fields = recordLeavesV2(content);\n const revealed: RevealedLeafV2[] = [];\n const items: RecordItemV3[] = [];\n for (const field of fields) {\n if (!parsePointerV3(field.pointer)) throw new RecordIntakeError('RECORD_CONTENT_INVALID', NOT_CANONICAL);\n const leaf = { pointer: field.pointer, value: field.value, salt: await deriveLeafSaltV3(saltKey, field.pointer) };\n revealed.push(leaf);\n items.push((await itemOf(leaf)) as RecordItemV3);\n }\n items.sort(comparePrefix);\n return { recordHash: await computeRecordHashV3(items), items, revealed };\n}\n\nexport type OpenRecordEntryV3Result =\n | { ok: true; recordHash: string; fields: RecordLeafV2[]; withheld: number; content: Record<string, unknown> | null }\n | { ok: false; failure: 'malformed' | 'leaf-mismatch' | 'not-canonical'; reason: string };\n\n/**\n * Opens a v3 entry. Every group is checked, shown or not. Each shown leaf's\n * recomputed (memberTag, slot, leafHash) must equal one item exactly. A whole\n * leaf holding a non-empty array is refused. `every` requires all items shown\n * and the content canonical.\n */\nexport async function openRecordEntryV3(\n entry: { items: readonly RecordItemV3[]; revealed: readonly RevealedLeafV2[] },\n options: { every: boolean },\n): Promise<OpenRecordEntryV3Result> {\n const malformed = { ok: false as const, failure: 'malformed' as const, reason: NOT_CANONICAL };\n const items = entry?.items;\n const revealed = entry?.revealed;\n if (!validateRecordItemsV3(items) || !Array.isArray(revealed) || revealed.length > items.length) return malformed;\n for (let i = 0; i < revealed.length; i += 1) {\n const leaf = revealed[i];\n if (!isPlainObject(leaf) || !isHex32(leaf.salt) || leaf.value === undefined) return malformed;\n const parsed = parsePointerV3(leaf.pointer);\n if (!parsed) return malformed;\n if (i > 0 && !(revealed[i - 1].pointer < (leaf.pointer as string))) return malformed;\n if (parsed.index === null && Array.isArray(leaf.value) && leaf.value.length > 0) return malformed;\n if (hasLoneSurrogate(leaf.value)) return malformed;\n try {\n canonicalizeJcs(leaf.value);\n } catch {\n return malformed;\n }\n }\n const byPrefix = new Map(items.map((it) => [`${it[0]}:${it[1]}`, it[2]] as const));\n for (const leaf of revealed) {\n const item = (await itemOf(leaf)) as RecordItemV3;\n if (byPrefix.get(`${item[0]}:${item[1]}`) !== item[2]) return { ok: false, failure: 'leaf-mismatch', reason: SHOWN_FIELD_MISMATCH };\n }\n const fields = revealed.map((l) => ({ pointer: l.pointer, value: l.value }));\n const full = revealed.length === items.length;\n const content = full ? recordContentFromLeavesV2(fields) : null;\n if (options.every && (!full || content === null)) return { ok: false, failure: 'not-canonical', reason: NOT_CANONICAL };\n return { ok: true, recordHash: await computeRecordHashV3(items), fields, withheld: items.length - revealed.length, content };\n}\n", "import { ethers } from 'ethers';\nimport {\n buildMerkleProofV2,\n computeMerkleItemsRootV2,\n normalizeProofHash,\n} from './merkle-v2';\n\n/**\n * Per-item hiding commitments (ADR 0008 \u00A74).\n *\n * The canonical content fingerprint (`itemHash`) is unchanged. What gets\n * published is a position-bound hiding commitment derived from the fingerprint\n * plus a per-item opening, where every opening is derived from one random\n * per-batch seed:\n *\n * itemOpening[i] = HMAC-SHA256(batchSeed,\n * \"pacspace:item-opening:v1\" || 0x00 || uint32be(i) || itemHash[i])\n *\n * publishedLeaf[i] = keccak256(\n * \"pacspace:published-leaf:v1\" || 0x00 || uint32be(i) || itemHash[i]\n * || itemOpening[i])\n *\n * The published root is the existing pair-sorted-keccak-v2 Merkle root over\n * `publishedLeaf[]`, never over raw fingerprints. A receipt disclosed for one\n * item carries only that item's index, opening, and proof path; sibling nodes\n * are themselves hiding commitments, so no other event's raw fingerprint is\n * ever disclosed.\n *\n * This module is intentionally implemented with ethers primitives only\n * (keccak256, computeHmac, randomBytes) so the verifier half stays usable in\n * browser bundles for independent, offline receipt verification.\n */\n\n/**\n * Anchor-level proof algorithm identifier recorded for batches and\n * checkpoints whose published root commits to hiding commitments.\n */\nexport const PROOF_ALGORITHM_HIDING_COMMITMENT_V1 = 'hiding-commitment-v1';\n\nconst OPENING_DOMAIN = ethers.toUtf8Bytes('pacspace:item-opening:v1');\nconst LEAF_DOMAIN = ethers.toUtf8Bytes('pacspace:published-leaf:v1');\nconst SEPARATOR = new Uint8Array([0x00]);\n\nfunction uint32be(value: number): Uint8Array {\n if (!Number.isInteger(value) || value < 0 || value > 0xffffffff) {\n throw new Error(`item index ${value} is out of uint32 range.`);\n }\n const bytes = new Uint8Array(4);\n bytes[0] = (value >>> 24) & 0xff;\n bytes[1] = (value >>> 16) & 0xff;\n bytes[2] = (value >>> 8) & 0xff;\n bytes[3] = value & 0xff;\n return bytes;\n}\n\n/**\n * Generate a cryptographically random 32-byte batch or checkpoint seed.\n * The seed is availability-critical for receipt re-issuance: it must be\n * persisted encrypted at rest and must never appear in an API response,\n * log line, receipt, or calldata.\n */\nexport function generateBatchSeedV1(): string {\n return ethers.hexlify(ethers.randomBytes(32));\n}\n\n/**\n * Derive the undisclosed opening for one item position.\n */\nexport function deriveItemOpeningV1(\n batchSeed: string,\n itemIndex: number,\n itemHash: string,\n): string {\n const seed = normalizeProofHash(batchSeed, 'batchSeed');\n const hash = normalizeProofHash(itemHash, 'itemHash');\n const message = ethers.concat([\n OPENING_DOMAIN,\n SEPARATOR,\n uint32be(itemIndex),\n ethers.getBytes(hash),\n ]);\n return ethers.computeHmac('sha256', seed, message);\n}\n\n/**\n * Compute the position-bound published leaf for one item.\n */\nexport function computePublishedLeafV1(\n itemIndex: number,\n itemHash: string,\n itemOpening: string,\n): string {\n const hash = normalizeProofHash(itemHash, 'itemHash');\n const opening = normalizeProofHash(itemOpening, 'itemOpening');\n const message = ethers.concat([\n LEAF_DOMAIN,\n SEPARATOR,\n uint32be(itemIndex),\n ethers.getBytes(hash),\n ethers.getBytes(opening),\n ]);\n return ethers.keccak256(message);\n}\n\nexport interface HidingCommitmentBatchV1 {\n /** One undisclosed opening per item position. Receipt material only. */\n itemOpenings: string[];\n /** Position-bound hiding commitments; these are the published leaves. */\n publishedLeaves: string[];\n /** pair-sorted-keccak-v2 root over publishedLeaves. */\n publishedRoot: string;\n}\n\n/**\n * Build the complete hiding-commitment set for a batch or checkpoint.\n * `itemHashes` must already be in canonical order (submission order for\n * batches, deterministic sorted order for checkpoints); the index of each\n * hash is bound into its commitment.\n */\nexport function buildHidingCommitmentsV1(\n batchSeed: string,\n itemHashes: string[],\n): HidingCommitmentBatchV1 {\n if (!Array.isArray(itemHashes) || itemHashes.length === 0) {\n throw new Error('itemHashes must be a non-empty array.');\n }\n const itemOpenings: string[] = [];\n const publishedLeaves: string[] = [];\n for (let index = 0; index < itemHashes.length; index += 1) {\n const opening = deriveItemOpeningV1(batchSeed, index, itemHashes[index]);\n itemOpenings.push(opening);\n publishedLeaves.push(\n computePublishedLeafV1(index, itemHashes[index], opening),\n );\n }\n return {\n itemOpenings,\n publishedLeaves,\n publishedRoot: computeMerkleItemsRootV2(publishedLeaves),\n };\n}\n\n/**\n * Build the sorted-pair Merkle proof for one published leaf.\n */\nexport function buildPublishedLeafProofV1(\n publishedLeaves: string[],\n itemIndex: number,\n): string[] {\n return buildMerkleProofV2(publishedLeaves, itemIndex);\n}\n\nexport interface HiddenItemProofV1 {\n /** Canonical content fingerprint, recomputed by the caller from disclosed\n * event content. Never accept this value from an untrusted proof blob\n * without recomputing it. */\n itemHash: string;\n /** Position of the item inside the committed batch or checkpoint. */\n itemIndex: number;\n /** The opening disclosed in the authorized receipt for this item. */\n itemOpening: string;\n /** Sorted-pair sibling path from the published leaf to the root. */\n proof: string[];\n /** The published (on-chain) root to verify against. */\n expectedRoot: string;\n}\n\n/**\n * Verify that one disclosed event is committed under a published root.\n *\n * This is the canonical-event semantic verifier: it always recomputes the\n * position-bound leaf from (index, fingerprint, opening) before folding the\n * proof path. A bare 32-byte value is never accepted as a leaf, so a real\n * internal tree node with a shortened proof cannot masquerade as a usage\n * event (ADR 0008 Required Verification 12).\n */\nexport function verifyHiddenItemProofV1(input: HiddenItemProofV1): boolean {\n const root = normalizeProofHash(input.expectedRoot, 'expectedRoot');\n if (!Array.isArray(input.proof)) return false;\n let node: string;\n try {\n node = computePublishedLeafV1(\n input.itemIndex,\n input.itemHash,\n input.itemOpening,\n );\n } catch {\n return false;\n }\n try {\n for (let i = 0; i < input.proof.length; i += 1) {\n const sibling = normalizeProofHash(input.proof[i], `proof[${i}]`);\n const low = node < sibling ? node : sibling;\n const high = node < sibling ? sibling : node;\n node = ethers.keccak256(\n ethers.concat([ethers.getBytes(low), ethers.getBytes(high)]),\n );\n }\n } catch {\n return false;\n }\n return node === root;\n}\n", "import { ethers } from 'ethers';\n\nexport const MERKLE_ITEMS_ROOT_ALGORITHM_V2 = 'pair-sorted-keccak-v2';\n\nexport function normalizeProofHash(value: string, fieldName = 'hash'): string {\n const normalized = String(value || '').trim().toLowerCase();\n if (!/^0x[a-f0-9]{64}$/.test(normalized)) {\n throw new Error(`${fieldName} must be a 32-byte hex value.`);\n }\n return normalized;\n}\n\nexport function normalizeFingerprintList(fingerprints: string[]): string[] {\n if (!Array.isArray(fingerprints)) {\n throw new Error('fingerprints must be an array.');\n }\n return fingerprints.map((value, index) =>\n normalizeProofHash(value, `fingerprints[${index}]`),\n );\n}\n\nexport function computeMerkleItemsRootV2(fingerprints: string[]): string {\n const normalized = normalizeFingerprintList(fingerprints);\n if (normalized.length === 0) return ethers.ZeroHash;\n if (normalized.length === 1) return normalized[0];\n\n let layer = [...normalized];\n while (layer.length > 1) {\n const next: string[] = [];\n for (let i = 0; i < layer.length; i += 2) {\n const left = layer[i];\n const right = layer[i + 1] || left;\n const low = left < right ? left : right;\n const high = left < right ? right : left;\n next.push(\n ethers.keccak256(\n ethers.concat([ethers.getBytes(low), ethers.getBytes(high)]),\n ),\n );\n }\n layer = next;\n }\n return layer[0];\n}\n\nexport function buildMerkleProofV2(\n fingerprints: string[],\n targetIndex: number,\n): string[] {\n const normalized = normalizeFingerprintList(fingerprints);\n if (targetIndex < 0 || targetIndex >= normalized.length) {\n throw new Error(`targetIndex ${targetIndex} is out of range.`);\n }\n\n let layer = [...normalized];\n let index = targetIndex;\n const proof: string[] = [];\n\n while (layer.length > 1) {\n const siblingIndex = index ^ 1;\n proof.push(siblingIndex < layer.length ? layer[siblingIndex] : layer[index]);\n\n const next: string[] = [];\n for (let i = 0; i < layer.length; i += 2) {\n const left = layer[i];\n const right = layer[i + 1] || left;\n const low = left < right ? left : right;\n const high = left < right ? right : left;\n next.push(\n ethers.keccak256(\n ethers.concat([ethers.getBytes(low), ethers.getBytes(high)]),\n ),\n );\n }\n layer = next;\n index = Math.floor(index / 2);\n }\n\n return proof;\n}\n", "import { ethers } from 'ethers';\nimport { normalizeProofHash } from './merkle-v2';\n\n/**\n * The hash a seal is computed over (card 10, F1; record-hash spec, sealing).\n * Versions 1 and 2 seal the record hash itself. Version 3 seals\n * SHA-256(\"pacspace:record-hash-version:v1\" || 0x00 || u8(3) || recordHash),\n * so a record's hash version is fixed on the ledger: a v3 hash read as v2, or\n * a v2 hash read as v3, reproduces no seal. Rows, receipts and forms carry the\n * raw record hash; only the seal's input is wrapped.\n *\n * A verifier passes 3 only for a hash it recomputed under the v3 member\n * algorithm, or on a seal-only path that claims no content.\n */\nexport type SealedRecordHashVersion = 1 | 2 | 3;\n\nconst LABEL = 'pacspace:record-hash-version:v1';\n\nexport function sealInputHash(version: SealedRecordHashVersion, recordHash: string): string {\n const hash = normalizeProofHash(recordHash, 'recordHash');\n if (version === 1 || version === 2) return hash;\n if (version !== 3) throw new Error(`record hash version ${String(version)} has no seal input`);\n return ethers.sha256(ethers.concat([ethers.toUtf8Bytes(LABEL), new Uint8Array([0, 3]), ethers.getBytes(hash)]));\n}\n", "import { ethers } from 'ethers';\nimport { canonicalizeJcs } from './jcs';\nimport {\n DecodedState,\n LayoutDocumentV1,\n RecordIntakeError,\n StateFieldValues,\n computeLayoutDigestV1,\n decodeStateV1,\n isTransitionAllowedV1,\n packStateV1,\n readLayoutIdFromState,\n} from './layout-document-v1';\nimport { validatePayloadRefsInContent } from './payload-ref-v1';\nimport {\n buildHidingCommitmentsV1,\n computePublishedLeafV1,\n deriveItemOpeningV1,\n} from './hiding-commitment-v1';\nimport { buildMerkleProofV2, computeMerkleItemsRootV2, normalizeProofHash } from './merkle-v2';\nimport { sealInputHash, type SealedRecordHashVersion } from './seal-input';\nimport { nextLedgerHeadV1 } from './ledger-head-v1';\n\n/**\n * slot-encoding-v1: the byte-exact construction of the additive record lane\n * (ADR 0012; docs/spec/records/slot-encoding-v1.md). Every function here is\n * mirrored by scripts/records/generate-slot-encoding-vectors.mjs and pinned\n * by packages/shared/src/proof/__vectors__/slot-encoding-v1.json.\n *\n * The bitmask lane (canonical-item-v1, hiding-commitment-v1, merkle-v2,\n * semantic-receipt-v1) is not modified; this module composes it.\n */\n\nexport const SLOT_ENCODING_VERSION_V1 = 1;\nexport const SLOT_STATE_BITS = 96;\nexport const SLOT_SEAL_BITS = 160;\nexport const SLOT_SEAL_MASK = (1n << 160n) - 1n;\n// Upper bound of the state region (2^96 - 1). Written as a mask, not a shift:\n// the record lane never shifts a wallet or a raw index into a key (ADR 0008 \u00A72\n// gate); the state region is a bounded field under a published layout.\nexport const SLOT_STATE_MASK = (1n << BigInt(SLOT_STATE_BITS)) - 1n;\nexport const SLOT_ITEM_KIND_V1 = 'slot-v1';\n\nexport const SLOT_DOMAINS_V1 = {\n slotKey: 'pacspace:slot-key:v1',\n slotOpening: 'pacspace:slot-opening:v1',\n slotCommit: 'pacspace:slot-commit:v1',\n record: 'pacspace:record:v1',\n slotItem: 'pacspace:slot-item:v1',\n intake: 'pacspace:record-intake:v1',\n} as const;\n\nexport const WRITE_RECORD_BATCH_SIGNATURE_V1 =\n 'writeRecordBatchAndCommit(bytes32[],uint256[],uint256[],uint8,bytes32,uint256)';\n\n/** Reserved flag names every layout that records attempts or failures carries. */\nexport const FLAG_TRANSITION_NOT_APPLIED = 'transition_not_applied';\nexport const FLAG_DELIVERY_FAILED = 'delivery_failed';\n\nconst SEP = new Uint8Array([0x00]);\nconst utf8 = (s: string) => ethers.toUtf8Bytes(s);\nconst bytes = (h: string) => ethers.getBytes(h);\n\nfunction uintBe(value: bigint | number | string, bits: number): Uint8Array {\n const v = BigInt(value);\n if (v < 0n || v >= 1n << BigInt(bits)) {\n throw new RecordIntakeError('RECORD_QUANTITY_OVERFLOW', `value ${v} is out of uint${bits} range`);\n }\n return bytes(ethers.toBeHex(v, bits / 8));\n}\n\nexport const hex256 = (v: bigint | number | string): string => ethers.toBeHex(BigInt(v), 32);\nexport const hex160 = (v: bigint | number | string): string => ethers.toBeHex(BigInt(v), 20);\nexport const hex96 = (v: bigint | number | string): string => ethers.toBeHex(BigInt(v), 12);\n\n// ----------------------------------------------------------------- registry\n\nexport interface RegisteredLayout {\n doc: LayoutDocumentV1;\n digest: string;\n}\n\nexport type LayoutRegistry = ReadonlyMap<number, RegisteredLayout>;\n\nexport function buildLayoutRegistry(docs: LayoutDocumentV1[]): LayoutRegistry {\n const map = new Map<number, RegisteredLayout>();\n for (const doc of docs) map.set(doc.layoutId, { doc, digest: computeLayoutDigestV1(doc) });\n return map;\n}\n\nexport function getLayoutOrThrow(registry: LayoutRegistry, layoutId: number): RegisteredLayout {\n const found = registry.get(layoutId);\n if (!found) throw new RecordIntakeError('LAYOUT_NOT_FOUND', `layout 0x${layoutId.toString(16).padStart(4, '0')} is not registered`);\n return found;\n}\n\n// ----------------------------------------------------------------- primitives\n\n/** recordKey = HMAC-SHA256(tenantKey, domain || 0x00 || recordTypeId || 0x00 || entityId). */\nexport function deriveRecordKeyV1(tenantKey: string, recordTypeId: string, entityId: string): string {\n const key = normalizeProofHash(tenantKey, 'tenantKey');\n return ethers.computeHmac(\n 'sha256',\n key,\n ethers.concat([utf8(SLOT_DOMAINS_V1.slotKey), SEP, utf8(recordTypeId), SEP, utf8(entityId)]),\n );\n}\n\n/** recordHash = keccak256(domain || 0x00 || JCS(content)). */\nexport function computeRecordHashV1(content: unknown): string {\n return ethers.keccak256(ethers.concat([utf8(SLOT_DOMAINS_V1.record), SEP, utf8(canonicalizeJcs(content))]));\n}\n\n/** recordOpening = HMAC-SHA256(batchSeed, domain || 0x00 || uint32be(itemIndex) || recordKey). */\nexport function deriveRecordOpeningV1(batchSeed: string, itemIndex: number, recordKey: string): string {\n const seed = normalizeProofHash(batchSeed, 'batchSeed');\n const key = normalizeProofHash(recordKey, 'recordKey');\n return ethers.computeHmac(\n 'sha256',\n seed,\n ethers.concat([utf8(SLOT_DOMAINS_V1.slotOpening), SEP, uintBe(itemIndex, 32), bytes(key)]),\n );\n}\n\nexport interface SealInputV1 {\n layoutId: number;\n layoutVersion: number;\n layoutDigest: string;\n state96: bigint;\n recordHash: string;\n recordOpening: string;\n}\n\n/** seal = keccak256(domain||0x00||uint16be(layoutId)||uint8(layoutVersion)||layoutDigest||uint96be(state96)||recordHash||recordOpening). */\nexport function computeSealV1(input: SealInputV1): string {\n return ethers.keccak256(\n ethers.concat([\n utf8(SLOT_DOMAINS_V1.slotCommit),\n SEP,\n uintBe(input.layoutId, 16),\n uintBe(input.layoutVersion, 8),\n bytes(normalizeProofHash(input.layoutDigest, 'layoutDigest')),\n uintBe(input.state96, 96),\n bytes(normalizeProofHash(input.recordHash, 'recordHash')),\n bytes(normalizeProofHash(input.recordOpening, 'recordOpening')),\n ]),\n );\n}\n\nexport function sealTagOfV1(seal: string): string {\n return hex160(BigInt(normalizeProofHash(seal, 'seal')) & SLOT_SEAL_MASK);\n}\n\nexport function composeWordV1(state96: bigint, seal: string): bigint {\n if (state96 < 0n || state96 > SLOT_STATE_MASK) throw new RecordIntakeError('RECORD_QUANTITY_OVERFLOW', 'state96 out of range');\n return (state96 << 160n) | (BigInt(normalizeProofHash(seal, 'seal')) & SLOT_SEAL_MASK);\n}\n\nexport interface SplitWordV1 {\n state96: bigint;\n state96Hex: string;\n sealTag: string;\n layoutId: number;\n layoutVersion: number;\n}\n\n/** Shift-and-mask: the public state region and the seal tag of a word. */\nexport function splitWordV1(word: string | bigint): SplitWordV1 {\n const w = BigInt(word);\n if (w < 0n || w >= 1n << 256n) throw new RecordIntakeError('RECORD_CONTENT_INVALID', 'word out of uint256 range');\n const state96 = w >> 160n;\n const { layoutId, layoutVersion } = readLayoutIdFromState(state96);\n return { state96, state96Hex: hex96(state96), sealTag: hex160(w & SLOT_SEAL_MASK), layoutId, layoutVersion };\n}\n\n/** Decode the public state of a word under the registry; LAYOUT_NOT_FOUND for unregistered layout ids. */\nexport function decodeWordV1(registry: LayoutRegistry, word: string | bigint): SplitWordV1 & { layout: RegisteredLayout; decodedState: DecodedState } {\n const split = splitWordV1(word);\n const layout = getLayoutOrThrow(registry, split.layoutId);\n return { ...split, layout, decodedState: decodeStateV1(layout.doc, split.state96) };\n}\n\nexport interface SlotItemInputV1 {\n recordKey: string;\n seq: number;\n previousWord: string | bigint;\n newWord: string | bigint;\n seal: string;\n}\n\n/** itemHash = keccak256(domain||0x00||recordKey||uint32be(seq)||uint256be(previousWord)||uint256be(newWord)||seal). */\nexport function computeSlotItemHashV1(input: SlotItemInputV1): string {\n return ethers.keccak256(\n ethers.concat([\n utf8(SLOT_DOMAINS_V1.slotItem),\n SEP,\n bytes(normalizeProofHash(input.recordKey, 'recordKey')),\n uintBe(input.seq, 32),\n uintBe(BigInt(input.previousWord), 256),\n uintBe(BigInt(input.newWord), 256),\n bytes(normalizeProofHash(input.seal, 'seal')),\n ]),\n );\n}\n\n/** Intake idempotency key over tenant, record type, entity, and the reported event (excludes seq and previousWord). */\nexport function computeIntakeIdempotencyKeyV1(\n tenantId: string,\n recordTypeId: string,\n entityId: string,\n reportedEvent: unknown,\n): string {\n return ethers.keccak256(\n ethers.concat([\n utf8(SLOT_DOMAINS_V1.intake),\n SEP,\n utf8(tenantId),\n SEP,\n utf8(recordTypeId),\n SEP,\n utf8(entityId),\n SEP,\n utf8(canonicalizeJcs(reportedEvent)),\n ]),\n );\n}\n\n// ----------------------------------------------------------------- records\n\nexport interface RecordReportV1 {\n /** Target lifecycle state by name. */\n lifecycle: string;\n /** Additional state field values (counters, quantities) applied only when the transition is applied. */\n fields?: StateFieldValues;\n /** Flag names to set. */\n flags?: string[];\n /** Sealed record content (validated against the layout's sealedRecordSchema by the caller). */\n content: Record<string, unknown>;\n}\n\nexport interface PreviousRecordV1 {\n seq: number;\n word: string | bigint;\n}\n\nexport type SlotRecordKind = 'transition' | 'attempt' | 'failure';\n\nexport interface BuiltSlotRecordV1 {\n layoutId: number;\n layoutVersion: number;\n layoutDigest: string;\n recordKey: string;\n seq: number;\n kind: SlotRecordKind;\n applied: boolean;\n ruleId: string | null;\n decodedState: DecodedState;\n state96: string;\n recordContent: Record<string, unknown>;\n recordBytes: string;\n recordHash: string;\n itemIndex: number;\n recordOpening: string;\n seal: string;\n sealTag: string;\n previousWord: string;\n newWord: string;\n itemHash: string;\n}\n\nexport interface BuildSlotRecordInputV1 {\n layout: RegisteredLayout;\n recordKey: string;\n previous: PreviousRecordV1 | null;\n report: RecordReportV1;\n batchSeed: string;\n itemIndex: number;\n kind?: 'transition' | 'failure';\n}\n\n/**\n * Build one record for a slot from the previous word, the report, and the\n * batch position. Rejects malformed input with a registered code; a\n * forbidden transition becomes an attempt record when the layout records\n * attempts, otherwise RECORD_TRANSITION_FORBIDDEN.\n */\nexport function buildSlotRecordV1(input: BuildSlotRecordInputV1): BuiltSlotRecordV1 {\n const plan = planSlotRecordV1(input);\n return sealSlotRecordV1(plan, computeRecordHashV1(plan.recordContent));\n}\n\n/** Everything of one slot record that precedes its record hash (record hash v2 plans once and hashes either way). */\nexport interface PlannedSlotRecordV1 {\n layout: RegisteredLayout;\n recordKey: string;\n seq: number;\n kind: SlotRecordKind;\n applied: boolean;\n ruleId: string | null;\n state96: bigint;\n recordContent: Record<string, unknown>;\n previousWord: bigint;\n itemIndex: number;\n batchSeed: string;\n}\n\n/** The first half of buildSlotRecordV1: validation, the transition rule, the content and state96. */\nexport function planSlotRecordV1(input: BuildSlotRecordInputV1): PlannedSlotRecordV1 {\n const { doc } = input.layout;\n const kind = input.kind ?? 'transition';\n const lifecycleField = doc.lifecycle.field;\n const recordKey = normalizeProofHash(input.recordKey, 'recordKey');\n\n let previousWord = 0n;\n let fromLifecycle: string | null = null;\n if (input.previous) {\n previousWord = BigInt(input.previous.word);\n const prevSplit = splitWordV1(previousWord);\n if (prevSplit.layoutId !== doc.layoutId || prevSplit.layoutVersion !== doc.layoutVersion) {\n throw new RecordIntakeError(\n 'RECORD_LAYOUT_MISMATCH',\n `previous word is layout ${prevSplit.layoutId}/${prevSplit.layoutVersion}, report targets ${doc.layoutId}/${doc.layoutVersion}`,\n );\n }\n const prevState = decodeStateV1(doc, prevSplit.state96);\n fromLifecycle = prevState[lifecycleField] as string;\n if (String(prevState.seq) !== String(input.previous.seq)) {\n throw new RecordIntakeError('RECORD_CONTENT_INVALID', `previous seq ${input.previous.seq} does not match the previous word`);\n }\n }\n\n let toLifecycle = input.report.lifecycle;\n const flags = [...(input.report.flags ?? [])];\n let content: Record<string, unknown> = { ...input.report.content };\n let applied = true;\n let ruleId: string | null = null;\n\n if (!input.previous) {\n if (!doc.lifecycle.genesis.includes(toLifecycle)) {\n throw new RecordIntakeError('RECORD_GENESIS_MISMATCH', `${toLifecycle} is not a genesis state of ${doc.name}`);\n }\n } else if (kind === 'failure') {\n toLifecycle = fromLifecycle as string;\n flags.push(FLAG_DELIVERY_FAILED);\n } else if (!isTransitionAllowedV1(doc, fromLifecycle as string, toLifecycle)) {\n if (!doc.recordAttempts) {\n throw new RecordIntakeError('RECORD_TRANSITION_FORBIDDEN', `${fromLifecycle} -> ${toLifecycle} is not in the ${doc.name} table`);\n }\n applied = false;\n ruleId = `${doc.name}#transitions.${fromLifecycle}`;\n content = { ...content, attemptedTarget: toLifecycle, ruleId };\n toLifecycle = fromLifecycle as string;\n flags.push(FLAG_TRANSITION_NOT_APPLIED);\n }\n\n validatePayloadRefsInContent(content);\n\n const seq = input.previous ? input.previous.seq + 1 : 0;\n const values: StateFieldValues = {\n layoutId: doc.layoutId,\n layoutVersion: doc.layoutVersion,\n [lifecycleField]: toLifecycle,\n flags,\n seq,\n ...(applied ? input.report.fields ?? {} : {}),\n };\n const state96 = packStateV1(doc, values);\n return {\n layout: input.layout,\n recordKey,\n seq,\n kind: applied ? kind : 'attempt',\n applied,\n ruleId,\n state96,\n recordContent: content,\n previousWord,\n itemIndex: input.itemIndex,\n batchSeed: input.batchSeed,\n };\n}\n\n/** The second half of buildSlotRecordV1: the opening, the seal, the word and the item hash, from a record hash. */\n/** Seals a planned record. The seal is over sealInputHash(sealedVersion, recordHash); the row keeps the raw hash. */\nexport function sealSlotRecordV1(plan: PlannedSlotRecordV1, recordHash: string, sealedVersion: SealedRecordHashVersion = 1): BuiltSlotRecordV1 {\n const { doc, digest } = plan.layout;\n const { recordKey, seq, state96, previousWord } = plan;\n const content = plan.recordContent;\n const recordOpening = deriveRecordOpeningV1(plan.batchSeed, plan.itemIndex, recordKey);\n const seal = computeSealV1({\n layoutId: doc.layoutId,\n layoutVersion: doc.layoutVersion,\n layoutDigest: digest,\n state96,\n recordHash: sealInputHash(sealedVersion, recordHash),\n recordOpening,\n });\n const newWord = composeWordV1(state96, seal);\n const itemHash = computeSlotItemHashV1({ recordKey, seq, previousWord, newWord, seal });\n\n return {\n layoutId: doc.layoutId,\n layoutVersion: doc.layoutVersion,\n layoutDigest: digest,\n recordKey,\n seq,\n kind: plan.kind,\n applied: plan.applied,\n ruleId: plan.ruleId,\n decodedState: decodeStateV1(doc, state96),\n state96: hex96(state96),\n recordContent: content,\n recordBytes: canonicalizeJcs(content),\n recordHash,\n itemIndex: plan.itemIndex,\n recordOpening,\n seal,\n sealTag: sealTagOfV1(seal),\n previousWord: hex256(previousWord),\n newWord: hex256(newWord),\n itemHash,\n };\n}\n\n// ----------------------------------------------------------------- batches\n\nexport interface CommittedSlotItemV1 extends BuiltSlotRecordV1 {\n itemOpening: string;\n publishedLeaf: string;\n merkleProof: string[];\n}\n\nexport interface SlotBatchCommitV1 {\n batchId: number;\n itemCount: number;\n merkleRoot: string;\n previousHead: string;\n ledgerHead: string;\n calldata: string;\n items: CommittedSlotItemV1[];\n}\n\nconst writeIface = new ethers.Interface([`function ${WRITE_RECORD_BATCH_SIGNATURE_V1} returns (uint256)`]);\nexport const WRITE_RECORD_BATCH_SELECTOR_V1 = writeIface.getFunction('writeRecordBatchAndCommit')!.selector;\n\nexport function encodeWriteRecordBatchCalldataV1(\n records: Array<Pick<BuiltSlotRecordV1, 'recordKey' | 'previousWord' | 'newWord'>>,\n merkleRoot: string,\n): string {\n return writeIface.encodeFunctionData('writeRecordBatchAndCommit', [\n records.map((r) => r.recordKey),\n records.map((r) => BigInt(r.previousWord)),\n records.map((r) => BigInt(r.newWord)),\n SLOT_ENCODING_VERSION_V1,\n normalizeProofHash(merkleRoot, 'merkleRoot'),\n records.length,\n ]);\n}\n\nexport interface DecodedWriteRecordBatchCalldataV1 {\n selector: string;\n functionSignature: string;\n recordKeys: string[];\n expectedWords: string[];\n newWords: string[];\n encodingVersion: number;\n merkleRoot: string;\n itemCount: number;\n}\n\nexport function decodeWriteRecordBatchCalldataV1(calldata: string): DecodedWriteRecordBatchCalldataV1 {\n const data = ethers.hexlify(ethers.getBytes(calldata));\n if (!data.startsWith(WRITE_RECORD_BATCH_SELECTOR_V1)) {\n throw new RecordIntakeError('RECORD_CONTENT_INVALID', 'calldata selector is not writeRecordBatchAndCommit');\n }\n const decoded = writeIface.decodeFunctionData('writeRecordBatchAndCommit', data);\n return {\n selector: WRITE_RECORD_BATCH_SELECTOR_V1,\n functionSignature: WRITE_RECORD_BATCH_SIGNATURE_V1,\n recordKeys: Array.from(decoded[0] as string[], (k) => k.toLowerCase()),\n expectedWords: Array.from(decoded[1] as bigint[], (w) => hex256(w)),\n newWords: Array.from(decoded[2] as bigint[], (w) => hex256(w)),\n encodingVersion: Number(decoded[3]),\n merkleRoot: String(decoded[4]).toLowerCase(),\n itemCount: Number(decoded[5]),\n };\n}\n\n/**\n * Commit a batch of built records (CAS order = array order): hiding\n * commitments over the item hashes, pair-sorted root, ledger head, calldata.\n */\nexport function commitSlotBatchV1(\n records: BuiltSlotRecordV1[],\n batchSeed: string,\n batchId: number,\n previousHead: string,\n): SlotBatchCommitV1 {\n if (records.length === 0) throw new RecordIntakeError('RECORD_CONTENT_INVALID', 'a batch needs at least one record');\n for (let i = 0; i < records.length; i += 1) {\n if (records[i].itemIndex !== i) {\n throw new RecordIntakeError('RECORD_CONTENT_INVALID', `record ${i} was built for item index ${records[i].itemIndex}`);\n }\n }\n const commitments = buildHidingCommitmentsV1(batchSeed, records.map((r) => r.itemHash));\n const merkleRoot = commitments.publishedRoot;\n const ledgerHead = nextLedgerHeadV1(previousHead, merkleRoot, batchId);\n const items: CommittedSlotItemV1[] = records.map((r, i) => ({\n ...r,\n itemIndex: i,\n itemOpening: commitments.itemOpenings[i],\n publishedLeaf: commitments.publishedLeaves[i],\n merkleProof: buildMerkleProofV2(commitments.publishedLeaves, i),\n }));\n return {\n batchId,\n itemCount: records.length,\n merkleRoot,\n previousHead: normalizeProofHash(previousHead, 'previousHead'),\n ledgerHead,\n calldata: encodeWriteRecordBatchCalldataV1(records, merkleRoot),\n items,\n };\n}\n\nexport interface SlotBatchCommitmentsV1 {\n itemCount: number;\n merkleRoot: string;\n calldata: string;\n items: CommittedSlotItemV1[];\n}\n\n/**\n * Commit a batch whose records were built under per-record seeds (one\n * intake anchor, one sealed seed; several anchors in one transaction). The\n * openings are derived record by record from that record's own seed, the\n * published leaves are position-bound exactly as in `commitSlotBatchV1`,\n * and the root is the same pair-sorted construction, so a receipt verifies\n * identically: the verifier receives openings, never seeds. With one seed\n * repeated for every record the output equals `commitSlotBatchV1` minus the\n * ledger fields, which the writer takes from the `LedgerHeadAdvanced` event\n * of the transaction that actually landed.\n */\nexport function commitSlotBatchWithSeedsV1(records: BuiltSlotRecordV1[], seeds: string[]): SlotBatchCommitmentsV1 {\n if (records.length === 0) throw new RecordIntakeError('RECORD_CONTENT_INVALID', 'a batch needs at least one record');\n if (seeds.length !== records.length) {\n throw new RecordIntakeError('RECORD_CONTENT_INVALID', `expected ${records.length} seeds, got ${seeds.length}`);\n }\n for (let i = 0; i < records.length; i += 1) {\n if (records[i].itemIndex !== i) {\n throw new RecordIntakeError('RECORD_CONTENT_INVALID', `record ${i} was built for item index ${records[i].itemIndex}`);\n }\n }\n const itemOpenings = records.map((r, i) => deriveItemOpeningV1(seeds[i], i, r.itemHash));\n const publishedLeaves = records.map((r, i) => computePublishedLeafV1(i, r.itemHash, itemOpenings[i]));\n const merkleRoot = computeMerkleItemsRootV2(publishedLeaves);\n const items: CommittedSlotItemV1[] = records.map((r, i) => ({\n ...r,\n itemIndex: i,\n itemOpening: itemOpenings[i],\n publishedLeaf: publishedLeaves[i],\n merkleProof: buildMerkleProofV2(publishedLeaves, i),\n }));\n return {\n itemCount: records.length,\n merkleRoot,\n calldata: encodeWriteRecordBatchCalldataV1(records, merkleRoot),\n items,\n };\n}\n\n// ----------------------------------------------------------------- rules\n\nexport interface TransitionRuleCheckV1 {\n ok: boolean;\n from: string | null;\n to: string;\n flags: string[];\n reason: string;\n}\n\n/**\n * Recompute the transition rule for a record from its previous and new words\n * under the layout table. A receipt that claims `transition_not_applied` for\n * a permitted move, or an applied move the table forbids, fails here.\n */\nexport function checkTransitionRuleV1(\n doc: LayoutDocumentV1,\n input: { previousWord: string | bigint; newWord: string | bigint; recordContent?: Record<string, unknown> },\n): TransitionRuleCheckV1 {\n const lifecycleField = doc.lifecycle.field;\n const next = decodeStateV1(doc, splitWordV1(input.newWord).state96);\n const to = next[lifecycleField] as string;\n const flags = (next.flags as string[]) ?? [];\n const prevWord = BigInt(input.previousWord);\n if (prevWord === 0n) {\n if (!doc.lifecycle.genesis.includes(to)) {\n return { ok: false, from: null, to, flags, reason: `${to} is not a genesis state` };\n }\n if (flags.includes(FLAG_TRANSITION_NOT_APPLIED) || flags.includes(FLAG_DELIVERY_FAILED)) {\n return { ok: false, from: null, to, flags, reason: 'a genesis record cannot carry attempt or failure flags' };\n }\n return { ok: true, from: null, to, flags, reason: 'genesis state is in the layout genesis list' };\n }\n const prev = decodeStateV1(doc, splitWordV1(prevWord).state96);\n const from = prev[lifecycleField] as string;\n if (flags.includes(FLAG_TRANSITION_NOT_APPLIED)) {\n if (!doc.recordAttempts) return { ok: false, from, to, flags, reason: `${doc.name} does not record attempts` };\n if (to !== from) return { ok: false, from, to, flags, reason: 'an attempt record must keep the lifecycle unchanged' };\n const attempted = input.recordContent?.attemptedTarget;\n if (typeof attempted !== 'string') {\n return { ok: false, from, to, flags, reason: 'an attempt record must carry attemptedTarget in the sealed record' };\n }\n if (isTransitionAllowedV1(doc, from, attempted)) {\n return { ok: false, from, to, flags, reason: `${from} -> ${attempted} is permitted by the table; it cannot be recorded as not applied` };\n }\n return { ok: true, from, to, flags, reason: `${from} -> ${attempted} is forbidden by the table and was recorded as not applied` };\n }\n if (flags.includes(FLAG_DELIVERY_FAILED)) {\n if (to !== from) return { ok: false, from, to, flags, reason: 'a failure record must keep the lifecycle unchanged' };\n return { ok: true, from, to, flags, reason: 'failure record keeps the lifecycle' };\n }\n if (!isTransitionAllowedV1(doc, from, to)) {\n return { ok: false, from, to, flags, reason: `${from} -> ${to} is forbidden by the table but the record claims it was applied` };\n }\n return { ok: true, from, to, flags, reason: `${from} -> ${to} is permitted by the table` };\n}\n", "import { ethers } from 'ethers';\nimport { normalizeProofHash } from './merkle-v2';\n\n/**\n * Ledger head (ADR 0012 section 3; slot-encoding-v1 section 13).\n *\n * newHead = keccak256(abi.encode(previousHead, merkleRoot, batchId))\n *\n * One head per tenant contract, advanced on every batch commit on either lane\n * in the frame that stores the root, and emitted as\n * `LedgerHeadAdvanced(batchId, merkleRoot, previousHead, newHead)`.\n */\n\nexport interface LedgerBatchRef {\n batchId: number | bigint | string;\n merkleRoot: string;\n}\n\nexport function nextLedgerHeadV1(previousHead: string, merkleRoot: string, batchId: number | bigint | string): string {\n const prev = normalizeProofHash(previousHead, 'previousHead');\n const root = normalizeProofHash(merkleRoot, 'merkleRoot');\n return ethers.keccak256(\n ethers.AbiCoder.defaultAbiCoder().encode(['bytes32', 'bytes32', 'uint256'], [prev, root, BigInt(batchId)]),\n );\n}\n\n/** Heads after each batch, starting with the genesis head at index 0. */\nexport function recomputeLedgerHeadsV1(genesisHead: string, batches: LedgerBatchRef[]): string[] {\n const heads = [normalizeProofHash(genesisHead, 'genesisHead')];\n for (const b of batches) heads.push(nextLedgerHeadV1(heads[heads.length - 1], b.merkleRoot, b.batchId));\n return heads;\n}\n\nexport interface LedgerChainCheck {\n verified: boolean;\n recomputedHead: string;\n passesThrough: boolean;\n endsAtExpected: boolean;\n reason: string;\n}\n\n/**\n * Verify that a receipt's (batchId, proofRoot) sits in a ledger described by\n * its batches from genesis, and that the recomputed chain ends at the head\n * read from the contract.\n */\nexport function verifyLedgerChainV1(input: {\n genesisHead: string;\n batches: LedgerBatchRef[];\n expectedHead: string;\n receipt: { batchId: number | bigint | string; proofRoot: string };\n}): LedgerChainCheck {\n const heads = recomputeLedgerHeadsV1(input.genesisHead, input.batches);\n const recomputedHead = heads[heads.length - 1];\n const endsAtExpected = recomputedHead === normalizeProofHash(input.expectedHead, 'expectedHead');\n const wantId = BigInt(input.receipt.batchId);\n const wantRoot = normalizeProofHash(input.receipt.proofRoot, 'proofRoot');\n const passesThrough = input.batches.some(\n (b) => BigInt(b.batchId) === wantId && normalizeProofHash(b.merkleRoot, 'merkleRoot') === wantRoot,\n );\n const verified = endsAtExpected && passesThrough;\n return {\n verified,\n recomputedHead,\n passesThrough,\n endsAtExpected,\n reason: verified\n ? 'The batch sits unaltered in the ledger and the chain ends at the current head.'\n : !passesThrough\n ? 'No batch on the chain carries this receipt batch id and root.'\n : 'The recomputed head chain does not end at the head read from the contract.',\n };\n}\n", "import { verifyHiddenItemProofV1 } from '../proof/hiding-commitment-v1';\nimport { canonicalizeJcs } from '../proof/jcs';\nimport type { RecordReceipt } from '../proof/semantic-receipt-v3';\nimport { sealInputHash } from '../proof/seal-input';\nimport { computeRecordHashV1, computeSealV1, computeSlotItemHashV1, sealTagOfV1, splitWordV1 } from '../proof/slot-encoding-v1';\nimport { concatBytes, isHex32, sha256, toHex0x, utf8 } from './platform-crypto';\nimport {\n RECORD_LEAVES_MAX_V2,\n openRecordEntryV2,\n parsePointerV2,\n recordLeavesV2,\n type RecordLeafV2,\n type RevealedLeafV2,\n} from './record-hash-v2';\nimport { openRecordEntryV3, parsePointerV3, validateRecordItemsV3, type RecordItemV3 } from './record-hash-v3';\n\n/**\n * record-disclosure/v1 (ADR 0016; record-hash-v2.md): chosen entries of one\n * record, each with the fields its owner chose to show. A reader checks each\n * shown field against the entry's leaves, the leaves against the seal, and\n * the seal's item through its Merkle path to a batch root the reader read\n * from the chain itself. The verifier returns a result and never throws.\n *\n * record-disclosure/v2 (card 10, F1) is the same for a record hash v3\n * record: each entry carries the v3 items, the seal is over\n * sealInputHash(3, hash), and the digest has its own label. The form says\n * which a record needs: a form marked `recordHashVersion: 3` takes only v2,\n * and any other form only v1 (RECORD_HASH_VERSION_MISMATCH).\n */\nexport const RECORD_DISCLOSURE_SCHEMA_V1 = 'record-disclosure/v1' as const;\nexport const RECORD_DISCLOSURE_SCHEMA_V2 = 'record-disclosure/v2' as const;\nexport const RECORD_DISCLOSURE_MAX_BYTES_V1 = 1048576;\n\nexport type RecordDisclosureEntryV1 =\n | { seq: number; recordOpening: string; leaves: string[]; revealed: RevealedLeafV2[] }\n | { seq: number; recordOpening: string; recordContent: Record<string, unknown> };\n\nexport interface RecordDisclosureV1 {\n schema: typeof RECORD_DISCLOSURE_SCHEMA_V1;\n recordKey: string;\n chain: { chainId: number; contractAddress: string };\n layout: { layoutId: number; layoutVersion: number; layoutDigest: string };\n recordHashVersion: 1 | 2;\n entries: RecordDisclosureEntryV1[];\n digest: string;\n}\n\nexport interface RecordDisclosureEntryV2 {\n seq: number;\n recordOpening: string;\n items: RecordItemV3[];\n revealed: RevealedLeafV2[];\n}\n\nexport interface RecordDisclosureV2 {\n schema: typeof RECORD_DISCLOSURE_SCHEMA_V2;\n recordKey: string;\n chain: { chainId: number; contractAddress: string };\n layout: { layoutId: number; layoutVersion: number; layoutDigest: string };\n recordHashVersion: 3;\n entries: RecordDisclosureEntryV2[];\n digest: string;\n}\n\nexport type RecordDisclosure = RecordDisclosureV1 | RecordDisclosureV2;\n\n/** A receipt of a v3 record with its full copy: a served v6 receipt, or a v5 receipt opened in the holder's browser. */\nexport interface RecordReceiptV3Items {\n schema: 'semantic-receipt/v6';\n recordKey: string;\n seq: number;\n recordOpening: string;\n items: RecordItemV3[];\n revealed: RevealedLeafV2[];\n}\n\nexport interface SealHistoryEntryForDisclosureV1 {\n seq: number;\n previousWord: string;\n newWord: string;\n recordHash?: string;\n itemIndex: number;\n itemOpening: string;\n merkleProof: string[];\n batchId: number;\n}\n\nexport interface SealHistoryFormForDisclosureV1 {\n recordKey: string;\n chain: { chainId: number; contractAddress: string };\n layout: { layoutId: number; layoutVersion: number; layoutDigest: string };\n /** Present, and 3, only for a record hash v3 record. */\n recordHashVersion?: 3;\n entries: SealHistoryEntryForDisclosureV1[];\n}\n\n/** Batch roots the caller read from the chain itself, by batchId in decimal. Never a root PacSpace served. */\nexport type ChainBatchRootsV1 = Readonly<Record<string, string>>;\n\nexport type RecordDisclosureRefusalV1 =\n | 'DISCLOSURE_MALFORMED'\n | 'DISCLOSURE_TOO_LARGE'\n | 'DISCLOSURE_DIGEST_MISMATCH'\n | 'DISCLOSURE_RECORD_MISMATCH'\n | 'DISCLOSURE_ENTRY_NOT_IN_HISTORY'\n | 'DISCLOSURE_LEAF_MISMATCH'\n | 'DISCLOSURE_SEAL_MISMATCH'\n | 'DISCLOSURE_CHAIN_ROOT_MISSING'\n | 'RECORD_HASH_VERSION_MISMATCH';\n\nexport type RecordDisclosureVerificationV1 =\n | {\n ok: true;\n recordHashVersion: 1 | 2 | 3;\n entries: Array<{ seq: number; batchId: number; fields: RecordLeafV2[]; withheld: number; content: Record<string, unknown> | null }>;\n }\n | { ok: false; code: RecordDisclosureRefusalV1; seq: number | null; reason: string };\n\nconst REASONS = {\n DISCLOSURE_MALFORMED: () => 'This is not a record disclosure this version can read.',\n DISCLOSURE_TOO_LARGE: () => 'This disclosure is larger than 1 MiB, the most one disclosure may hold.',\n DISCLOSURE_DIGEST_MISMATCH: () => 'This disclosure was changed after it was made: its digest does not match its contents.',\n DISCLOSURE_RECORD_MISMATCH: () => 'This disclosure is for a different record than the history it was checked against.',\n DISCLOSURE_ENTRY_NOT_IN_HISTORY: (n: number) => `Entry ${n} of this disclosure is not in the record's sealed history.`,\n DISCLOSURE_LEAF_MISMATCH: (n: number) => `A shown field of entry ${n} does not match the fields sealed for that entry.`,\n DISCLOSURE_SEAL_MISMATCH: (n: number) => `Entry ${n} of this disclosure does not reproduce the seal recorded on the ledger for it.`,\n DISCLOSURE_CHAIN_ROOT_MISSING: (n: number) =>\n `Entry ${n} could not be checked: the ledger's record of its batch was not available. Try again.`,\n RECORD_HASH_VERSION_MISMATCH: () => \"This shared record's format doesn't match the record on the ledger.\",\n} as const;\nconst RECORD_HASH_MISMATCH = (n: number) => `Entry ${n} of this disclosure does not match the record hash in the record's sealed history.`;\n\n/** Thrown by the builder and the encryption; its message is the refusal's fixed sentence. */\nexport class RecordDisclosureError extends Error {\n constructor(readonly code: 'DISCLOSURE_MALFORMED' | 'DISCLOSURE_TOO_LARGE') {\n super(REASONS[code]());\n this.name = 'RecordDisclosureError';\n }\n}\n\nconst DIGEST_LABEL = 'pacspace:record-disclosure-digest:v1';\nconst DIGEST_LABEL_V2 = 'pacspace:record-disclosure-digest:v2';\nconst ADDRESS = /^0x[0-9a-f]{40}$/;\nconst ZERO32 = '0x' + '0'.repeat(64);\nconst UINT32_MAX = 4294967295;\nconst LONE_SURROGATE = /[\\ud800-\\udbff](?![\\udc00-\\udfff])|(?<![\\ud800-\\udbff])[\\udc00-\\udfff]/;\n\nfunction hasLoneSurrogate(value: unknown): boolean {\n if (typeof value === 'string') return LONE_SURROGATE.test(value);\n if (Array.isArray(value)) return value.some(hasLoneSurrogate);\n if (value && typeof value === 'object') {\n return Object.entries(value).some(([k, v]) => LONE_SURROGATE.test(k) || hasLoneSurrogate(v));\n }\n return false;\n}\n\nconst isPlainObject = (v: unknown): v is Record<string, unknown> =>\n !!v && typeof v === 'object' && !Array.isArray(v) && Object.getPrototypeOf(v) === Object.prototype;\nconst hasExactly = (v: Record<string, unknown>, keys: readonly string[]) => {\n const own = Object.keys(v);\n return own.length === keys.length && keys.every((k) => Object.prototype.hasOwnProperty.call(v, k));\n};\nconst isUint32 = (v: unknown): v is number => Number.isInteger(v) && (v as number) >= 0 && (v as number) <= UINT32_MAX;\nconst isSafeNatural = (v: unknown): v is number => Number.isSafeInteger(v) && (v as number) >= 0;\n\nasync function digestUnder(label: string, disclosure: object): Promise<string> {\n const rest: Record<string, unknown> = { ...disclosure };\n delete rest.digest;\n return toHex0x(await sha256(concatBytes(utf8(label), new Uint8Array([0]), utf8(canonicalizeJcs(rest)))));\n}\n\n/** SHA-256(\"pacspace:record-disclosure-digest:v1\" || 0x00 || utf8(JCS(disclosure without \"digest\"))). */\nexport async function computeRecordDisclosureDigestV1(disclosure: Omit<RecordDisclosureV1, 'digest'> & { digest?: string }): Promise<string> {\n return digestUnder(DIGEST_LABEL, disclosure);\n}\n\n/** SHA-256(\"pacspace:record-disclosure-digest:v2\" || 0x00 || utf8(JCS(disclosure without \"digest\"))). */\nexport async function computeRecordDisclosureDigestV2(disclosure: Omit<RecordDisclosureV2, 'digest'> & { digest?: string }): Promise<string> {\n return digestUnder(DIGEST_LABEL_V2, disclosure);\n}\n\n/** A disclosure's digest under its own schema's label. */\nexport function computeRecordDisclosureDigest(disclosure: Omit<RecordDisclosure, 'digest'> & { digest?: string }): Promise<string> {\n return disclosure.schema === RECORD_DISCLOSURE_SCHEMA_V2 ? digestUnder(DIGEST_LABEL_V2, disclosure) : digestUnder(DIGEST_LABEL, disclosure);\n}\n\nfunction chainShapeOk(chain: unknown, exact: boolean): chain is { chainId: number; contractAddress: string } {\n return (\n isPlainObject(chain) &&\n (!exact || hasExactly(chain, ['chainId', 'contractAddress'])) &&\n isSafeNatural(chain.chainId) &&\n typeof chain.contractAddress === 'string' &&\n ADDRESS.test(chain.contractAddress)\n );\n}\n\nfunction layoutShapeOk(layout: unknown, exact: boolean): layout is { layoutId: number; layoutVersion: number; layoutDigest: string } {\n return (\n isPlainObject(layout) &&\n (!exact || hasExactly(layout, ['layoutId', 'layoutVersion', 'layoutDigest'])) &&\n isSafeNatural(layout.layoutId) &&\n isSafeNatural(layout.layoutVersion) &&\n isHex32(layout.layoutDigest)\n );\n}\n\nfunction revealedShapeOk(revealed: unknown, leafCount: number, parsePointer: (p: string) => unknown = parsePointerV2): boolean {\n if (!Array.isArray(revealed) || revealed.length > leafCount) return false;\n for (let i = 0; i < revealed.length; i += 1) {\n const leaf = revealed[i];\n if (!isPlainObject(leaf) || !hasExactly(leaf, ['pointer', 'value', 'salt'])) return false;\n if (typeof leaf.pointer !== 'string' || !parsePointer(leaf.pointer) || !isHex32(leaf.salt)) return false;\n if (hasLoneSurrogate(leaf.value)) return false;\n if (i > 0 && !((revealed[i - 1] as RevealedLeafV2).pointer < leaf.pointer)) return false;\n }\n return true;\n}\n\nfunction entryShapeOk(entry: unknown, version: 1 | 2 | 3): boolean {\n if (!isPlainObject(entry) || !isUint32(entry.seq) || !isHex32(entry.recordOpening)) return false;\n if (version === 3) {\n return (\n hasExactly(entry, ['seq', 'recordOpening', 'items', 'revealed']) &&\n validateRecordItemsV3(entry.items) &&\n revealedShapeOk(entry.revealed, (entry.items as RecordItemV3[]).length, parsePointerV3)\n );\n }\n if (version === 1) {\n return hasExactly(entry, ['seq', 'recordOpening', 'recordContent']) && isPlainObject(entry.recordContent) && !hasLoneSurrogate(entry.recordContent);\n }\n if (!hasExactly(entry, ['seq', 'recordOpening', 'leaves', 'revealed'])) return false;\n const leaves = entry.leaves;\n if (!Array.isArray(leaves) || leaves.length > RECORD_LEAVES_MAX_V2) return false;\n for (let i = 0; i < leaves.length; i += 1) {\n if (!isHex32(leaves[i]) || (i > 0 && !(leaves[i - 1] < leaves[i]))) return false;\n }\n return revealedShapeOk(entry.revealed, leaves.length);\n}\n\nfunction disclosureShapeOk(d: Record<string, unknown>): d is Record<string, unknown> & RecordDisclosure {\n if (!hasExactly(d, ['schema', 'recordKey', 'chain', 'layout', 'recordHashVersion', 'entries', 'digest'])) return false;\n if (!isHex32(d.recordKey) || !isHex32(d.digest)) return false;\n if (!chainShapeOk(d.chain, true) || !layoutShapeOk(d.layout, true)) return false;\n if (d.schema === RECORD_DISCLOSURE_SCHEMA_V2 ? d.recordHashVersion !== 3 : d.recordHashVersion !== 1 && d.recordHashVersion !== 2) return false;\n const entries = d.entries;\n if (!Array.isArray(entries) || entries.length === 0) return false;\n for (let i = 0; i < entries.length; i += 1) {\n if (!entryShapeOk(entries[i], d.recordHashVersion as 1 | 2 | 3)) return false;\n if (i > 0 && !(entries[i - 1].seq < entries[i].seq)) return false;\n }\n return true;\n}\n\nfunction formShapeOk(form: unknown): form is SealHistoryFormForDisclosureV1 {\n if (!isPlainObject(form) || !isHex32(form.recordKey)) return false;\n if (form.recordHashVersion !== undefined && form.recordHashVersion !== 3) return false;\n if (!chainShapeOk(form.chain, false) || !layoutShapeOk(form.layout, false)) return false;\n const entries = form.entries;\n if (!Array.isArray(entries)) return false;\n for (let i = 0; i < entries.length; i += 1) {\n const e = entries[i];\n if (!isPlainObject(e) || !isUint32(e.seq) || !isUint32(e.itemIndex) || !isSafeNatural(e.batchId)) return false;\n if (!isHex32(e.previousWord) || !isHex32(e.newWord) || !isHex32(e.itemOpening)) return false;\n if (e.recordHash !== undefined && !isHex32(e.recordHash)) return false;\n if (!Array.isArray(e.merkleProof) || e.merkleProof.length > 32 || !e.merkleProof.every(isHex32)) return false;\n if (i > 0 && !((entries[i - 1] as SealHistoryEntryForDisclosureV1).seq < e.seq)) return false;\n }\n return true;\n}\n\nfunction refuse(code: RecordDisclosureRefusalV1, seq: number | null, reason?: string): RecordDisclosureVerificationV1 {\n const n = seq === null ? 0 : seq + 1;\n return { ok: false, code, seq, reason: reason ?? REASONS[code](n) };\n}\n\n/** Section 6's algorithm, in order, stopping at the first refusal. Trusts only `chainRoots`. */\nexport async function verifyRecordDisclosureV1(input: {\n form: SealHistoryFormForDisclosureV1;\n chainRoots: ChainBatchRootsV1;\n disclosure: unknown;\n}): Promise<RecordDisclosureVerificationV1> {\n try {\n return await verifyDisclosure(input);\n } catch {\n return refuse('DISCLOSURE_MALFORMED', null);\n }\n}\n\nasync function verifyDisclosure(input: {\n form: SealHistoryFormForDisclosureV1;\n chainRoots: ChainBatchRootsV1;\n disclosure: unknown;\n}): Promise<RecordDisclosureVerificationV1> {\n const d = input?.disclosure;\n if (!isPlainObject(d) || (d.schema !== RECORD_DISCLOSURE_SCHEMA_V1 && d.schema !== RECORD_DISCLOSURE_SCHEMA_V2)) {\n return refuse('DISCLOSURE_MALFORMED', null);\n }\n\n let canonical: string;\n try {\n canonical = canonicalizeJcs(d);\n } catch {\n return refuse('DISCLOSURE_MALFORMED', null);\n }\n if (utf8(canonical).length > RECORD_DISCLOSURE_MAX_BYTES_V1) return refuse('DISCLOSURE_TOO_LARGE', null);\n\n const form = input.form;\n if (!disclosureShapeOk(d) || !formShapeOk(form)) return refuse('DISCLOSURE_MALFORMED', null);\n\n if ((await computeRecordDisclosureDigest(d)) !== d.digest) return refuse('DISCLOSURE_DIGEST_MISMATCH', null);\n\n if (\n d.recordKey !== form.recordKey ||\n d.chain.chainId !== form.chain.chainId ||\n d.chain.contractAddress !== form.chain.contractAddress ||\n d.layout.layoutId !== form.layout.layoutId ||\n d.layout.layoutVersion !== form.layout.layoutVersion ||\n d.layout.layoutDigest !== form.layout.layoutDigest\n ) {\n return refuse('DISCLOSURE_RECORD_MISMATCH', null);\n }\n if ((form.recordHashVersion === 3) !== (d.schema === RECORD_DISCLOSURE_SCHEMA_V2)) {\n return refuse('RECORD_HASH_VERSION_MISMATCH', null);\n }\n const sealedVersion = d.recordHashVersion;\n\n const bySeq = new Map(form.entries.map((e) => [e.seq, e] as const));\n const roots: Record<string, unknown> = isPlainObject(input.chainRoots) ? input.chainRoots : {};\n const out: Extract<RecordDisclosureVerificationV1, { ok: true }>['entries'] = [];\n for (const entry of d.entries) {\n const seq = entry.seq;\n const formEntry = bySeq.get(seq);\n if (!formEntry) return refuse('DISCLOSURE_ENTRY_NOT_IN_HISTORY', seq);\n\n let recordHash: string;\n let fields: RecordLeafV2[];\n let withheld: number;\n let content: Record<string, unknown> | null;\n if ('items' in entry) {\n const opened = await openRecordEntryV3(entry, { every: false });\n if (!opened.ok) return refuse(opened.failure === 'leaf-mismatch' ? 'DISCLOSURE_LEAF_MISMATCH' : 'DISCLOSURE_MALFORMED', seq);\n ({ recordHash, fields, withheld, content } = opened);\n } else if ('leaves' in entry) {\n const opened = await openRecordEntryV2(entry, { every: false });\n if (!opened.ok) return refuse(opened.failure === 'leaf-mismatch' ? 'DISCLOSURE_LEAF_MISMATCH' : 'DISCLOSURE_MALFORMED', seq);\n ({ recordHash, fields, withheld, content } = opened);\n } else {\n try {\n recordHash = computeRecordHashV1(entry.recordContent);\n fields = recordLeavesV2(entry.recordContent);\n } catch {\n return refuse('DISCLOSURE_MALFORMED', seq);\n }\n withheld = 0;\n content = entry.recordContent;\n }\n\n if (formEntry.recordHash !== undefined && formEntry.recordHash !== recordHash) {\n return refuse('DISCLOSURE_SEAL_MISMATCH', seq, RECORD_HASH_MISMATCH(seq + 1));\n }\n\n const newWord = BigInt(formEntry.newWord);\n const split = splitWordV1(newWord);\n const seal = computeSealV1({\n layoutId: d.layout.layoutId,\n layoutVersion: d.layout.layoutVersion,\n layoutDigest: d.layout.layoutDigest,\n state96: split.state96,\n recordHash: sealInputHash(sealedVersion, recordHash),\n recordOpening: entry.recordOpening,\n });\n if (sealTagOfV1(seal) !== split.sealTag) return refuse('DISCLOSURE_SEAL_MISMATCH', seq);\n\n const root = roots[String(formEntry.batchId)];\n if (!isHex32(root) || root === ZERO32) return refuse('DISCLOSURE_CHAIN_ROOT_MISSING', seq);\n\n const itemHash = computeSlotItemHashV1({\n recordKey: d.recordKey,\n seq,\n previousWord: BigInt(formEntry.previousWord),\n newWord,\n seal,\n });\n let included = false;\n try {\n included = verifyHiddenItemProofV1({\n itemHash,\n itemIndex: formEntry.itemIndex,\n itemOpening: formEntry.itemOpening,\n proof: formEntry.merkleProof,\n expectedRoot: root,\n });\n } catch {\n included = false;\n }\n if (!included) return refuse('DISCLOSURE_SEAL_MISMATCH', seq);\n out.push({ seq, batchId: formEntry.batchId, fields, withheld, content });\n }\n return { ok: true, recordHashVersion: d.recordHashVersion, entries: out };\n}\n\n/** The leaves of a full copy that a disclosure shows: all of them, or the listed pointers, each of which must be there. */\nfunction chosenLeaves(revealed: readonly RevealedLeafV2[], reveal: 'all' | string[]): RevealedLeafV2[] | null {\n const copy = (l: RevealedLeafV2) => ({ pointer: l.pointer, value: l.value, salt: l.salt });\n if (reveal === 'all') return revealed.map(copy);\n if (!Array.isArray(reveal) || new Set(reveal).size !== reveal.length) return null;\n const known = new Set(revealed.map((l) => l.pointer));\n if (reveal.some((p) => !known.has(p))) return null;\n const wanted = new Set(reveal);\n return revealed.filter((l) => wanted.has(l.pointer)).map(copy);\n}\n\n/**\n * Builds a disclosure from receipts the caller holds (a tenant's receipts or\n * a served bundle's). A semantic-receipt/v3 entry shows the listed fields; a\n * semantic-receipt/v2 entry is shown whole. Receipts of a v3 record (v6, or\n * a v5 opened into v6's shape) build a record-disclosure/v2. It never needs\n * a salt key.\n */\nexport async function buildRecordDisclosureV1(input: {\n recordKey: string;\n chain: { chainId: number; contractAddress: string };\n layout: { layoutId: number; layoutVersion: number; layoutDigest: string };\n entries: Array<{ receipt: RecordReceipt; reveal: 'all' | string[] }>;\n}): Promise<RecordDisclosureV1>;\nexport async function buildRecordDisclosureV1(input: {\n recordKey: string;\n chain: { chainId: number; contractAddress: string };\n layout: { layoutId: number; layoutVersion: number; layoutDigest: string };\n entries: Array<{ receipt: RecordReceiptV3Items; reveal: 'all' | string[] }>;\n}): Promise<RecordDisclosureV2>;\nexport async function buildRecordDisclosureV1(input: {\n recordKey: string;\n chain: { chainId: number; contractAddress: string };\n layout: { layoutId: number; layoutVersion: number; layoutDigest: string };\n entries: Array<{ receipt: RecordReceipt | RecordReceiptV3Items; reveal: 'all' | string[] }>;\n}): Promise<RecordDisclosure>;\nexport async function buildRecordDisclosureV1(input: {\n recordKey: string;\n chain: { chainId: number; contractAddress: string };\n layout: { layoutId: number; layoutVersion: number; layoutDigest: string };\n entries: Array<{ receipt: RecordReceipt | RecordReceiptV3Items; reveal: 'all' | string[] }>;\n}): Promise<RecordDisclosure> {\n const malformed = () => new RecordDisclosureError('DISCLOSURE_MALFORMED');\n if (!input || !Array.isArray(input.entries) || input.entries.length === 0) throw malformed();\n const recordKey = String(input.recordKey).toLowerCase();\n const schemas = new Set(input.entries.map((e) => e?.receipt?.schema));\n if (schemas.size !== 1) throw malformed();\n const schema = [...schemas][0];\n if (schema === 'semantic-receipt/v6') return buildDisclosureV2(input as Parameters<typeof buildDisclosureV2>[0]);\n if (schema !== 'semantic-receipt/v2' && schema !== 'semantic-receipt/v3') throw malformed();\n const version: 1 | 2 = schema === 'semantic-receipt/v3' ? 2 : 1;\n\n const seen = new Set<number>();\n const entries: RecordDisclosureEntryV1[] = [];\n for (const { receipt, reveal } of input.entries) {\n if (String(receipt.recordKey).toLowerCase() !== recordKey || seen.has(receipt.seq)) throw malformed();\n seen.add(receipt.seq);\n if (receipt.schema === 'semantic-receipt/v2') {\n if (reveal !== 'all') throw malformed();\n entries.push({ seq: receipt.seq, recordOpening: receipt.recordOpening, recordContent: receipt.recordContent });\n continue;\n }\n if (receipt.schema !== 'semantic-receipt/v3') throw malformed();\n const revealed = chosenLeaves(receipt.revealed, reveal);\n if (!revealed) throw malformed();\n entries.push({ seq: receipt.seq, recordOpening: receipt.recordOpening, leaves: [...receipt.leaves], revealed });\n }\n entries.sort((a, b) => a.seq - b.seq);\n\n const body: Omit<RecordDisclosureV1, 'digest'> = {\n schema: RECORD_DISCLOSURE_SCHEMA_V1,\n recordKey,\n chain: { chainId: input.chain.chainId, contractAddress: String(input.chain.contractAddress).toLowerCase() },\n layout: { layoutId: input.layout.layoutId, layoutVersion: input.layout.layoutVersion, layoutDigest: input.layout.layoutDigest },\n recordHashVersion: version,\n entries,\n };\n const disclosure: RecordDisclosureV1 = { ...body, digest: await computeRecordDisclosureDigestV1(body) };\n if (utf8(canonicalizeJcs(disclosure)).length > RECORD_DISCLOSURE_MAX_BYTES_V1) {\n throw new RecordDisclosureError('DISCLOSURE_TOO_LARGE');\n }\n return disclosure;\n}\n\nasync function buildDisclosureV2(input: {\n recordKey: string;\n chain: { chainId: number; contractAddress: string };\n layout: { layoutId: number; layoutVersion: number; layoutDigest: string };\n entries: Array<{ receipt: RecordReceiptV3Items; reveal: 'all' | string[] }>;\n}): Promise<RecordDisclosureV2> {\n const malformed = () => new RecordDisclosureError('DISCLOSURE_MALFORMED');\n const recordKey = String(input.recordKey).toLowerCase();\n const seen = new Set<number>();\n const entries: RecordDisclosureEntryV2[] = [];\n for (const { receipt, reveal } of input.entries) {\n if (String(receipt.recordKey).toLowerCase() !== recordKey || seen.has(receipt.seq)) throw malformed();\n if (!validateRecordItemsV3(receipt.items) || !Array.isArray(receipt.revealed)) throw malformed();\n seen.add(receipt.seq);\n const revealed = chosenLeaves(receipt.revealed, reveal);\n if (!revealed) throw malformed();\n entries.push({ seq: receipt.seq, recordOpening: receipt.recordOpening, items: receipt.items.map((it) => [it[0], it[1], it[2]]), revealed });\n }\n entries.sort((a, b) => a.seq - b.seq);\n const body: Omit<RecordDisclosureV2, 'digest'> = {\n schema: RECORD_DISCLOSURE_SCHEMA_V2,\n recordKey,\n chain: { chainId: input.chain.chainId, contractAddress: String(input.chain.contractAddress).toLowerCase() },\n layout: { layoutId: input.layout.layoutId, layoutVersion: input.layout.layoutVersion, layoutDigest: input.layout.layoutDigest },\n recordHashVersion: 3,\n entries,\n };\n const disclosure: RecordDisclosureV2 = { ...body, digest: await computeRecordDisclosureDigestV2(body) };\n if (utf8(canonicalizeJcs(disclosure)).length > RECORD_DISCLOSURE_MAX_BYTES_V1) {\n throw new RecordDisclosureError('DISCLOSURE_TOO_LARGE');\n }\n return disclosure;\n}\n", "const B64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';\nconst B64URL_TEXT = /^[A-Za-z0-9_-]*$/;\n/** Character code to 6-bit value: one lookup per character, so decoding a key takes no data-dependent search. */\nconst B64URL_VALUE = (() => {\n const table = new Uint8Array(256);\n for (let i = 0; i < B64URL.length; i += 1) table[B64URL.charCodeAt(i)] = i;\n return table;\n})();\n\n/** Unpadded base64url (RFC 4648 section 5). */\nexport function toBase64Url(bytes: Uint8Array): string {\n let out = '';\n let i = 0;\n for (; i + 2 < bytes.length; i += 3) {\n const n = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];\n out += B64URL[(n >> 18) & 63] + B64URL[(n >> 12) & 63] + B64URL[(n >> 6) & 63] + B64URL[n & 63];\n }\n if (i < bytes.length) {\n const rest = bytes.length - i;\n const n = (bytes[i] << 16) | (rest === 2 ? bytes[i + 1] << 8 : 0);\n out += B64URL[(n >> 18) & 63] + B64URL[(n >> 12) & 63];\n if (rest === 2) out += B64URL[(n >> 6) & 63];\n }\n return out;\n}\n\n/** Canonical unpadded base64url only: decoding and re-encoding gives the same text. */\nexport function fromBase64Url(text: string): Uint8Array | null {\n if (typeof text !== 'string' || !B64URL_TEXT.test(text) || text.length % 4 === 1) return null;\n const out = new Uint8Array(Math.floor((text.length * 3) / 4));\n let bits = 0;\n let acc = 0;\n let o = 0;\n for (let i = 0; i < text.length; i += 1) {\n acc = (acc << 6) | B64URL_VALUE[text.charCodeAt(i) & 0xff];\n bits += 6;\n if (bits >= 8) {\n bits -= 8;\n out[o++] = (acc >> bits) & 0xff;\n }\n acc &= (1 << bits) - 1;\n }\n if (acc !== 0) return null;\n return out;\n}\n\n/** The length of the unpadded base64url text of `byteLength` bytes. */\nexport function base64UrlLength(byteLength: number): number {\n return Math.floor(byteLength / 3) * 4 + (byteLength % 3 ? (byteLength % 3) + 1 : 0);\n}\n", "import { canonicalizeJcs } from '../proof/jcs';\nimport { fromBase64Url, toBase64Url } from './base64url';\nimport { concatBytes, platformCrypto, randomBytes, utf8 } from './platform-crypto';\nimport { RECORD_DISCLOSURE_MAX_BYTES_V1, RecordDisclosureError, type RecordDisclosure } from './record-disclosure-v1';\n\n/**\n * The sealed disclosure a link holds (ADR 0016; record-hash-v2.md section 7):\n * AES-256-GCM under a fresh key that travels only after `#` in the link, with\n * the link's handle as additional data. The plaintext is the disclosure's\n * canonical bytes padded with spaces to a 4096-byte step. These functions keep\n * no copy of the key and never log; no result or error carries the key, the\n * handle or the plaintext.\n */\nexport const RECORD_DISCLOSURE_ENVELOPE_VERSION_V1 = 0x01;\nexport const RECORD_DISCLOSURE_PAD_BLOCK_V1 = 4096;\nexport const RECORD_DISCLOSURE_ENVELOPE_MAX_BYTES_V1 = 1 + 12 + RECORD_DISCLOSURE_MAX_BYTES_V1 + 16;\nexport const RECORD_DISCLOSURE_ENVELOPE_MAX_CHARS_V1 = Math.ceil((RECORD_DISCLOSURE_ENVELOPE_MAX_BYTES_V1 * 4) / 3);\n\nexport type DisclosureEnvelopeRefusalV1 =\n | 'DISCLOSURE_ENVELOPE_MALFORMED'\n | 'DISCLOSURE_ENVELOPE_TOO_LARGE'\n | 'DISCLOSURE_ENVELOPE_AUTH_FAILED';\n\nconst REASONS: Record<DisclosureEnvelopeRefusalV1, string> = {\n DISCLOSURE_ENVELOPE_MALFORMED: \"This link's sealed disclosure is not in a form this version can open.\",\n DISCLOSURE_ENVELOPE_TOO_LARGE: \"This link's sealed disclosure is larger than a disclosure may be.\",\n DISCLOSURE_ENVELOPE_AUTH_FAILED:\n 'This disclosure could not be opened with this link. The link may be incomplete, or the disclosure belongs to another link.',\n};\n\nconst AAD_LABEL = 'pacspace:record-disclosure:v1';\nconst KEY_BYTES = 32;\nconst IV_BYTES = 12;\nconst TAG_BYTES = 16;\nconst HEADER_BYTES = 1 + IV_BYTES;\nconst SPACE = 0x20;\nconst FRAGMENT = /^dk=([A-Za-z0-9_-]{43})$/;\n\nfunction aadOf(handle: string): Uint8Array {\n return concatBytes(utf8(AAD_LABEL), new Uint8Array([0]), utf8(handle));\n}\n\nfunction refuse(code: DisclosureEnvelopeRefusalV1): { ok: false; code: DisclosureEnvelopeRefusalV1; reason: string } {\n return { ok: false, code, reason: REASONS[code] };\n}\n\n/** 32 fresh random bytes, one key per disclosure. */\nexport function newDisclosureKeyV1(): Uint8Array {\n return randomBytes(KEY_BYTES);\n}\n\n/** \"dk=\" plus the key's 43 base64url characters, for after `#` in the link. */\nexport function disclosureFragmentV1(key: Uint8Array): string {\n if (!(key instanceof Uint8Array) || key.length !== KEY_BYTES) throw new RecordDisclosureError('DISCLOSURE_MALFORMED');\n return `dk=${toBase64Url(key)}`;\n}\n\n/** The key from \"#dk=...\" or \"dk=...\", or null for anything else, including a non-canonical key text. */\nexport function readDisclosureFragmentV1(hash: string): Uint8Array | null {\n if (typeof hash !== 'string') return null;\n const match = FRAGMENT.exec(hash.startsWith('#') ? hash.slice(1) : hash);\n if (!match) return null;\n const key = fromBase64Url(match[1]);\n return key && key.length === KEY_BYTES ? key : null;\n}\n\n/**\n * A link's fragment in format 2 (card 10, D1 a): exactly one of `dk=` (the\n * key, as before) or `dd=` (the disclosure's own digest, when the key comes\n * from a wrap). Anything else, both, or a non-canonical text is null.\n */\nexport type DisclosureLinkFragmentV2 = { kind: 'key'; key: Uint8Array } | { kind: 'digest'; digest: string };\n\nconst LINK_FRAGMENT_V2 = /^(dk|dd)=([A-Za-z0-9_-]{43})$/;\nconst DIGEST_HEX = /^0x[0-9a-f]{64}$/;\n\nexport function readDisclosureLinkFragmentV2(hash: string): DisclosureLinkFragmentV2 | null {\n if (typeof hash !== 'string') return null;\n const match = LINK_FRAGMENT_V2.exec(hash.startsWith('#') ? hash.slice(1) : hash);\n if (!match) return null;\n const bytes = fromBase64Url(match[2]);\n if (!bytes || bytes.length !== KEY_BYTES || toBase64Url(bytes) !== match[2]) return null;\n if (match[1] === 'dk') return { kind: 'key', key: bytes };\n return { kind: 'digest', digest: `0x${Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')}` };\n}\n\n/** \"dd=\" plus the disclosure digest's 43 base64url characters, for after `#` in a link whose key comes from a wrap. */\nexport function disclosureDigestFragmentV2(digest: string): string {\n if (typeof digest !== 'string' || !DIGEST_HEX.test(digest)) throw new RecordDisclosureError('DISCLOSURE_MALFORMED');\n const bytes = new Uint8Array(KEY_BYTES);\n for (let i = 0; i < KEY_BYTES; i += 1) bytes[i] = parseInt(digest.slice(2 + i * 2, 4 + i * 2), 16);\n return `dd=${toBase64Url(bytes)}`;\n}\n\n/** The keyless checks decryption runs first (size, encoding, version byte, padded length). Never throws. */\nexport function readDisclosureEnvelopeShapeV1(\n text: string,\n): { ok: true; byteLength: number } | { ok: false; code: 'DISCLOSURE_ENVELOPE_MALFORMED' | 'DISCLOSURE_ENVELOPE_TOO_LARGE' } {\n if (typeof text !== 'string') return { ok: false, code: 'DISCLOSURE_ENVELOPE_MALFORMED' };\n if (text.length > RECORD_DISCLOSURE_ENVELOPE_MAX_CHARS_V1) return { ok: false, code: 'DISCLOSURE_ENVELOPE_TOO_LARGE' };\n const bytes = fromBase64Url(text);\n if (!bytes || bytes[0] !== RECORD_DISCLOSURE_ENVELOPE_VERSION_V1) return { ok: false, code: 'DISCLOSURE_ENVELOPE_MALFORMED' };\n const cipherLength = bytes.length - HEADER_BYTES - TAG_BYTES;\n if (cipherLength <= 0 || cipherLength % RECORD_DISCLOSURE_PAD_BLOCK_V1 !== 0) {\n return { ok: false, code: 'DISCLOSURE_ENVELOPE_MALFORMED' };\n }\n return { ok: true, byteLength: bytes.length };\n}\n\nasync function aesKey(key: Uint8Array, usage: 'encrypt' | 'decrypt'): Promise<CryptoKey> {\n const subtle = (await platformCrypto()).subtle;\n return subtle.importKey('raw', key as BufferSource, { name: 'AES-GCM' }, false, [usage]);\n}\n\n/** A key the caller already holds as a CryptoKey: AES-256-GCM, secret, usable to decrypt. Anything else opens nothing. */\nfunction isDecryptKey(key: unknown): key is CryptoKey {\n if (typeof CryptoKey === 'undefined' || !(key instanceof CryptoKey) || key.type !== 'secret' || !key.usages.includes('decrypt')) return false;\n const algorithm = key.algorithm as AesKeyAlgorithm;\n return algorithm.name === 'AES-GCM' && algorithm.length === KEY_BYTES * 8;\n}\n\n/** The base64url envelope of a disclosure under a fresh IV. */\nexport async function encryptDisclosureV1(input: { disclosure: RecordDisclosure; key: Uint8Array; handle: string }): Promise<string> {\n const { key, handle } = input;\n if (!(key instanceof Uint8Array) || key.length !== KEY_BYTES || typeof handle !== 'string') {\n throw new RecordDisclosureError('DISCLOSURE_MALFORMED');\n }\n const text = utf8(canonicalizeJcs(input.disclosure));\n if (text.length > RECORD_DISCLOSURE_MAX_BYTES_V1) throw new RecordDisclosureError('DISCLOSURE_TOO_LARGE');\n const padded = new Uint8Array(Math.ceil(text.length / RECORD_DISCLOSURE_PAD_BLOCK_V1) * RECORD_DISCLOSURE_PAD_BLOCK_V1);\n padded.set(text);\n padded.fill(SPACE, text.length);\n const iv = randomBytes(IV_BYTES);\n const subtle = (await platformCrypto()).subtle;\n const sealed = new Uint8Array(\n await subtle.encrypt({ name: 'AES-GCM', iv: iv as BufferSource, additionalData: aadOf(handle) as BufferSource, tagLength: 128 }, await aesKey(key, 'encrypt'), padded as BufferSource),\n );\n return toBase64Url(concatBytes(new Uint8Array([RECORD_DISCLOSURE_ENVELOPE_VERSION_V1]), iv, sealed));\n}\n\n/**\n * Opens an envelope; the caller then runs verifyRecordDisclosureV1 on `disclosure`. Never throws. The key is the 32\n * bytes, or a non-extractable AES-256-GCM CryptoKey with the decrypt usage that a browser keeps (plan conflict 2);\n * any other key is refused as not opening.\n */\nexport async function decryptDisclosureV1(input: {\n envelope: string;\n key: Uint8Array | CryptoKey;\n handle: string;\n}): Promise<{ ok: true; disclosure: unknown } | { ok: false; code: DisclosureEnvelopeRefusalV1; reason: string }> {\n try {\n const shape = readDisclosureEnvelopeShapeV1(input?.envelope);\n if (!shape.ok) return refuse(shape.code);\n const bytes = fromBase64Url(input.envelope) as Uint8Array;\n const { key, handle } = input;\n const held = isDecryptKey(key);\n if ((!held && (!(key instanceof Uint8Array) || key.length !== KEY_BYTES)) || typeof handle !== 'string') {\n return refuse('DISCLOSURE_ENVELOPE_AUTH_FAILED');\n }\n let plain: Uint8Array;\n try {\n const subtle = (await platformCrypto()).subtle;\n plain = new Uint8Array(\n await subtle.decrypt(\n { name: 'AES-GCM', iv: bytes.subarray(1, HEADER_BYTES) as BufferSource, additionalData: aadOf(handle) as BufferSource, tagLength: 128 },\n held ? key : await aesKey(key as Uint8Array, 'decrypt'),\n bytes.subarray(HEADER_BYTES) as BufferSource,\n ),\n );\n } catch {\n return refuse('DISCLOSURE_ENVELOPE_AUTH_FAILED');\n }\n let end = plain.length;\n while (end > 0 && plain[end - 1] === SPACE) end -= 1;\n if (plain.length - end >= RECORD_DISCLOSURE_PAD_BLOCK_V1) return refuse('DISCLOSURE_ENVELOPE_MALFORMED');\n const trimmed = plain.subarray(0, end);\n const text = new TextDecoder('utf-8', { fatal: true }).decode(trimmed);\n const disclosure: unknown = JSON.parse(text);\n const canonical = utf8(canonicalizeJcs(disclosure));\n if (canonical.length !== trimmed.length || canonical.some((b, i) => b !== trimmed[i])) return refuse('DISCLOSURE_ENVELOPE_MALFORMED');\n return { ok: true, disclosure };\n } catch {\n return refuse('DISCLOSURE_ENVELOPE_MALFORMED');\n }\n}\n", "import { fromBase64Url } from './base64url';\nimport { concatBytes, sha256, utf8 } from './platform-crypto';\nimport type { RecordsRefusalV1 } from './records-encryption-v1';\n\n/**\n * The keyless half of level 2's asymmetric formats (ADR 0015, formats notes\n * N3, N9 and N12): the sizes, the public key id, and the shape checks of a\n * seed wrap and of a wrap to a holder. Nothing here loads a library, so the\n * API checks what it stores with the same code the SDKs open it with; the\n * `records-crypto/asymmetric` subpath re-exports these.\n */\nexport const KEY_WRAP_SUITE_V1 = 'hpke-1' as const;\nexport const WORKSPACE_PUBLIC_KEY_BYTES_V1 = 1216;\nexport const KEY_WRAP_ENC_BYTES_V1 = 1120;\nexport const KEY_WRAP_CT_BYTES_V1 = 48;\nexport const SEED_WRAP_CT_BYTES_V1 = 48;\nexport const PUBLIC_KEY_ID_LABEL_V1 = 'pacspace:public-key-id:v1';\n\nconst SEP = new Uint8Array([0]);\nconst HEX64 = /^[0-9a-f]{64}$/;\nconst IV_BYTES = 12;\n\nconst refuse = <C extends string>(code: C): RecordsRefusalV1<C> => ({ ok: false, code });\nconst hex = (bytes: Uint8Array) => Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\n\n/**\n * `SHA-256(\"pacspace:public-key-id:v1\" || 0x00 || encoded public key)`, 64\n * lowercase hex; null unless the key is the encoded 1,216 bytes.\n */\nexport async function workspacePublicKeyIdV1(publicKey: Uint8Array): Promise<string | null> {\n if (!(publicKey instanceof Uint8Array) || publicKey.length !== WORKSPACE_PUBLIC_KEY_BYTES_V1) return null;\n return hex(await sha256(concatBytes(utf8(PUBLIC_KEY_ID_LABEL_V1), SEP, publicKey)));\n}\n\n/** The seed wrap's keyless checks (N9). Never throws. */\nexport function readSeedWrapShapeV1(wrap: unknown): { ok: true; kid: string; iv: Uint8Array; ct: Uint8Array } | RecordsRefusalV1<'SEED_WRAP_MALFORMED'> {\n if (!wrap || typeof wrap !== 'object' || Array.isArray(wrap)) return refuse('SEED_WRAP_MALFORMED');\n const w = wrap as Record<string, unknown>;\n if (Object.keys(w).sort().join(',') !== 'alg,ct,iv,kid,v') return refuse('SEED_WRAP_MALFORMED');\n if (w.v !== 1 || w.alg !== 'A256GCM' || typeof w.kid !== 'string' || !HEX64.test(w.kid)) return refuse('SEED_WRAP_MALFORMED');\n const iv = typeof w.iv === 'string' ? fromBase64Url(w.iv) : null;\n const ct = typeof w.ct === 'string' ? fromBase64Url(w.ct) : null;\n if (!iv || iv.length !== IV_BYTES || !ct || ct.length !== SEED_WRAP_CT_BYTES_V1) return refuse('SEED_WRAP_MALFORMED');\n return { ok: true, kid: w.kid, iv, ct };\n}\n\ntype KeyWrapShape = { ok: true; to: string; enc: Uint8Array; ct: Uint8Array } | RecordsRefusalV1<'KEY_WRAP_MALFORMED' | 'KEY_WRAP_SUITE'>;\n\n/** The keyless checks every reader of a wrap to a holder runs first (N9). Never throws. */\nexport function readKeyWrapShapeV1(wrap: unknown): KeyWrapShape {\n return readKeyWrapShape(wrap, 1);\n}\n\n/**\n * The same checks for a wrap v2 (card 10, F3), the only form a store route\n * takes and a reader opens: a v1 wrap is malformed here. Never throws.\n */\nexport function readKeyWrapShapeV2(wrap: unknown): KeyWrapShape {\n return readKeyWrapShape(wrap, 2);\n}\n\nfunction readKeyWrapShape(wrap: unknown, v: 1 | 2): KeyWrapShape {\n if (!wrap || typeof wrap !== 'object' || Array.isArray(wrap)) return refuse('KEY_WRAP_MALFORMED');\n const w = wrap as Record<string, unknown>;\n if (Object.keys(w).sort().join(',') !== 'ct,enc,suite,to,v' || w.v !== v || typeof w.suite !== 'string') return refuse('KEY_WRAP_MALFORMED');\n if (w.suite !== KEY_WRAP_SUITE_V1) return refuse('KEY_WRAP_SUITE');\n if (typeof w.to !== 'string' || !HEX64.test(w.to)) return refuse('KEY_WRAP_MALFORMED');\n const enc = typeof w.enc === 'string' ? fromBase64Url(w.enc) : null;\n const ct = typeof w.ct === 'string' ? fromBase64Url(w.ct) : null;\n if (!enc || enc.length !== KEY_WRAP_ENC_BYTES_V1 || !ct || ct.length !== KEY_WRAP_CT_BYTES_V1) return refuse('KEY_WRAP_MALFORMED');\n return { ok: true, to: w.to, enc, ct };\n}\n", "import { canonicalizeJcs } from '../proof/jcs';\nimport { base64UrlLength, fromBase64Url, toBase64Url } from './base64url';\nimport { concatBytes, hmacSha256, isHex32, platformCrypto, randomBytes, sha256, utf8 } from './platform-crypto';\n\n/**\n * Level 2's symmetric layer (ADR 0015 sections 5 and 7, and its formats\n * note, N1 to N6): the workspace secret's derivations, wire ids, the content\n * tag, the entry envelope and its padding, the size caps, the outside-copy\n * check and the keyring file. WebCrypto only, through platformCrypto.\n *\n * No key's bytes are ever printed: every key type keeps them in a module\n * WeakMap, so `JSON.stringify`, `inspect` and `toString` see the version and\n * the id only. Refusals carry a code and no sentence; nothing here logs.\n */\nexport const RECORDS_ENCRYPTION_LABELS_V1 = {\n idKey: 'pacspace:id-key:v1',\n recordsKey: 'pacspace:records-key:v1',\n wrapKey: 'pacspace:wrap-key:v1',\n recordKey: 'pacspace:record-key:v1',\n recordsKeyId: 'pacspace:records-key-id:v1',\n wrapKeyId: 'pacspace:wrap-key-id:v1',\n recordKeyId: 'pacspace:record-key-id:v1',\n recordId: 'pacspace:record-id:v1',\n referenceId: 'pacspace:reference-id:v1',\n contentTag: 'pacspace:content-tag:v1',\n entry: 'pacspace:record-entry:v1',\n} as const;\n\n/** Card 10, F2: the content tag is keyed per version of the workspace secret. */\nexport const RECORDS_CONTENT_TAG_LABELS_V2 = {\n contentTagKey: 'pacspace:content-tag-key:v2',\n contentTag: 'pacspace:content-tag:v2',\n} as const;\n\nexport const RECORDS_ENCRYPTION_PAD_BLOCK_V1 = 256;\nexport const RECORD_ENTRY_PLAINTEXT_MAX_BYTES_V1 = 47104;\nexport const RECORD_ENTRY_CIPHERTEXT_MAX_BYTES_V1 = RECORD_ENTRY_PLAINTEXT_MAX_BYTES_V1 + 16;\nexport const RECORD_ENTRY_CIPHERTEXT_MAX_CHARS_V1 = base64UrlLength(RECORD_ENTRY_CIPHERTEXT_MAX_BYTES_V1);\nexport const RECORD_ENTRY_BODY_MAX_BYTES_V1 = 65536;\nexport const RECORDS_KEYRING_MAX_BYTES_V1 = 65536;\nexport const RECORDS_KEYRING_SCHEMA_V1 = 'pacspace-workspace-secret/v1';\nexport const WORKSPACE_SECRET_BYTES_V1 = 32;\n\nexport type RecordsEncryptionCodeV1 =\n | 'RECORDS_KEY_INVALID'\n | 'RECORDS_KEYRING_MALFORMED'\n | 'RECORDS_KEYRING_TOO_LARGE'\n | 'RECORD_ENTRY_MALFORMED'\n | 'RECORD_ENTRY_TOO_LARGE'\n | 'RECORD_ENTRY_BODY_TOO_LARGE'\n | 'RECORD_ENTRY_REFS_MISMATCH'\n | 'RECORD_ENTRY_HASH_MISMATCH'\n | 'RECORD_ENVELOPE_MALFORMED'\n | 'RECORD_ENVELOPE_TOO_LARGE'\n | 'RECORD_ENVELOPE_WRONG_KEY'\n | 'RECORD_ENVELOPE_AUTH_FAILED'\n | 'RECORD_ENVELOPE_PADDING';\n\n/** Thrown by the writing side only; its message is the code. */\nexport class RecordsEncryptionError extends Error {\n constructor(readonly code: RecordsEncryptionCodeV1) {\n super(code);\n this.name = 'RecordsEncryptionError';\n }\n}\n\nexport type RecordsRefusalV1<C extends string = RecordsEncryptionCodeV1> = { ok: false; code: C };\nconst refuse = <C extends string>(code: C): RecordsRefusalV1<C> => ({ ok: false, code });\n\nconst KEY_BYTES = 32;\nconst IV_BYTES = 12;\nconst TAG_BYTES = 16;\nconst SPACE = 0x20;\nconst SEP = new Uint8Array([0]);\nconst HEX64 = /^[0-9a-f]{64}$/;\nconst WIRE_ID = /^[A-Za-z0-9_-]{22}$/;\nconst L = RECORDS_ENCRYPTION_LABELS_V1;\nconst INSPECT = Symbol.for('nodejs.util.inspect.custom');\n\n// ------------------------------------------------------------------ key types\n\nconst KEY_BYTES_OF = new WeakMap<object, Uint8Array>();\n/** Only this module makes keys, so a key's id is always the one its bytes derive. */\nconst MINT: unique symbol = Symbol('records key');\ntype Mint = typeof MINT;\n\nabstract class HiddenKey {\n protected constructor(mint: Mint, bytes: Uint8Array) {\n if (mint !== MINT) throw new TypeError('records keys are made by their derive and import functions');\n KEY_BYTES_OF.set(this, Uint8Array.from(bytes));\n }\n protected abstract describe(): string;\n toString(): string {\n return this.describe();\n }\n toJSON(): string {\n return this.describe();\n }\n [INSPECT](): string {\n return this.describe();\n }\n}\n\n/** The id key, from version 1 of the workspace secret only (wire ids never change across rotations). */\nexport class RecordsIdKeyV1 extends HiddenKey {\n /** @internal */\n constructor(mint: Mint, bytes: Uint8Array) {\n super(mint, bytes);\n }\n protected describe(): string {\n return '[records id key]';\n }\n}\n\n/** `K_v`: reads every record made under version `version`. */\nexport class RecordsKeyV1 extends HiddenKey {\n /** @internal */\n constructor(mint: Mint, bytes: Uint8Array, readonly version: number, readonly id: string) {\n super(mint, bytes);\n }\n protected describe(): string {\n return `[records key v${this.version} ${this.id.slice(0, 8)}]`;\n }\n}\n\n/** `W_v`: wraps the workspace's private seed for storage at PacSpace (L2a2). */\nexport class RecordsWrapKeyV1 extends HiddenKey {\n /** @internal */\n constructor(mint: Mint, bytes: Uint8Array, readonly version: number, readonly id: string) {\n super(mint, bytes);\n }\n protected describe(): string {\n return `[wrap key v${this.version} ${this.id.slice(0, 8)}]`;\n }\n}\n\n/** The content-tag key of one version (card 10, F2): tags made under it say nothing under another version. */\nexport class RecordsContentTagKeyV2 extends HiddenKey {\n /** @internal */\n constructor(mint: Mint, bytes: Uint8Array, readonly version: number) {\n super(mint, bytes);\n }\n protected describe(): string {\n return `[content tag key v${this.version}]`;\n }\n}\n\n/**\n * `RK`: opens one record's envelopes and no other. `recordsKeyId` is the id\n * of the `K_v` that made it, or null for a key that arrived on its own (a\n * copy file, a grant, a record-scope holder).\n */\nexport class RecordKeyV1 extends HiddenKey {\n /** @internal */\n constructor(mint: Mint, bytes: Uint8Array, readonly id: string, readonly recordsKeyId: string | null) {\n super(mint, bytes);\n }\n protected describe(): string {\n return `[record key ${this.id.slice(0, 8)}]`;\n }\n}\n\ntype AnyKey = RecordsIdKeyV1 | RecordsKeyV1 | RecordsWrapKeyV1 | RecordKeyV1 | RecordsContentTagKeyV2;\n\nfunction bytesOf(key: AnyKey): Uint8Array {\n const bytes = KEY_BYTES_OF.get(key);\n if (!bytes) throw new RecordsEncryptionError('RECORDS_KEY_INVALID');\n return bytes;\n}\n\n/**\n * A key's raw bytes, for the three places they may leave the key layer: a\n * copy file (`RK`), a wrap to a holder (L2a2), and the published vectors.\n */\nexport function exportKeyBytesV1(key: AnyKey): Uint8Array {\n return Uint8Array.from(bytesOf(key));\n}\n\n// ------------------------------------------------------------------ derivations (N3)\n\nasync function hkdf32(ikm: Uint8Array, salt: Uint8Array, info: string): Promise<Uint8Array> {\n const { subtle } = await platformCrypto();\n const base = await subtle.importKey('raw', Uint8Array.from(ikm), 'HKDF', false, ['deriveBits']);\n return hkdf32From(base, salt, info);\n}\n\nasync function hkdf32From(base: CryptoKey, salt: Uint8Array, info: string): Promise<Uint8Array> {\n const { subtle } = await platformCrypto();\n const bits = await subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: Uint8Array.from(salt), info: utf8(info) as BufferSource }, base, KEY_BYTES * 8);\n return new Uint8Array(bits);\n}\n\nconst hex = (bytes: Uint8Array) => Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\nconst keyIdOf = async (label: string, key: Uint8Array) => hex(await sha256(concatBytes(utf8(label), SEP, key)));\n\nfunction assertSecret(secret: Uint8Array, version: number): void {\n if (!(secret instanceof Uint8Array) || secret.length !== WORKSPACE_SECRET_BYTES_V1 || !Number.isSafeInteger(version) || version < 1) {\n throw new RecordsEncryptionError('RECORDS_KEY_INVALID');\n }\n}\n\n/** 32 fresh random bytes: a new workspace secret. It is the customer's; it never reaches PacSpace. */\nexport function generateWorkspaceSecretV1(): Uint8Array {\n return randomBytes(WORKSPACE_SECRET_BYTES_V1);\n}\n\n/** The id key, from version 1 of the workspace secret. */\nexport async function deriveRecordsIdKeyV1(secretV1: Uint8Array): Promise<RecordsIdKeyV1> {\n assertSecret(secretV1, 1);\n return new RecordsIdKeyV1(MINT, await hkdf32(secretV1, new Uint8Array(0), L.idKey));\n}\n\ntype VersionKeys = { recordsKey: RecordsKeyV1; wrapKey: RecordsWrapKeyV1; contentTagKey: RecordsContentTagKeyV2 };\n\n/** `K_v`, `W_v` (with their ids) and the content-tag key of one version. */\nexport async function deriveRecordsKeysV1(secret: Uint8Array, version: number): Promise<VersionKeys> {\n assertSecret(secret, version);\n const k = await hkdf32(secret, new Uint8Array(0), L.recordsKey);\n const w = await hkdf32(secret, new Uint8Array(0), L.wrapKey);\n const t = await hkdf32(secret, new Uint8Array(0), RECORDS_CONTENT_TAG_LABELS_V2.contentTagKey);\n return {\n recordsKey: new RecordsKeyV1(MINT, k, version, await keyIdOf(L.recordsKeyId, k)),\n wrapKey: new RecordsWrapKeyV1(MINT, w, version, await keyIdOf(L.wrapKeyId, w)),\n contentTagKey: new RecordsContentTagKeyV2(MINT, t, version),\n };\n}\n\n/**\n * One version of the workspace secret as a non-extractable HKDF key, for a\n * browser to store: no script can read the secret back out of it. Keys\n * derived from it are bytes in memory, as every derivation here needs.\n */\nexport async function importWorkspaceSecretKeyV1(secret: Uint8Array, version: number): Promise<CryptoKey> {\n assertSecret(secret, version);\n const { subtle } = await platformCrypto();\n return subtle.importKey('raw', Uint8Array.from(secret), 'HKDF', false, ['deriveBits']);\n}\n\nfunction assertBaseKey(base: CryptoKey): void {\n if (\n !base ||\n typeof base !== 'object' ||\n (base.algorithm as { name?: unknown } | undefined)?.name !== 'HKDF' ||\n base.extractable !== false ||\n !base.usages.includes('deriveBits')\n ) {\n throw new RecordsEncryptionError('RECORDS_KEY_INVALID');\n }\n}\n\n/** The id key, from version 1's stored key (`importWorkspaceSecretKeyV1`). */\nexport async function deriveRecordsIdKeyFromBaseV1(baseV1: CryptoKey): Promise<RecordsIdKeyV1> {\n assertBaseKey(baseV1);\n return new RecordsIdKeyV1(MINT, await hkdf32From(baseV1, new Uint8Array(0), L.idKey));\n}\n\n/** `K_v`, `W_v` and the content-tag key of one version, from its stored key. */\nexport async function deriveRecordsKeysFromBaseV1(base: CryptoKey, version: number): Promise<VersionKeys> {\n assertBaseKey(base);\n if (!Number.isSafeInteger(version) || version < 1) throw new RecordsEncryptionError('RECORDS_KEY_INVALID');\n const k = await hkdf32From(base, new Uint8Array(0), L.recordsKey);\n const w = await hkdf32From(base, new Uint8Array(0), L.wrapKey);\n const t = await hkdf32From(base, new Uint8Array(0), RECORDS_CONTENT_TAG_LABELS_V2.contentTagKey);\n return {\n recordsKey: new RecordsKeyV1(MINT, k, version, await keyIdOf(L.recordsKeyId, k)),\n wrapKey: new RecordsWrapKeyV1(MINT, w, version, await keyIdOf(L.wrapKeyId, w)),\n contentTagKey: new RecordsContentTagKeyV2(MINT, t, version),\n };\n}\n\n/** `RK` for one record: HKDF of `K_v` salted with the wire record id. */\nexport async function recordKeyOfV1(recordsKey: RecordsKeyV1, wireRecordId: string): Promise<RecordKeyV1> {\n if (!(recordsKey instanceof RecordsKeyV1) || !WIRE_ID.test(wireRecordId)) throw new RecordsEncryptionError('RECORDS_KEY_INVALID');\n const rk = await hkdf32(bytesOf(recordsKey), utf8(wireRecordId), L.recordKey);\n return new RecordKeyV1(MINT, rk, await keyIdOf(L.recordKeyId, rk), recordsKey.id);\n}\n\n/** `K_v` that arrived in a wrap: 32 bytes, its id recomputed from them. */\nexport async function recordsKeyFromBytesV1(bytes: Uint8Array, version: number): Promise<RecordsKeyV1> {\n if (!(bytes instanceof Uint8Array) || bytes.length !== KEY_BYTES || !Number.isSafeInteger(version) || version < 1) {\n throw new RecordsEncryptionError('RECORDS_KEY_INVALID');\n }\n return new RecordsKeyV1(MINT, bytes, version, await keyIdOf(L.recordsKeyId, bytes));\n}\n\n/**\n * A record key that arrived on its own (a copy file, a grant): 32 bytes.\n * `recordsKeyId` is given only by a caller that made the key from that\n * `K_v` itself, so a verifier can tell which envelopes it must open.\n */\nexport async function recordKeyFromBytesV1(bytes: Uint8Array, recordsKeyId: string | null = null): Promise<RecordKeyV1> {\n if (!(bytes instanceof Uint8Array) || bytes.length !== KEY_BYTES) throw new RecordsEncryptionError('RECORDS_KEY_INVALID');\n if (recordsKeyId !== null && !/^[0-9a-f]{64}$/.test(recordsKeyId)) throw new RecordsEncryptionError('RECORDS_KEY_INVALID');\n return new RecordKeyV1(MINT, bytes, await keyIdOf(L.recordKeyId, bytes), recordsKeyId);\n}\n\n// ------------------------------------------------------------------ wire ids and the content tag (N4)\n\nconst wire16 = async (idKey: RecordsIdKeyV1, message: Uint8Array) => toBase64Url((await hmacSha256(bytesOf(idKey), message)).subarray(0, 16));\n\n/** The record's id on the wire: 22 characters, the same across key rotations. */\nexport async function wireRecordIdV1(idKey: RecordsIdKeyV1, recordType: string, entityId: string): Promise<string> {\n return wire16(idKey, concatBytes(utf8(L.recordId), SEP, utf8(recordType), SEP, utf8(entityId)));\n}\n\n/** The caller's reference on the wire: 22 characters, scoped like today's reference. */\nexport async function wireReferenceIdV1(idKey: RecordsIdKeyV1, referenceId: string): Promise<string> {\n return wire16(idKey, concatBytes(utf8(L.referenceId), SEP, utf8(referenceId)));\n}\n\n/**\n * A label blinded for an encrypted workspace (D-23): `b1:` and the base64url\n * HMAC-SHA-256, under the id key, of `name=value`. The name is lowercased\n * first, as `parseLabels` does. 46 characters.\n */\nexport async function blindedLabelV1(idKey: RecordsIdKeyV1, name: string, value: string): Promise<string> {\n return `b1:${toBase64Url(await hmacSha256(bytesOf(idKey), utf8(`${name.toLowerCase()}=${value}`)))}`;\n}\n\n/** The keyed tag of an entry's content and lifecycle; the default caller reference. 43 characters. */\nexport async function contentTagV1(\n idKey: RecordsIdKeyV1,\n input: { recordType: string; wireRecordId: string; content: Record<string, unknown>; lifecycle: string },\n): Promise<string> {\n const message = concatBytes(\n utf8(L.contentTag), SEP, utf8(input.recordType), SEP, utf8(input.wireRecordId), SEP,\n utf8(canonicalizeJcs({ content: input.content, lifecycle: input.lifecycle })),\n );\n return toBase64Url(await hmacSha256(bytesOf(idKey), message));\n}\n\n/**\n * The content tag under the record's version (card 10, F2): HMAC of the\n * version's content-tag key over \"pacspace:content-tag:v2\" || 0x00 ||\n * recordType || 0x00 || wireRecordId || 0x00 || JCS({content, lifecycle}).\n * The default caller reference, so it deduplicates within one version only.\n */\nexport async function contentTagV2(\n contentTagKey: RecordsContentTagKeyV2,\n input: { recordType: string; wireRecordId: string; content: Record<string, unknown>; lifecycle: string },\n): Promise<string> {\n if (!(contentTagKey instanceof RecordsContentTagKeyV2)) throw new RecordsEncryptionError('RECORDS_KEY_INVALID');\n const message = concatBytes(\n utf8(RECORDS_CONTENT_TAG_LABELS_V2.contentTag), SEP, utf8(input.recordType), SEP, utf8(input.wireRecordId), SEP,\n utf8(canonicalizeJcs({ content: input.content, lifecycle: input.lifecycle })),\n );\n return toBase64Url(await hmacSha256(bytesOf(contentTagKey), message));\n}\n\n// ------------------------------------------------------------------ the envelope (N5, N6)\n\nexport interface RecordEntryEnvelopeV1 {\n v: 1;\n alg: 'A256GCM';\n kid: string;\n iv: string;\n ct: string;\n}\n\n/**\n * `UTF-8(JCS({ content, saltKey }))`; throws RECORD_ENTRY_MALFORMED unless the\n * content is an object and the salt key 0x-prefixed 32-byte hex, and\n * RECORD_ENTRY_TOO_LARGE past the cap.\n */\nexport function recordEntryPlaintextV1(content: Record<string, unknown>, saltKey: string): Uint8Array {\n if (!content || typeof content !== 'object' || Array.isArray(content) || !isHex32(saltKey)) {\n throw new RecordsEncryptionError('RECORD_ENTRY_MALFORMED');\n }\n const p = utf8(canonicalizeJcs({ content, saltKey }));\n if (p.length > RECORD_ENTRY_PLAINTEXT_MAX_BYTES_V1) throw new RecordsEncryptionError('RECORD_ENTRY_TOO_LARGE');\n return p;\n}\n\n/** The plaintext with spaces to the next multiple of 256 bytes (none when it is one already). */\nexport function padRecordEntryV1(plaintext: Uint8Array): Uint8Array {\n const block = RECORDS_ENCRYPTION_PAD_BLOCK_V1;\n const out = new Uint8Array(Math.ceil(plaintext.length / block) * block);\n out.set(plaintext);\n out.fill(SPACE, plaintext.length);\n return out;\n}\n\nconst aadOf = (recordType: string, wireRecordId: string) =>\n concatBytes(utf8(L.entry), SEP, utf8(recordType), SEP, utf8(wireRecordId)) as BufferSource;\n\nasync function aesKey(key: Uint8Array, usage: 'encrypt' | 'decrypt'): Promise<CryptoKey> {\n const { subtle } = await platformCrypto();\n return subtle.importKey('raw', Uint8Array.from(key), { name: 'AES-GCM' }, false, [usage]);\n}\n\n/** @internal Seals already padded bytes under a given IV; vectors and the seal below only. */\nexport async function sealPaddedEntryV1(input: {\n recordKey: RecordKeyV1;\n recordsKeyId: string;\n recordType: string;\n wireRecordId: string;\n padded: Uint8Array;\n iv: Uint8Array;\n}): Promise<RecordEntryEnvelopeV1> {\n if (!HEX64.test(input.recordsKeyId) || !(input.iv instanceof Uint8Array) || input.iv.length !== IV_BYTES) {\n throw new RecordsEncryptionError('RECORDS_KEY_INVALID');\n }\n const { subtle } = await platformCrypto();\n const sealed = new Uint8Array(\n await subtle.encrypt(\n { name: 'AES-GCM', iv: Uint8Array.from(input.iv), additionalData: aadOf(input.recordType, input.wireRecordId), tagLength: 128 },\n await aesKey(bytesOf(input.recordKey), 'encrypt'),\n Uint8Array.from(input.padded),\n ),\n );\n return { v: 1, alg: 'A256GCM', kid: input.recordsKeyId, iv: toBase64Url(input.iv), ct: toBase64Url(sealed) };\n}\n\n/** Seals one entry under its record key with a fresh IV. The record key must come from a `K_v` (it names it as `kid`). */\nexport async function sealRecordEntryV1(input: {\n recordKey: RecordKeyV1;\n recordType: string;\n wireRecordId: string;\n content: Record<string, unknown>;\n saltKey: string;\n}): Promise<RecordEntryEnvelopeV1> {\n if (!(input.recordKey instanceof RecordKeyV1) || input.recordKey.recordsKeyId === null) throw new RecordsEncryptionError('RECORDS_KEY_INVALID');\n return sealPaddedEntryV1({\n recordKey: input.recordKey,\n recordsKeyId: input.recordKey.recordsKeyId,\n recordType: input.recordType,\n wireRecordId: input.wireRecordId,\n padded: padRecordEntryV1(recordEntryPlaintextV1(input.content, input.saltKey)),\n iv: randomBytes(IV_BYTES),\n });\n}\n\n/** The keyless checks every reader and intake run first. Never throws. */\nexport function readRecordEnvelopeShapeV1(\n envelope: unknown,\n): { ok: true; kid: string; iv: Uint8Array; ct: Uint8Array } | RecordsRefusalV1<'RECORD_ENVELOPE_MALFORMED' | 'RECORD_ENVELOPE_TOO_LARGE'> {\n if (!envelope || typeof envelope !== 'object' || Array.isArray(envelope)) return refuse('RECORD_ENVELOPE_MALFORMED');\n const e = envelope as Record<string, unknown>;\n const keys = Object.keys(e).sort();\n if (keys.join(',') !== 'alg,ct,iv,kid,v') return refuse('RECORD_ENVELOPE_MALFORMED');\n if (e.v !== 1 || e.alg !== 'A256GCM' || typeof e.kid !== 'string' || !HEX64.test(e.kid)) return refuse('RECORD_ENVELOPE_MALFORMED');\n if (typeof e.ct !== 'string' || typeof e.iv !== 'string') return refuse('RECORD_ENVELOPE_MALFORMED');\n if (e.ct.length > RECORD_ENTRY_CIPHERTEXT_MAX_CHARS_V1) return refuse('RECORD_ENVELOPE_TOO_LARGE');\n const iv = fromBase64Url(e.iv);\n const ct = fromBase64Url(e.ct);\n if (!iv || iv.length !== IV_BYTES || !ct) return refuse('RECORD_ENVELOPE_MALFORMED');\n const body = ct.length - TAG_BYTES;\n if (body <= 0 || body % RECORDS_ENCRYPTION_PAD_BLOCK_V1 !== 0) return refuse('RECORD_ENVELOPE_MALFORMED');\n return { ok: true, kid: e.kid, iv, ct };\n}\n\nexport type OpenRecordEntryResultV1 =\n | { ok: true; content: Record<string, unknown>; saltKey: string; recordsKeyId: string | null }\n | RecordsRefusalV1<'RECORD_ENVELOPE_MALFORMED' | 'RECORD_ENVELOPE_TOO_LARGE' | 'RECORD_ENVELOPE_WRONG_KEY' | 'RECORD_ENVELOPE_AUTH_FAILED' | 'RECORD_ENVELOPE_PADDING'>;\n\n/**\n * Opens one envelope with a record key, or with a keyring (whose `K_v`\n * named by `kid` makes the record key). Never throws.\n */\nexport async function openRecordEntryEnvelopeV1(input: {\n envelope: unknown;\n recordType: string;\n wireRecordId: string;\n recordKey?: RecordKeyV1;\n keyring?: RecordsKeyringV1;\n}): Promise<OpenRecordEntryResultV1> {\n try {\n const shape = readRecordEnvelopeShapeV1(input?.envelope);\n if (!shape.ok) return shape;\n let rk = input.recordKey;\n if (input.keyring) {\n const k = input.keyring.byId(shape.kid);\n if (!k) return refuse('RECORD_ENVELOPE_WRONG_KEY');\n rk = await recordKeyOfV1(k, input.wireRecordId);\n }\n if (!(rk instanceof RecordKeyV1)) return refuse('RECORD_ENVELOPE_AUTH_FAILED');\n let plain: Uint8Array;\n try {\n const { subtle } = await platformCrypto();\n plain = new Uint8Array(\n await subtle.decrypt(\n { name: 'AES-GCM', iv: Uint8Array.from(shape.iv), additionalData: aadOf(input.recordType, input.wireRecordId), tagLength: 128 },\n await aesKey(bytesOf(rk), 'decrypt'),\n Uint8Array.from(shape.ct),\n ),\n );\n } catch {\n return refuse('RECORD_ENVELOPE_AUTH_FAILED');\n }\n let end = plain.length;\n while (end > 0 && plain[end - 1] === SPACE) end -= 1;\n if (plain.length - end >= RECORDS_ENCRYPTION_PAD_BLOCK_V1) return refuse('RECORD_ENVELOPE_PADDING');\n const trimmed = plain.subarray(0, end);\n const parsed: unknown = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(trimmed));\n const canonical = utf8(canonicalizeJcs(parsed));\n if (canonical.length !== trimmed.length || canonical.some((b, i) => b !== trimmed[i])) return refuse('RECORD_ENVELOPE_PADDING');\n const value = parsed as Record<string, unknown>;\n if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).sort().join(',') !== 'content,saltKey') {\n return refuse('RECORD_ENVELOPE_PADDING');\n }\n const content = value.content;\n if (!content || typeof content !== 'object' || Array.isArray(content) || !isHex32(value.saltKey)) return refuse('RECORD_ENVELOPE_PADDING');\n return { ok: true, content: content as Record<string, unknown>, saltKey: value.saltKey as string, recordsKeyId: input.keyring ? shape.kid : rk.recordsKeyId };\n } catch {\n return refuse('RECORD_ENVELOPE_PADDING');\n }\n}\n\n// ------------------------------------------------------------------ the write body (N5)\n\n/** The serialized length of an encrypted write's body, with the envelope at the length `plaintextBytes` gives it. */\nexport function encryptedWriteBodyBytesV1(body: Record<string, unknown>, recordsKeyId: string, plaintextBytes: number): number {\n const padded = Math.ceil(plaintextBytes / RECORDS_ENCRYPTION_PAD_BLOCK_V1) * RECORDS_ENCRYPTION_PAD_BLOCK_V1;\n const envelope = { v: 1, alg: 'A256GCM', kid: recordsKeyId, iv: 'A'.repeat(base64UrlLength(IV_BYTES)), ct: 'A'.repeat(base64UrlLength(padded + TAG_BYTES)) };\n return utf8(canonicalizeJcs({ ...body, envelope })).length;\n}\n\n/** Both caps, checked before encrypting. */\nexport function checkEncryptedWriteSizeV1(\n body: Record<string, unknown>,\n recordsKeyId: string,\n plaintextBytes: number,\n): { ok: true; bodyBytes: number } | (RecordsRefusalV1<'RECORD_ENTRY_TOO_LARGE' | 'RECORD_ENTRY_BODY_TOO_LARGE'> & { bodyBytes: number | null }) {\n if (plaintextBytes > RECORD_ENTRY_PLAINTEXT_MAX_BYTES_V1) return { ...refuse('RECORD_ENTRY_TOO_LARGE'), bodyBytes: null };\n const bodyBytes = encryptedWriteBodyBytesV1(body, recordsKeyId, plaintextBytes);\n if (bodyBytes > RECORD_ENTRY_BODY_MAX_BYTES_V1) return { ...refuse('RECORD_ENTRY_BODY_TOO_LARGE'), bodyBytes };\n return { ok: true, bodyBytes };\n}\n\n// ------------------------------------------------------------------ the outside copies (N7)\n\nconst jcsOrNull = (value: unknown) => (value === undefined ? null : canonicalizeJcs(value));\n\n/** `amends` and `references` inside the content equal the copies outside the envelope (both absent is equal). */\nexport function entryRefsMatchV1(\n content: Record<string, unknown>,\n outside: { amends?: unknown; references?: unknown },\n): { ok: true } | RecordsRefusalV1<'RECORD_ENTRY_REFS_MISMATCH'> {\n try {\n for (const member of ['amends', 'references'] as const) {\n if (jcsOrNull(content?.[member]) !== jcsOrNull(outside?.[member])) return refuse('RECORD_ENTRY_REFS_MISMATCH');\n }\n return { ok: true };\n } catch {\n return refuse('RECORD_ENTRY_REFS_MISMATCH');\n }\n}\n\n// ------------------------------------------------------------------ the keyring (N2) and the key interface\n\n/**\n * Where the SDKs get the workspace secret. The local provider holds it in\n * memory; a customer's provider can answer from a KMS or HSM.\n */\nexport interface RecordsKeyProviderV1 {\n /** Every version held, ascending from 1 with no gaps. */\n versions(): Promise<number[]>;\n /** The 32-byte secret of one version. */\n secret(version: number): Promise<Uint8Array>;\n}\n\n/** A provider over stored keys (`importWorkspaceSecretKeyV1`), for a browser that keeps no secret bytes. */\nexport interface RecordsBaseKeyProviderV1 {\n /** Every version held, ascending from 1 with no gaps. */\n versions(): Promise<number[]>;\n /** The stored key of one version. */\n baseKey(version: number): Promise<CryptoKey>;\n}\n\nfunction assertVersions(versions: unknown): void {\n if (!Array.isArray(versions) || versions.length === 0 || versions.some((v, i) => v !== i + 1)) {\n throw new RecordsEncryptionError('RECORDS_KEY_INVALID');\n }\n}\n\n/** Every version of a workspace's keys, made once from a provider. */\nexport class RecordsKeyringV1 {\n readonly #byId = new Map<string, RecordsKeyV1>();\n readonly #byVersion = new Map<number, RecordsKeyV1>();\n readonly #wrap = new Map<number, RecordsWrapKeyV1>();\n readonly #tag = new Map<number, RecordsContentTagKeyV2>();\n\n private constructor(readonly idKey: RecordsIdKeyV1) {}\n\n static async fromProvider(provider: RecordsKeyProviderV1): Promise<RecordsKeyringV1> {\n const versions = await provider.versions();\n assertVersions(versions);\n const ring = new RecordsKeyringV1(await deriveRecordsIdKeyV1(await provider.secret(1)));\n for (const version of versions) ring.#add(await deriveRecordsKeysV1(await provider.secret(version), version));\n return ring;\n }\n\n /** The same keyring, from stored keys: the same derivations, no secret bytes. */\n static async fromBaseKeys(provider: RecordsBaseKeyProviderV1): Promise<RecordsKeyringV1> {\n const versions = await provider.versions();\n assertVersions(versions);\n const ring = new RecordsKeyringV1(await deriveRecordsIdKeyFromBaseV1(await provider.baseKey(1)));\n for (const version of versions) ring.#add(await deriveRecordsKeysFromBaseV1(await provider.baseKey(version), version));\n return ring;\n }\n\n #add({ recordsKey, wrapKey, contentTagKey }: VersionKeys): void {\n this.#byId.set(recordsKey.id, recordsKey);\n this.#byVersion.set(recordsKey.version, recordsKey);\n this.#wrap.set(wrapKey.version, wrapKey);\n this.#tag.set(contentTagKey.version, contentTagKey);\n }\n\n /** The newest version: new records are made under it. */\n get current(): RecordsKeyV1 {\n return this.#byVersion.get(this.#byVersion.size) as RecordsKeyV1;\n }\n\n get versions(): number[] {\n return [...this.#byVersion.keys()];\n }\n\n byId(id: string): RecordsKeyV1 | null {\n return this.#byId.get(id) ?? null;\n }\n\n byVersion(version: number): RecordsKeyV1 | null {\n return this.#byVersion.get(version) ?? null;\n }\n\n wrapKey(version: number): RecordsWrapKeyV1 | null {\n return this.#wrap.get(version) ?? null;\n }\n\n contentTagKey(version: number): RecordsContentTagKeyV2 | null {\n return this.#tag.get(version) ?? null;\n }\n\n toString(): string {\n return `[records keyring v1..v${this.#byVersion.size}]`;\n }\n\n toJSON(): string {\n return this.toString();\n }\n\n [INSPECT](): string {\n return this.toString();\n }\n}\n\n/** A provider over secrets held in memory: a keyring file's text, or the secrets themselves. */\nexport function localRecordsKeyProviderV1(source: string | ReadonlyArray<{ version: number; secret: Uint8Array }>): RecordsKeyProviderV1 {\n let secrets: Array<{ version: number; secret: Uint8Array }>;\n if (typeof source === 'string') {\n const parsed = parseRecordsKeyringFileV1(source);\n if (!parsed.ok) throw new RecordsEncryptionError(parsed.code);\n secrets = parsed.secrets;\n } else {\n secrets = source.map((s) => ({ version: s.version, secret: Uint8Array.from(s.secret) }));\n if (!secretsAreAKeyring(secrets)) throw new RecordsEncryptionError('RECORDS_KEY_INVALID');\n }\n const held = new Map(secrets.map((s) => [s.version, s.secret]));\n const provider: RecordsKeyProviderV1 & { toString(): string; toJSON(): string } = {\n versions: async () => [...held.keys()],\n secret: async (version: number) => {\n const s = held.get(version);\n if (!s) throw new RecordsEncryptionError('RECORDS_KEY_INVALID');\n return Uint8Array.from(s);\n },\n toString: () => `[local records key provider v1..v${held.size}]`,\n toJSON: () => `[local records key provider v1..v${held.size}]`,\n };\n Object.defineProperty(provider, INSPECT, { value: () => provider.toString() });\n return provider;\n}\n\nfunction secretsAreAKeyring(secrets: ReadonlyArray<{ version: unknown; secret: unknown }>): boolean {\n return (\n secrets.length > 0 &&\n secrets.every((s, i) => s.version === i + 1 && s.secret instanceof Uint8Array && s.secret.length === WORKSPACE_SECRET_BYTES_V1)\n );\n}\n\n/** The keyring file's text, as JCS. */\nexport function serializeRecordsKeyringFileV1(secrets: ReadonlyArray<{ version: number; secret: Uint8Array }>): string {\n if (!secretsAreAKeyring(secrets)) throw new RecordsEncryptionError('RECORDS_KEY_INVALID');\n return canonicalizeJcs({\n schema: RECORDS_KEYRING_SCHEMA_V1,\n secrets: secrets.map((s) => ({ version: s.version, secret: toBase64Url(s.secret) })),\n });\n}\n\n/** Reads a keyring file: any JSON of the shape, up to 65,536 bytes. Never throws. */\nexport function parseRecordsKeyringFileV1(\n text: string,\n): { ok: true; secrets: Array<{ version: number; secret: Uint8Array }> } | RecordsRefusalV1<'RECORDS_KEYRING_MALFORMED' | 'RECORDS_KEYRING_TOO_LARGE'> {\n if (typeof text !== 'string') return refuse('RECORDS_KEYRING_MALFORMED');\n if (utf8(text).length > RECORDS_KEYRING_MAX_BYTES_V1) return refuse('RECORDS_KEYRING_TOO_LARGE');\n let doc: unknown;\n try {\n doc = JSON.parse(text);\n } catch {\n return refuse('RECORDS_KEYRING_MALFORMED');\n }\n const d = doc as Record<string, unknown>;\n if (!d || typeof d !== 'object' || Array.isArray(d) || Object.keys(d).sort().join(',') !== 'schema,secrets') return refuse('RECORDS_KEYRING_MALFORMED');\n if (d.schema !== RECORDS_KEYRING_SCHEMA_V1 || !Array.isArray(d.secrets)) return refuse('RECORDS_KEYRING_MALFORMED');\n const secrets: Array<{ version: number; secret: Uint8Array }> = [];\n for (const item of d.secrets as unknown[]) {\n const s = item as Record<string, unknown>;\n if (!s || typeof s !== 'object' || Array.isArray(s) || Object.keys(s).sort().join(',') !== 'secret,version') return refuse('RECORDS_KEYRING_MALFORMED');\n const bytes = typeof s.secret === 'string' ? fromBase64Url(s.secret) : null;\n if (!Number.isSafeInteger(s.version) || !bytes) return refuse('RECORDS_KEYRING_MALFORMED');\n secrets.push({ version: s.version as number, secret: bytes });\n }\n if (!secretsAreAKeyring(secrets)) return refuse('RECORDS_KEYRING_MALFORMED');\n return { ok: true, secrets };\n}\n", "/**\n * records-crypto: the blinded fingerprint (`hmac-sha-256`), its blinding file\n * and the held-file rule (slot-encoding-v1 sections 6.1 and 6.2). Pure, no\n * I/O. Two real HMAC implementations, picked by runtime; no caller can pick.\n */\nimport type { PayloadByteSource, PayloadRefV1 } from '../proof/payload-ref-v1';\nimport { BLINDING_VALUE_BYTES, isNodeRuntime, loadNodeCrypto } from './blinding-value';\nimport { hmacNode } from './hmac-node';\nimport { hmacWeb } from './hmac-web';\n\nexport { BLINDING_FILE_SCHEMA_V1 } from '../proof/payload-ref-v1';\nexport { BLINDING_VALUE_BYTES, BlindingError, assertBlindingValue } from './blinding-value';\nexport {\n BLINDING_FILE_MAX_BYTES,\n parseBlindingFile,\n serializeBlindingFile,\n type BlindingFileRefusal,\n type BlindingFileV1,\n type ParsedBlindingFile,\n} from './blinding-file';\nexport { matchHeldFile, type HeldFile, type HeldFileMatch } from './held-file';\nexport * from './record-hash-v2';\nexport * from './record-hash-v3';\nexport * from './record-disclosure-v1';\nexport * from './disclosure-envelope-v1';\nexport * from './wrap-shapes-v1';\nexport {\n RECORDS_ENCRYPTION_LABELS_V1,\n RECORDS_ENCRYPTION_PAD_BLOCK_V1,\n RECORD_ENTRY_PLAINTEXT_MAX_BYTES_V1,\n RECORD_ENTRY_CIPHERTEXT_MAX_BYTES_V1,\n RECORD_ENTRY_CIPHERTEXT_MAX_CHARS_V1,\n RECORD_ENTRY_BODY_MAX_BYTES_V1,\n RECORDS_KEYRING_MAX_BYTES_V1,\n RECORDS_KEYRING_SCHEMA_V1,\n WORKSPACE_SECRET_BYTES_V1,\n RecordsEncryptionError,\n RecordsIdKeyV1,\n RecordsKeyV1,\n RecordsWrapKeyV1,\n RecordKeyV1,\n RecordsContentTagKeyV2,\n RECORDS_CONTENT_TAG_LABELS_V2,\n RecordsKeyringV1,\n exportKeyBytesV1,\n generateWorkspaceSecretV1,\n deriveRecordsIdKeyV1,\n deriveRecordsKeysV1,\n importWorkspaceSecretKeyV1,\n deriveRecordsIdKeyFromBaseV1,\n deriveRecordsKeysFromBaseV1,\n recordKeyOfV1,\n recordKeyFromBytesV1,\n recordsKeyFromBytesV1,\n wireRecordIdV1,\n wireReferenceIdV1,\n blindedLabelV1,\n contentTagV1,\n contentTagV2,\n recordEntryPlaintextV1,\n padRecordEntryV1,\n sealRecordEntryV1,\n readRecordEnvelopeShapeV1,\n openRecordEntryEnvelopeV1,\n encryptedWriteBodyBytesV1,\n checkEncryptedWriteSizeV1,\n entryRefsMatchV1,\n localRecordsKeyProviderV1,\n serializeRecordsKeyringFileV1,\n parseRecordsKeyringFileV1,\n type RecordsEncryptionCodeV1,\n type RecordsRefusalV1,\n type RecordEntryEnvelopeV1,\n type OpenRecordEntryResultV1,\n type RecordsKeyProviderV1,\n type RecordsBaseKeyProviderV1,\n} from './records-encryption-v1';\n\n/**\n * `node:crypto` when the runtime says Node and the module loads; otherwise\n * null, and WebCrypto is used (as digestPayload falls back).\n */\nasync function nodeCryptoOrNull(): Promise<typeof import('node:crypto') | null> {\n if (!isNodeRuntime()) return null;\n try {\n return await loadNodeCrypto();\n } catch {\n return null;\n }\n}\n\n/** HMAC-SHA256 of the source's bytes under a 32-byte blinding value, as a payload reference. */\nexport async function blindedDigest(source: PayloadByteSource, value: Uint8Array): Promise<PayloadRefV1> {\n return ((await nodeCryptoOrNull()) ? hmacNode : hmacWeb).blindedDigest(source, value);\n}\n\n/** 32 fresh random bytes. */\nexport async function newBlindingValue(): Promise<Uint8Array> {\n const nodeCrypto = await nodeCryptoOrNull();\n if (nodeCrypto) return new Uint8Array(nodeCrypto.randomBytes(BLINDING_VALUE_BYTES));\n return globalThis.crypto.getRandomValues(new Uint8Array(BLINDING_VALUE_BYTES));\n}\n", "/**\n * `signed-acknowledgment/v2` (ADR 0015 question C; the L2a2 formats in its\n * note, N12): an acknowledgment signed twice over the same canonical body,\n * once with ES256 and once with ML-DSA-65, both required. The key id names\n * the pair, and the body carries it, so neither signature can be lifted onto\n * another key's half.\n *\n * Like v1 this module holds only what the browser, the SDK and the API must\n * agree on byte for byte. It loads no signing library: the API verifies with\n * its platform (L2-2), and signing lives behind records-crypto's asymmetric\n * subpath.\n */\nimport { fromBase64Url } from '../records-crypto/base64url';\nimport { concatBytes, sha256, utf8 } from '../records-crypto/platform-crypto';\nimport type { AcknowledgmentSignedBodyV1, SigningPublicKeyJwkV1 } from './signed-acknowledgment-v1';\n\nexport const SIGNED_ACKNOWLEDGMENT_ALGS_V2 = ['ES256', 'ML-DSA-65'] as const;\nexport const ACKNOWLEDGMENT_KEY_ID_LABEL_V2 = 'pacspace:ack-key-id:v1';\nexport const MLDSA65_PUBLIC_KEY_BYTES = 1952;\nexport const MLDSA65_SIGNATURE_BYTES = 3309;\nexport const ES256_PUBLIC_POINT_BYTES = 65;\n\n/** Fields of a v2 acknowledgment that both signatures cover: v1's, and the pair's key id. */\nexport interface AcknowledgmentSignedBodyV2 extends AcknowledgmentSignedBodyV1 {\n /** 64 lowercase hex: acknowledgmentKeyIdV2 of the two public keys. */\n keyId: string;\n}\n\n/** Canonical JSON in the fixed member order below, as v1 writes it. */\nexport function canonicalAcknowledgmentBodyV2(body: AcknowledgmentSignedBodyV2): string {\n return JSON.stringify({\n v: 2,\n kind: 'acknowledgment',\n handle: body.handle,\n seq: body.seq,\n matched: body.matched,\n missing: body.missing,\n historyDigest: body.historyDigest.toLowerCase(),\n signedAt: body.signedAt,\n keyId: body.keyId.toLowerCase(),\n });\n}\n\n/** The P-256 public key as its 65-byte uncompressed point, or null if the JWK is not one. */\nexport function es256PublicPointV1(key: SigningPublicKeyJwkV1): Uint8Array | null {\n if (!key || key.kty !== 'EC' || key.crv !== 'P-256') return null;\n const x = typeof key.x === 'string' ? fromBase64Url(key.x) : null;\n const y = typeof key.y === 'string' ? fromBase64Url(key.y) : null;\n if (!x || !y || x.length !== 32 || y.length !== 32) return null;\n return concatBytes(new Uint8Array([4]), x, y);\n}\n\nconst hex = (bytes: Uint8Array) => Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\n\n/**\n * `SHA-256(\"pacspace:ack-key-id:v1\" || 0x00 || P-256 point || 0x00 || ML-DSA-65\n * public key)`, 64 lowercase hex; null when either key has the wrong form.\n * Carried as `actorId`.\n */\nexport async function acknowledgmentKeyIdV2(es256: SigningPublicKeyJwkV1, mldsaPublicKey: Uint8Array): Promise<string | null> {\n const point = es256PublicPointV1(es256);\n if (!point || !(mldsaPublicKey instanceof Uint8Array) || mldsaPublicKey.length !== MLDSA65_PUBLIC_KEY_BYTES) return null;\n const sep = new Uint8Array([0]);\n return hex(await sha256(concatBytes(utf8(ACKNOWLEDGMENT_KEY_ID_LABEL_V2), sep, point, sep, mldsaPublicKey)));\n}\n", "import { MLDSA65_PUBLIC_KEY_BYTES, MLDSA65_SIGNATURE_BYTES } from '../../records/signed-acknowledgment-v2';\nimport { fromBase64Url, toBase64Url } from '../base64url';\nimport { concatBytes, hmacSha256, platformCrypto, randomBytes, sha256, utf8 } from '../platform-crypto';\nimport {\n RecordKeyV1,\n RecordsEncryptionError,\n RecordsKeyV1,\n RecordsKeyringV1,\n RecordsWrapKeyV1,\n exportKeyBytesV1,\n recordKeyFromBytesV1,\n recordsKeyFromBytesV1,\n type RecordsRefusalV1,\n} from '../records-encryption-v1';\nimport {\n KEY_WRAP_CT_BYTES_V1,\n KEY_WRAP_ENC_BYTES_V1,\n KEY_WRAP_SUITE_V1,\n PUBLIC_KEY_ID_LABEL_V1,\n SEED_WRAP_CT_BYTES_V1,\n WORKSPACE_PUBLIC_KEY_BYTES_V1,\n readKeyWrapShapeV1,\n readKeyWrapShapeV2,\n readSeedWrapShapeV1,\n workspacePublicKeyIdV1,\n} from '../wrap-shapes-v1';\n\nexport {\n KEY_WRAP_CT_BYTES_V1,\n KEY_WRAP_ENC_BYTES_V1,\n KEY_WRAP_SUITE_V1,\n SEED_WRAP_CT_BYTES_V1,\n WORKSPACE_PUBLIC_KEY_BYTES_V1,\n readKeyWrapShapeV1,\n readKeyWrapShapeV2,\n readSeedWrapShapeV1,\n};\n\n/**\n * Level 2's asymmetric layer (ADR 0015 sections 4, 5 and 11; formats note N3,\n * N9 and N12): the workspace keypair from a 32-byte seed our code draws, the\n * seed's wrap under `W_v`, the public key id and the holder key code, wraps\n * to a holder under the suite `hpke-1`, and ML-DSA-65 signing.\n *\n * This file is reached only through the `records-crypto/asymmetric` subpath,\n * which shared's index does not re-export, and it loads `hpke`,\n * `@panva/hpke-noble` and `@noble/post-quantum` by dynamic import on first\n * use, so the API, worker and indexer load none of them.\n *\n * No seed or private key is ever printed: those types keep their bytes in a\n * module WeakMap. Refusals carry a code and no sentence; nothing here logs.\n */\nexport const RECORDS_ASYMMETRIC_LABELS_V1 = {\n publicKeyId: PUBLIC_KEY_ID_LABEL_V1,\n holderKeyCode: 'pacspace:holder-key-code:v1',\n seedWrap: 'pacspace:seed-wrap:v1',\n wrap: 'pacspace:wrap:v1',\n wrapV2: 'pacspace:wrap:v2',\n identityRotation: 'pacspace:identity-rotation:v1',\n} as const;\n\n/** The one wrap suite: HPKE base mode, MLKEM768-X25519 as draft-ietf-hpke-pq-05 fixes it, HKDF-SHA256, AES-256-GCM. */\nexport const KEY_WRAP_SUITES_V1 = {\n 'hpke-1': { kem: 0x647a, kdf: 0x0001, aead: 0x0002, draft: 'draft-ietf-hpke-pq-05' },\n} as const;\nexport const WORKSPACE_SEED_BYTES_V1 = 32;\nexport const MLDSA65_SEED_BYTES_V1 = 32;\nexport const HOLDER_KEY_CODE_DIGITS_V1 = 40;\n\nexport type KeyWrapPurposeV1 = 'records-key' | 'record-key' | 'disclosure-key';\n\nexport type RecordsAsymmetricCodeV1 =\n | 'WORKSPACE_SEED_INVALID'\n | 'WORKSPACE_PUBLIC_KEY_INVALID'\n | 'SEED_WRAP_MALFORMED'\n | 'SEED_WRAP_WRONG_KEY'\n | 'SEED_WRAP_AUTH_FAILED'\n | 'KEY_WRAP_MALFORMED'\n | 'KEY_WRAP_SUITE'\n | 'KEY_WRAP_WRONG_HOLDER'\n | 'KEY_WRAP_AUTH_FAILED'\n | 'KEY_WRAP_KEY_MISMATCH'\n | 'KEY_WRAP_BINDING_INVALID'\n | 'MLDSA_KEY_INVALID'\n | 'ROTATION_BINDING_INVALID'\n | 'ROTATION_CHALLENGE_MALFORMED';\n\n/** Thrown by the writing side only; its message is the code. */\nexport class RecordsAsymmetricError extends Error {\n constructor(readonly code: RecordsAsymmetricCodeV1) {\n super(code);\n this.name = 'RecordsAsymmetricError';\n }\n}\n\nconst refuse = <C extends string>(code: C): RecordsRefusalV1<C> => ({ ok: false, code });\n\nconst SEP = new Uint8Array([0]);\nconst HEX64 = /^[0-9a-f]{64}$/;\nconst WIRE_ID = /^[A-Za-z0-9_-]{22}$/;\nconst IV_BYTES = 12;\nconst INSPECT = Symbol.for('nodejs.util.inspect.custom');\nconst L = RECORDS_ASYMMETRIC_LABELS_V1;\nconst SUITE = KEY_WRAP_SUITES_V1[KEY_WRAP_SUITE_V1];\n\nconst unhex = (text: string) => Uint8Array.from(text.match(/../g) ?? [], (h) => parseInt(h, 16));\n\n// ------------------------------------------------------------------ the pinned libraries, loaded on first use\n\ntype Libraries = {\n hpke: typeof import('hpke');\n noble: typeof import('@panva/hpke-noble');\n hybrid: typeof import('@noble/post-quantum/hybrid.js');\n mldsa: typeof import('@noble/post-quantum/ml-dsa.js');\n};\n\nlet libraries: Promise<Libraries> | null = null;\n\nfunction load(): Promise<Libraries> {\n libraries ??= Promise.all([\n import('hpke'),\n import('@panva/hpke-noble'),\n import('@noble/post-quantum/hybrid.js'),\n import('@noble/post-quantum/ml-dsa.js'),\n ]).then(([hpke, noble, hybrid, mldsa]) => ({ hpke, noble, hybrid, mldsa }));\n return libraries;\n}\n\n/** @internal The pinned libraries, for the draft's vectors; untyped so no declaration names them. */\nexport function loadRecordsAsymmetricLibrariesV1(): Promise<unknown> {\n return load();\n}\n\n/** @internal The wrap suite's KDF and AEAD factories: hpke's, which run on the platform's WebCrypto. */\nexport async function keyWrapSuiteFactoriesV1(): Promise<unknown> {\n const { hpke } = await load();\n return { kdf: hpke.KDF_HKDF_SHA256, aead: hpke.AEAD_AES_256_GCM };\n}\n\nasync function wrapSuite(ikmE?: Uint8Array) {\n const { hpke, noble, hybrid } = await load();\n const kem = ikmE\n ? () => {\n const base = noble.KEM_MLKEM768_X25519();\n return {\n ...base,\n DeriveKeyPair: base.DeriveKeyPair.bind(base),\n GenerateKeyPair: base.GenerateKeyPair.bind(base),\n SerializePublicKey: base.SerializePublicKey.bind(base),\n DeserializePublicKey: base.DeserializePublicKey.bind(base),\n SerializePrivateKey: base.SerializePrivateKey.bind(base),\n DeserializePrivateKey: base.DeserializePrivateKey.bind(base),\n Decap: base.Decap.bind(base),\n async Encap(pkR: Parameters<typeof base.Encap>[0]) {\n const { cipherText, sharedSecret } = hybrid.ml_kem768_x25519.encapsulate(await base.SerializePublicKey(pkR), ikmE);\n return { shared_secret: sharedSecret, enc: cipherText };\n },\n };\n }\n : noble.KEM_MLKEM768_X25519;\n const suite = new hpke.CipherSuite(kem, hpke.KDF_HKDF_SHA256, hpke.AEAD_AES_256_GCM);\n if (suite.KEM.id !== SUITE.kem || suite.KDF.id !== SUITE.kdf || suite.AEAD.id !== SUITE.aead) {\n throw new RecordsAsymmetricError('KEY_WRAP_SUITE');\n }\n return suite;\n}\n\n// ------------------------------------------------------------------ hidden key types\n\nconst HELD = new WeakMap<object, Uint8Array>();\n\nabstract class HiddenKey {\n protected constructor(bytes: Uint8Array) {\n HELD.set(this, Uint8Array.from(bytes));\n }\n protected abstract describe(): string;\n toString(): string {\n return this.describe();\n }\n toJSON(): string {\n return this.describe();\n }\n [INSPECT](): string {\n return this.describe();\n }\n}\n\nfunction heldBytes(key: HiddenKey, code: RecordsAsymmetricCodeV1): Uint8Array {\n const bytes = HELD.get(key);\n if (!bytes) throw new RecordsAsymmetricError(code);\n return bytes;\n}\n\n/** The workspace's private seed, with the X-Wing public key it makes. */\nexport class WorkspaceSeedV1 extends HiddenKey {\n readonly #publicKey: Uint8Array;\n /** @internal */\n constructor(seed: Uint8Array, publicKey: Uint8Array, readonly publicKeyId: string) {\n super(seed);\n this.#publicKey = Uint8Array.from(publicKey);\n }\n /** The encoded public key (1,216 bytes): the ML-KEM-768 key, then the X25519 key. */\n get publicKey(): Uint8Array {\n return Uint8Array.from(this.#publicKey);\n }\n protected describe(): string {\n return `[workspace seed ${this.publicKeyId.slice(0, 8)}]`;\n }\n}\n\n/** An ML-DSA-65 signing key, made from a 32-byte seed. */\nexport class MldsaSigningKeyV1 extends HiddenKey {\n readonly #publicKey: Uint8Array;\n /** @internal */\n constructor(seed: Uint8Array, publicKey: Uint8Array) {\n super(seed);\n this.#publicKey = Uint8Array.from(publicKey);\n }\n get publicKey(): Uint8Array {\n return Uint8Array.from(this.#publicKey);\n }\n protected describe(): string {\n return '[ML-DSA-65 signing key]';\n }\n}\n\n/**\n * The seed's 32 bytes, for the two places they may leave the key layer: the\n * seed wrap and the published vectors.\n */\nexport function exportWorkspaceSeedBytesV1(seed: WorkspaceSeedV1): Uint8Array {\n return Uint8Array.from(heldBytes(seed, 'WORKSPACE_SEED_INVALID'));\n}\n\n// ------------------------------------------------------------------ the workspace keypair, its id and code (N3, section 7)\n\nfunction assertPublicKey(publicKey: Uint8Array): void {\n if (!(publicKey instanceof Uint8Array) || publicKey.length !== WORKSPACE_PUBLIC_KEY_BYTES_V1) {\n throw new RecordsAsymmetricError('WORKSPACE_PUBLIC_KEY_INVALID');\n }\n}\n\n/** `SHA-256(\"pacspace:public-key-id:v1\" || 0x00 || encoded public key)`, 64 lowercase hex. */\nexport async function publicKeyIdV1(publicKey: Uint8Array): Promise<string> {\n assertPublicKey(publicKey);\n return (await workspacePublicKeyIdV1(publicKey))!;\n}\n\n/**\n * The holder key code: the first 17 bytes of `SHA-256(\"pacspace:holder-key-code:v1\"\n * || 0x00 || encoded public key)` as an unsigned big-endian integer, modulo\n * 10^40, 40 digits with leading zeros in eight groups of five.\n */\nexport async function holderKeyCodeV1(publicKey: Uint8Array): Promise<string> {\n assertPublicKey(publicKey);\n const digest = await sha256(concatBytes(utf8(L.holderKeyCode), SEP, publicKey));\n let n = 0n;\n for (const byte of digest.subarray(0, 17)) n = (n << 8n) | BigInt(byte);\n const digits = (n % 10n ** 40n).toString().padStart(HOLDER_KEY_CODE_DIGITS_V1, '0');\n return digits.match(/.{5}/g)!.join(' ');\n}\n\n/** The keypair the 32-byte seed makes, as draft-ietf-hpke-pq-05's MLKEM768-X25519 derives it. */\nexport async function workspaceSeedFromBytesV1(seed: Uint8Array): Promise<WorkspaceSeedV1> {\n if (!(seed instanceof Uint8Array) || seed.length !== WORKSPACE_SEED_BYTES_V1) throw new RecordsAsymmetricError('WORKSPACE_SEED_INVALID');\n const { hybrid } = await load();\n const { publicKey } = hybrid.ml_kem768_x25519.keygen(Uint8Array.from(seed));\n return new WorkspaceSeedV1(seed, publicKey, await publicKeyIdV1(publicKey));\n}\n\n/** A new workspace keypair from 32 random bytes this code draws (not the library's key generation). */\nexport async function generateWorkspaceSeedV1(): Promise<WorkspaceSeedV1> {\n return workspaceSeedFromBytesV1(randomBytes(WORKSPACE_SEED_BYTES_V1));\n}\n\n// ------------------------------------------------------------------ the seed wrap under W_v (N9)\n\nexport interface SeedWrapV1 {\n v: 1;\n alg: 'A256GCM';\n kid: string;\n iv: string;\n ct: string;\n}\n\nconst seedWrapAad = (publicKeyId: string) => concatBytes(utf8(L.seedWrap), SEP, unhex(publicKeyId)) as BufferSource;\n\nasync function aesKey(key: Uint8Array, usage: 'encrypt' | 'decrypt'): Promise<CryptoKey> {\n const { subtle } = await platformCrypto();\n return subtle.importKey('raw', Uint8Array.from(key), { name: 'AES-GCM' }, false, [usage]);\n}\n\n/** @internal Seals the seed under a given IV; vectors and the seal below only. */\nexport async function sealSeedWrapWithIvV1(wrapKey: RecordsWrapKeyV1, seed: WorkspaceSeedV1, iv: Uint8Array): Promise<SeedWrapV1> {\n if (!(wrapKey instanceof RecordsWrapKeyV1) || !(seed instanceof WorkspaceSeedV1) || !(iv instanceof Uint8Array) || iv.length !== IV_BYTES) {\n throw new RecordsAsymmetricError('WORKSPACE_SEED_INVALID');\n }\n const { subtle } = await platformCrypto();\n const ct = new Uint8Array(\n await subtle.encrypt(\n { name: 'AES-GCM', iv: Uint8Array.from(iv), additionalData: seedWrapAad(seed.publicKeyId), tagLength: 128 },\n await aesKey(exportKeyBytesV1(wrapKey), 'encrypt'),\n Uint8Array.from(heldBytes(seed, 'WORKSPACE_SEED_INVALID')),\n ),\n );\n return { v: 1, alg: 'A256GCM', kid: wrapKey.id, iv: toBase64Url(iv), ct: toBase64Url(ct) };\n}\n\n/** The seed, sealed for storage at PacSpace under `W_v` with a fresh IV. */\nexport async function sealSeedWrapV1(wrapKey: RecordsWrapKeyV1, seed: WorkspaceSeedV1): Promise<SeedWrapV1> {\n return sealSeedWrapWithIvV1(wrapKey, seed, randomBytes(IV_BYTES));\n}\n\n/**\n * Opens a seed wrap with `W_v`, or with a keyring (whose `W_v` named by\n * `kid` opens it), for the public key id it was stored under. Never throws.\n */\nexport async function openSeedWrapV1(input: {\n wrap: unknown;\n publicKeyId: string;\n wrapKey?: RecordsWrapKeyV1;\n keyring?: RecordsKeyringV1;\n}): Promise<{ ok: true; seed: WorkspaceSeedV1 } | RecordsRefusalV1<'SEED_WRAP_MALFORMED' | 'SEED_WRAP_WRONG_KEY' | 'SEED_WRAP_AUTH_FAILED'>> {\n try {\n const shape = readSeedWrapShapeV1(input?.wrap);\n if (!shape.ok) return shape;\n if (typeof input.publicKeyId !== 'string' || !HEX64.test(input.publicKeyId)) return refuse('SEED_WRAP_MALFORMED');\n let key = input.wrapKey;\n if (input.keyring) key = input.keyring.versions.map((v) => input.keyring!.wrapKey(v)).find((k) => k?.id === shape.kid) ?? undefined;\n if (!(key instanceof RecordsWrapKeyV1) || key.id !== shape.kid) return refuse('SEED_WRAP_WRONG_KEY');\n let seed: Uint8Array;\n try {\n const { subtle } = await platformCrypto();\n seed = new Uint8Array(\n await subtle.decrypt(\n { name: 'AES-GCM', iv: Uint8Array.from(shape.iv), additionalData: seedWrapAad(input.publicKeyId), tagLength: 128 },\n await aesKey(exportKeyBytesV1(key), 'decrypt'),\n Uint8Array.from(shape.ct),\n ),\n );\n } catch {\n return refuse('SEED_WRAP_AUTH_FAILED');\n }\n const made = await workspaceSeedFromBytesV1(seed);\n if (made.publicKeyId !== input.publicKeyId) return refuse('SEED_WRAP_AUTH_FAILED');\n return { ok: true, seed: made };\n } catch {\n return refuse('SEED_WRAP_AUTH_FAILED');\n }\n}\n\n// ------------------------------------------------------------------ wraps to a holder (N9)\n\nexport interface KeyWrapV1 {\n v: 1;\n suite: typeof KEY_WRAP_SUITE_V1;\n to: string;\n enc: string;\n ct: string;\n}\n\n/** The binding each purpose hashes into `info`. */\nexport type KeyWrapBindingV1 =\n | { purpose: 'records-key'; recordsKeyId: string }\n | { purpose: 'record-key'; recordType: string; wireRecordId: string }\n | { purpose: 'disclosure-key'; handle: string };\n\nconst PRINTABLE_ASCII = /^[\\x21-\\x7e]+$/;\n\nfunction bindingBytes(binding: KeyWrapBindingV1): Uint8Array {\n switch (binding?.purpose) {\n case 'records-key':\n if (typeof binding.recordsKeyId === 'string' && HEX64.test(binding.recordsKeyId)) return unhex(binding.recordsKeyId);\n break;\n case 'record-key':\n if (typeof binding.recordType === 'string' && PRINTABLE_ASCII.test(binding.recordType) && typeof binding.wireRecordId === 'string' && WIRE_ID.test(binding.wireRecordId)) {\n return concatBytes(utf8(binding.recordType), SEP, utf8(binding.wireRecordId));\n }\n break;\n case 'disclosure-key':\n if (typeof binding.handle === 'string' && PRINTABLE_ASCII.test(binding.handle)) return utf8(binding.handle);\n break;\n }\n throw new RecordsAsymmetricError('KEY_WRAP_BINDING_INVALID');\n}\n\n/** `\"pacspace:wrap:v1\" || 0x00 || purpose || 0x00 || SHA-256(binding)`, at most 64 bytes. */\nexport async function keyWrapInfoV1(binding: KeyWrapBindingV1): Promise<Uint8Array> {\n const bytes = bindingBytes(binding);\n return concatBytes(utf8(L.wrap), SEP, utf8(binding.purpose), SEP, await sha256(bytes));\n}\n\n/** @internal Seals 32 key bytes to a public key; `ikmE` fixes the encapsulation for vectors only. */\nexport async function sealKeyWrapV1(input: {\n publicKey: Uint8Array;\n binding: KeyWrapBindingV1;\n keyBytes: Uint8Array;\n ikmE?: Uint8Array;\n}): Promise<KeyWrapV1> {\n const sealed = await sealUnder(input.publicKey, input.keyBytes, () => keyWrapInfoV1(input.binding), input.ikmE);\n return { v: 1, ...sealed };\n}\n\nasync function sealUnder(publicKey: Uint8Array, keyBytes: Uint8Array, infoOf: () => Promise<Uint8Array>, ikmE?: Uint8Array) {\n const input = { publicKey, keyBytes, ikmE };\n assertPublicKey(input.publicKey);\n if (!(input.keyBytes instanceof Uint8Array) || input.keyBytes.length !== 32) throw new RecordsAsymmetricError('KEY_WRAP_BINDING_INVALID');\n const info = await infoOf();\n const suite = await wrapSuite(input.ikmE);\n const pk = await suite.DeserializePublicKey(Uint8Array.from(input.publicKey));\n const { encapsulatedSecret, ciphertext } = await suite.Seal(pk, Uint8Array.from(input.keyBytes), { info });\n return { suite: KEY_WRAP_SUITE_V1, to: await publicKeyIdV1(input.publicKey), enc: toBase64Url(encapsulatedSecret), ct: toBase64Url(ciphertext) };\n}\n\n/** `K_v`, wrapped to a workspace-scope holder's confirmed public key. */\nexport async function wrapRecordsKeyV1(publicKey: Uint8Array, recordsKey: RecordsKeyV1): Promise<KeyWrapV1> {\n if (!(recordsKey instanceof RecordsKeyV1)) throw new RecordsEncryptionError('RECORDS_KEY_INVALID');\n return sealKeyWrapV1({ publicKey, binding: { purpose: 'records-key', recordsKeyId: recordsKey.id }, keyBytes: exportKeyBytesV1(recordsKey) });\n}\n\n/** One record's `RK`, wrapped to a record-scope holder or a counterparty. */\nexport async function wrapRecordKeyV1(\n publicKey: Uint8Array,\n recordKey: RecordKeyV1,\n record: { recordType: string; wireRecordId: string },\n): Promise<KeyWrapV1> {\n if (!(recordKey instanceof RecordKeyV1)) throw new RecordsEncryptionError('RECORDS_KEY_INVALID');\n return sealKeyWrapV1({\n publicKey,\n binding: { purpose: 'record-key', recordType: record?.recordType, wireRecordId: record?.wireRecordId },\n keyBytes: exportKeyBytesV1(recordKey),\n });\n}\n\n/** A disclosure key, wrapped to a reader's confirmed public key. */\nexport async function wrapDisclosureKeyV1(publicKey: Uint8Array, disclosureKey: Uint8Array, handle: string): Promise<KeyWrapV1> {\n return sealKeyWrapV1({ publicKey, binding: { purpose: 'disclosure-key', handle }, keyBytes: disclosureKey });\n}\n\ntype UnwrapRefusal = RecordsRefusalV1<'KEY_WRAP_MALFORMED' | 'KEY_WRAP_SUITE' | 'KEY_WRAP_WRONG_HOLDER' | 'KEY_WRAP_AUTH_FAILED' | 'KEY_WRAP_BINDING_INVALID'>;\n\nasync function openKeyWrap(seed: WorkspaceSeedV1, wrap: unknown, binding: KeyWrapBindingV1): Promise<{ ok: true; keyBytes: Uint8Array } | UnwrapRefusal> {\n return openKeyWrapAs(seed, readKeyWrapShapeV1(wrap), () => keyWrapInfoV1(binding));\n}\n\nasync function openKeyWrapAs(\n seed: WorkspaceSeedV1,\n shape: ReturnType<typeof readKeyWrapShapeV1>,\n infoOf: () => Promise<Uint8Array>,\n): Promise<{ ok: true; keyBytes: Uint8Array } | UnwrapRefusal> {\n if (!shape.ok) return shape;\n if (!(seed instanceof WorkspaceSeedV1)) return refuse('KEY_WRAP_WRONG_HOLDER');\n if (shape.to !== seed.publicKeyId) return refuse('KEY_WRAP_WRONG_HOLDER');\n let info: Uint8Array;\n try {\n info = await infoOf();\n } catch {\n return refuse('KEY_WRAP_BINDING_INVALID');\n }\n try {\n const suite = await wrapSuite();\n const privateKey = await suite.DeserializePrivateKey(Uint8Array.from(heldBytes(seed, 'WORKSPACE_SEED_INVALID')), false);\n const publicKey = await suite.DeserializePublicKey(seed.publicKey);\n const keyBytes = await suite.Open({ privateKey, publicKey }, shape.enc, shape.ct, { info });\n if (keyBytes.length !== 32) return refuse('KEY_WRAP_AUTH_FAILED');\n return { ok: true, keyBytes };\n } catch {\n return refuse('KEY_WRAP_AUTH_FAILED');\n }\n}\n\n/**\n * `K_v` from a wrap. The expected id comes from the wrap's stored key\n * version; it is recomputed from the unwrapped bytes before use. Never throws.\n */\nexport async function unwrapRecordsKeyV1(input: {\n seed: WorkspaceSeedV1;\n wrap: unknown;\n version: number;\n recordsKeyId: string;\n}): Promise<{ ok: true; recordsKey: RecordsKeyV1 } | UnwrapRefusal | RecordsRefusalV1<'KEY_WRAP_KEY_MISMATCH'>> {\n try {\n if (!Number.isSafeInteger(input?.version) || input.version < 1) return refuse('KEY_WRAP_BINDING_INVALID');\n const opened = await openKeyWrap(input.seed, input.wrap, { purpose: 'records-key', recordsKeyId: input.recordsKeyId });\n if (!opened.ok) return opened;\n const recordsKey = await recordsKeyFromBytesV1(opened.keyBytes, input.version);\n if (recordsKey.id !== input.recordsKeyId) return refuse('KEY_WRAP_KEY_MISMATCH');\n return { ok: true, recordsKey };\n } catch {\n return refuse('KEY_WRAP_AUTH_FAILED');\n }\n}\n\n/** One record's `RK` from a wrap. Never throws. */\nexport async function unwrapRecordKeyV1(input: {\n seed: WorkspaceSeedV1;\n wrap: unknown;\n recordType: string;\n wireRecordId: string;\n}): Promise<{ ok: true; recordKey: RecordKeyV1 } | UnwrapRefusal> {\n try {\n const opened = await openKeyWrap(input.seed, input.wrap, { purpose: 'record-key', recordType: input?.recordType, wireRecordId: input?.wireRecordId });\n if (!opened.ok) return opened;\n return { ok: true, recordKey: await recordKeyFromBytesV1(opened.keyBytes) };\n } catch {\n return refuse('KEY_WRAP_AUTH_FAILED');\n }\n}\n\n/** A disclosure key from a wrap. Never throws. */\nexport async function unwrapDisclosureKeyV1(input: {\n seed: WorkspaceSeedV1;\n wrap: unknown;\n handle: string;\n}): Promise<{ ok: true; disclosureKey: Uint8Array } | UnwrapRefusal> {\n try {\n const opened = await openKeyWrap(input.seed, input.wrap, { purpose: 'disclosure-key', handle: input?.handle });\n if (!opened.ok) return opened;\n return { ok: true, disclosureKey: opened.keyBytes };\n } catch {\n return refuse('KEY_WRAP_AUTH_FAILED');\n }\n}\n\n// ------------------------------------------------------------------ wraps v2 (card 10, F3)\n\n/**\n * A wrap v2 binds who the key belongs to: the owner workspace's id, and for\n * `K_v` its version, for a record's `RK` its own id. A wrap made for another\n * owner, version or record key does not open. Only v2 is stored or opened.\n */\nexport interface KeyWrapV2 {\n v: 2;\n suite: typeof KEY_WRAP_SUITE_V1;\n to: string;\n enc: string;\n ct: string;\n}\n\nexport type KeyWrapBindingV2 =\n | { purpose: 'records-key'; owner: string; version: number; recordsKeyId: string }\n | { purpose: 'record-key'; owner: string; recordType: string; wireRecordId: string; recordKeyId: string }\n | { purpose: 'disclosure-key'; owner: string; handle: string };\n\n/** A workspace id as PacSpace makes them (cuid): checked before it is hashed. */\nexport const KEY_WRAP_OWNER_V2 = /^[a-z0-9]{20,32}$/;\n\nfunction bindingBytesV2(binding: KeyWrapBindingV2): Uint8Array {\n if (typeof binding?.owner !== 'string' || !KEY_WRAP_OWNER_V2.test(binding.owner)) throw new RecordsAsymmetricError('KEY_WRAP_BINDING_INVALID');\n const owner = utf8(binding.owner);\n switch (binding.purpose) {\n case 'records-key':\n if (Number.isInteger(binding.version) && binding.version >= 1 && binding.version <= 0xffff && typeof binding.recordsKeyId === 'string' && HEX64.test(binding.recordsKeyId)) {\n return concatBytes(owner, SEP, new Uint8Array([binding.version >> 8, binding.version & 0xff]), unhex(binding.recordsKeyId));\n }\n break;\n case 'record-key':\n if (\n typeof binding.recordType === 'string' &&\n PRINTABLE_ASCII.test(binding.recordType) &&\n typeof binding.wireRecordId === 'string' &&\n WIRE_ID.test(binding.wireRecordId) &&\n typeof binding.recordKeyId === 'string' &&\n HEX64.test(binding.recordKeyId)\n ) {\n return concatBytes(owner, SEP, utf8(binding.recordType), SEP, utf8(binding.wireRecordId), SEP, unhex(binding.recordKeyId));\n }\n break;\n case 'disclosure-key':\n if (typeof binding.handle === 'string' && PRINTABLE_ASCII.test(binding.handle)) return concatBytes(owner, SEP, utf8(binding.handle));\n break;\n }\n throw new RecordsAsymmetricError('KEY_WRAP_BINDING_INVALID');\n}\n\n/** `\"pacspace:wrap:v2\" || 0x00 || purpose || 0x00 || SHA-256(binding)`, at most 64 bytes. */\nexport async function keyWrapInfoV2(binding: KeyWrapBindingV2): Promise<Uint8Array> {\n const bytes = bindingBytesV2(binding);\n return concatBytes(utf8(L.wrapV2), SEP, utf8(binding.purpose), SEP, await sha256(bytes));\n}\n\n/** @internal Seals 32 key bytes to a public key as a wrap v2; `ikmE` fixes the encapsulation for vectors only. */\nexport async function sealKeyWrapV2(input: { publicKey: Uint8Array; binding: KeyWrapBindingV2; keyBytes: Uint8Array; ikmE?: Uint8Array }): Promise<KeyWrapV2> {\n const sealed = await sealUnder(input.publicKey, input.keyBytes, () => keyWrapInfoV2(input.binding), input.ikmE);\n return { v: 2, ...sealed };\n}\n\n/** `K_v`, wrapped to a workspace-scope holder of `owner`'s records. */\nexport async function wrapRecordsKeyV2(publicKey: Uint8Array, recordsKey: RecordsKeyV1, owner: string): Promise<KeyWrapV2> {\n if (!(recordsKey instanceof RecordsKeyV1)) throw new RecordsEncryptionError('RECORDS_KEY_INVALID');\n return sealKeyWrapV2({\n publicKey,\n binding: { purpose: 'records-key', owner, version: recordsKey.version, recordsKeyId: recordsKey.id },\n keyBytes: exportKeyBytesV1(recordsKey),\n });\n}\n\n/** One of `owner`'s records' `RK`, wrapped to a record-scope holder or a counterparty. */\nexport async function wrapRecordKeyV2(\n publicKey: Uint8Array,\n recordKey: RecordKeyV1,\n record: { recordType: string; wireRecordId: string },\n owner: string,\n): Promise<KeyWrapV2> {\n if (!(recordKey instanceof RecordKeyV1)) throw new RecordsEncryptionError('RECORDS_KEY_INVALID');\n return sealKeyWrapV2({\n publicKey,\n binding: { purpose: 'record-key', owner, recordType: record?.recordType, wireRecordId: record?.wireRecordId, recordKeyId: recordKey.id },\n keyBytes: exportKeyBytesV1(recordKey),\n });\n}\n\n/** A disclosure key `owner` made, wrapped to a reader's confirmed public key. */\nexport async function wrapDisclosureKeyV2(publicKey: Uint8Array, disclosureKey: Uint8Array, handle: string, owner: string): Promise<KeyWrapV2> {\n return sealKeyWrapV2({ publicKey, binding: { purpose: 'disclosure-key', owner, handle }, keyBytes: disclosureKey });\n}\n\nconst openKeyWrapV2 = (seed: WorkspaceSeedV1, wrap: unknown, binding: KeyWrapBindingV2) =>\n openKeyWrapAs(seed, readKeyWrapShapeV2(wrap), () => keyWrapInfoV2(binding));\n\n/** `K_v` of `owner` from a wrap v2, its id recomputed from the bytes. Never throws. */\nexport async function unwrapRecordsKeyV2(input: {\n seed: WorkspaceSeedV1;\n wrap: unknown;\n owner: string;\n version: number;\n recordsKeyId: string;\n}): Promise<{ ok: true; recordsKey: RecordsKeyV1 } | UnwrapRefusal | RecordsRefusalV1<'KEY_WRAP_KEY_MISMATCH'>> {\n try {\n const opened = await openKeyWrapV2(input.seed, input.wrap, {\n purpose: 'records-key',\n owner: input?.owner,\n version: input?.version,\n recordsKeyId: input?.recordsKeyId,\n });\n if (!opened.ok) return opened;\n const recordsKey = await recordsKeyFromBytesV1(opened.keyBytes, input.version);\n if (recordsKey.id !== input.recordsKeyId) return refuse('KEY_WRAP_KEY_MISMATCH');\n return { ok: true, recordsKey };\n } catch {\n return refuse('KEY_WRAP_AUTH_FAILED');\n }\n}\n\n/**\n * One of `owner`'s records' `RK` from a wrap v2. `recordKeyId` is the id the\n * caller expects (the envelope it opens names it); the opened key's id must\n * equal it. Never throws.\n */\nexport async function unwrapRecordKeyV2(input: {\n seed: WorkspaceSeedV1;\n wrap: unknown;\n owner: string;\n recordType: string;\n wireRecordId: string;\n recordKeyId: string;\n}): Promise<{ ok: true; recordKey: RecordKeyV1 } | UnwrapRefusal | RecordsRefusalV1<'KEY_WRAP_KEY_MISMATCH'>> {\n try {\n const opened = await openKeyWrapV2(input.seed, input.wrap, {\n purpose: 'record-key',\n owner: input?.owner,\n recordType: input?.recordType,\n wireRecordId: input?.wireRecordId,\n recordKeyId: input?.recordKeyId,\n });\n if (!opened.ok) return opened;\n const recordKey = await recordKeyFromBytesV1(opened.keyBytes);\n if (recordKey.id !== input.recordKeyId) return refuse('KEY_WRAP_KEY_MISMATCH');\n return { ok: true, recordKey };\n } catch {\n return refuse('KEY_WRAP_AUTH_FAILED');\n }\n}\n\n/** A disclosure key `owner` made, from a wrap v2. Never throws. */\nexport async function unwrapDisclosureKeyV2(input: {\n seed: WorkspaceSeedV1;\n wrap: unknown;\n owner: string;\n handle: string;\n}): Promise<{ ok: true; disclosureKey: Uint8Array } | UnwrapRefusal> {\n try {\n const opened = await openKeyWrapV2(input.seed, input.wrap, { purpose: 'disclosure-key', owner: input?.owner, handle: input?.handle });\n if (!opened.ok) return opened;\n return { ok: true, disclosureKey: opened.keyBytes };\n } catch {\n return refuse('KEY_WRAP_AUTH_FAILED');\n }\n}\n\n// ------------------------------------------------------------------ identity rotation (card 10, F4)\n\n/**\n * What a rotation proof binds: the workspace, the identity it leaves, the\n * identity it moves to, and the one challenge it answers.\n */\nexport interface RotationBindingV1 {\n workspaceId: string;\n fromId: string;\n newId: string;\n challengeId: string;\n}\n\n/** A challenge id the API makes: 22 to 64 base64url characters. */\nexport const ROTATION_CHALLENGE_ID_V1 = /^[A-Za-z0-9_-]{22,64}$/;\n/** The encapsulation sent with a challenge: 1,120 bytes. */\nexport const ROTATION_CHALLENGE_ENC_BYTES_V1 = 1120;\n\n/** `\"pacspace:identity-rotation:v1\" || 0x00 || workspaceId || 0x00 || fromId || 0x00 || newId || 0x00 || challengeId`. */\nfunction rotationMessage(binding: RotationBindingV1): Uint8Array {\n if (\n typeof binding?.workspaceId !== 'string' ||\n !KEY_WRAP_OWNER_V2.test(binding.workspaceId) ||\n typeof binding.fromId !== 'string' ||\n !HEX64.test(binding.fromId) ||\n typeof binding.newId !== 'string' ||\n !HEX64.test(binding.newId) ||\n binding.fromId === binding.newId ||\n typeof binding.challengeId !== 'string' ||\n !ROTATION_CHALLENGE_ID_V1.test(binding.challengeId)\n ) {\n throw new RecordsAsymmetricError('ROTATION_BINDING_INVALID');\n }\n return concatBytes(\n utf8(L.identityRotation), SEP, utf8(binding.workspaceId), SEP, utf8(binding.fromId), SEP, utf8(binding.newId), SEP, utf8(binding.challengeId),\n );\n}\n\nconst hex = (bytes: Uint8Array) => Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\n\n/** SHA-256 of a proof's bytes, 64 lowercase hex; null for a proof that is not 32 bytes of base64url. */\nexport async function rotationProofHashV1(proof: unknown): Promise<string | null> {\n if (typeof proof !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(proof)) return null;\n const bytes = fromBase64Url(proof);\n if (!bytes || bytes.length !== 32 || toBase64Url(bytes) !== proof) return null;\n return hex(await sha256(bytes));\n}\n\n/**\n * The API's side of a rotation challenge: an encapsulation to the current\n * public key and the SHA-256 of the proof only the holder of the current\n * seed can make. The shared secret never leaves this function. `ikmE` fixes\n * the encapsulation for vectors only.\n */\nexport async function rotationChallengeV1(\n currentPublicKey: Uint8Array,\n binding: RotationBindingV1,\n ikmE?: Uint8Array,\n): Promise<{ enc: string; proofHash: string }> {\n assertPublicKey(currentPublicKey);\n if ((await publicKeyIdV1(currentPublicKey)) !== binding?.fromId) throw new RecordsAsymmetricError('ROTATION_BINDING_INVALID');\n const message = rotationMessage(binding);\n const { hybrid } = await load();\n const { cipherText, sharedSecret } = hybrid.ml_kem768_x25519.encapsulate(Uint8Array.from(currentPublicKey), ikmE);\n const proof = await hmacSha256(sharedSecret, message);\n sharedSecret.fill(0);\n return { enc: toBase64Url(cipherText), proofHash: hex(await sha256(proof)) };\n}\n\n/** The current seed's answer to a challenge: base64url of HMAC-SHA256(shared secret, the binding). */\nexport async function rotationProofV1(seed: WorkspaceSeedV1, enc: string, binding: RotationBindingV1): Promise<string> {\n if (!(seed instanceof WorkspaceSeedV1) || binding?.fromId !== seed.publicKeyId) throw new RecordsAsymmetricError('ROTATION_BINDING_INVALID');\n const message = rotationMessage(binding);\n const cipherText = typeof enc === 'string' && /^[A-Za-z0-9_-]+$/.test(enc) ? fromBase64Url(enc) : null;\n if (!cipherText || cipherText.length !== ROTATION_CHALLENGE_ENC_BYTES_V1 || toBase64Url(cipherText) !== enc) {\n throw new RecordsAsymmetricError('ROTATION_CHALLENGE_MALFORMED');\n }\n const { hybrid } = await load();\n const sharedSecret = hybrid.ml_kem768_x25519.decapsulate(cipherText, Uint8Array.from(heldBytes(seed, 'WORKSPACE_SEED_INVALID')));\n const proof = await hmacSha256(sharedSecret, message);\n sharedSecret.fill(0);\n return toBase64Url(proof);\n}\n\n// ------------------------------------------------------------------ ML-DSA-65 (question C)\n\n/** The signing key a 32-byte seed makes (FIPS 204 ML-DSA.KeyGen_internal). */\nexport async function mldsaSigningKeyFromSeedV1(seed: Uint8Array): Promise<MldsaSigningKeyV1> {\n if (!(seed instanceof Uint8Array) || seed.length !== MLDSA65_SEED_BYTES_V1) throw new RecordsAsymmetricError('MLDSA_KEY_INVALID');\n const { mldsa } = await load();\n const { publicKey } = mldsa.ml_dsa65.keygen(Uint8Array.from(seed));\n return new MldsaSigningKeyV1(seed, publicKey);\n}\n\n/** A new signing key from 32 random bytes this code draws. */\nexport async function generateMldsaSigningKeyV1(): Promise<MldsaSigningKeyV1> {\n return mldsaSigningKeyFromSeedV1(randomBytes(MLDSA65_SEED_BYTES_V1));\n}\n\n/** The seed's 32 bytes, for storage on the key-page origin and the published vectors. */\nexport function exportMldsaSeedBytesV1(key: MldsaSigningKeyV1): Uint8Array {\n return Uint8Array.from(heldBytes(key, 'MLDSA_KEY_INVALID'));\n}\n\n/** @internal `deterministic` signs with no added randomness; vectors only. */\nexport async function signMldsa65WithV1(key: MldsaSigningKeyV1, message: Uint8Array, deterministic: boolean): Promise<Uint8Array> {\n if (!(key instanceof MldsaSigningKeyV1) || !(message instanceof Uint8Array)) throw new RecordsAsymmetricError('MLDSA_KEY_INVALID');\n const { mldsa } = await load();\n const { secretKey } = mldsa.ml_dsa65.keygen(Uint8Array.from(heldBytes(key, 'MLDSA_KEY_INVALID')));\n try {\n return mldsa.ml_dsa65.sign(Uint8Array.from(message), secretKey, deterministic ? { extraEntropy: false } : {});\n } finally {\n secretKey.fill(0);\n }\n}\n\n/** ML-DSA-65 over the message, hedged (FIPS 204's default), empty context. */\nexport async function signMldsa65V1(key: MldsaSigningKeyV1, message: Uint8Array): Promise<Uint8Array> {\n return signMldsa65WithV1(key, message, false);\n}\n\n/** Sizes first, then the signature. Never throws. */\nexport async function verifyMldsa65V1(publicKey: Uint8Array, message: Uint8Array, signature: Uint8Array): Promise<boolean> {\n try {\n if (!(publicKey instanceof Uint8Array) || publicKey.length !== MLDSA65_PUBLIC_KEY_BYTES) return false;\n if (!(signature instanceof Uint8Array) || signature.length !== MLDSA65_SIGNATURE_BYTES || !(message instanceof Uint8Array)) return false;\n const { mldsa } = await load();\n return mldsa.ml_dsa65.verify(Uint8Array.from(signature), Uint8Array.from(message), Uint8Array.from(publicKey));\n } catch {\n return false;\n }\n}\n", "/**\n * `reader-crypto-v1` (ADR 0019; records prototype build, R6, D-1, D-14, D-16): the compositions a trail link's\n * devices, link keys, reveals, answers, sealed notes and seeded samples are made of. This half holds every\n * composition that needs no key wrap, built only from SHA-256, HMAC-SHA-256, HKDF-SHA-256 and AES-256-GCM through\n * the platform's WebCrypto and BF's `record-disclosure/v1` envelope, so the API, the browser, the SDK and the\n * checker all read the same bytes. The wraps (`wrapDisclosureKeyV1` and its open) live beside BF's asymmetric layer,\n * in `records-crypto/asymmetric/reader-wraps-v1.ts`, so nothing that imports shared's index loads that layer.\n *\n * Nothing here logs, and no refusal carries a key, a note or a disclosure.\n */\nimport { canonicalizeJcs } from '../proof/jcs';\nimport { fromBase64Url, toBase64Url } from '../records-crypto/base64url';\nimport { decryptDisclosureV1, encryptDisclosureV1 } from '../records-crypto/disclosure-envelope-v1';\nimport { concatBytes, hmacSha256, platformCrypto, randomBytes, sha256, utf8 } from '../records-crypto/platform-crypto';\nimport { RECORD_DISCLOSURE_SCHEMA_V1, RECORD_DISCLOSURE_SCHEMA_V2, type RecordDisclosure } from '../records-crypto/record-disclosure-v1';\nimport { workspacePublicKeyIdV1 } from '../records-crypto/wrap-shapes-v1';\nimport { MLDSA65_PUBLIC_KEY_BYTES, es256PublicPointV1 } from './signed-acknowledgment-v2';\nimport type { SigningPublicKeyJwkV1 } from './signed-acknowledgment-v1';\n\nexport const READER_CRYPTO_LABELS_V1 = {\n deviceId: 'pacspace:reader-device:v1',\n proofKey: 'pacspace:device-proof-key:v1',\n deviceProof: 'pacspace:device-proof:v1',\n deviceConfirmed: 'pacspace:device-confirmed:v1',\n deviceApproval: 'pacspace:device-approval:v1',\n signedRequest: 'pacspace:signed-request:v1',\n deviceDisconnect: 'pacspace:device-disconnect:v1',\n sealedNote: 'pacspace:sealed-note:v1',\n workspaceKey: 'pacspace:workspace-key:v1',\n} as const;\n\nexport const SEALED_NOTE_SCHEMA_V1 = 'sealed-note/v1' as const;\nexport const SAMPLE_METHOD_V1 = 'pacspace-sample/v1' as const;\n/** The X-Wing public key's encoded length (the ML-KEM-768 key, then the X25519 key), as BF's wraps take it. */\nexport const DEVICE_XWING_PUBLIC_KEY_BYTES_V1 = 1216;\n/** A P-256 SubjectPublicKeyInfo in DER, uncompressed point. */\nexport const DEVICE_P256_SPKI_BYTES_V1 = 91;\nexport const DEVICE_CODE_DIGITS_V1 = 40;\nexport const LINK_KEY_BYTES_V1 = 32;\nexport const SAMPLE_SEED_HEX_V1 = /^[0-9a-f]{64}$/;\n/** A note's envelope, as text, at most this long: about 48 KiB of note. */\nexport const SEALED_NOTE_MAX_CHARS_V1 = 65_536;\n\nexport type ReaderCryptoCodeV1 = 'READER_BINDING_INVALID' | 'READER_DEVICE_KEYS_INVALID' | 'READER_KEY_INVALID' | 'SEALED_NOTE_MALFORMED';\n\n/** Thrown by the making side only; its message is the code. */\nexport class ReaderCryptoError extends Error {\n constructor(readonly code: ReaderCryptoCodeV1) {\n super(code);\n this.name = 'ReaderCryptoError';\n }\n}\n\nconst SEP = new Uint8Array([0]);\nconst HEX64 = /^[0-9a-f]{64}$/;\nconst P256_SPKI_PREFIX = Uint8Array.from([\n 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00,\n]);\n\nconst hex = (bytes: Uint8Array) => Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\n\n// ------------------------------------------------------------------ typed bindings (D-1)\n\n/** A trail link's handle as bindings take it: `csh1_` and base64url characters, never a colon. */\nconst HANDLE = /^csh1_[A-Za-z0-9_-]{1,80}$/;\n/** A record key or wire id, a reference or a kind: printable, never a colon, so no two bindings can read alike. */\nconst PART = /^[\\x21-\\x39\\x3b-\\x7e]{1,128}$/;\nconst KIND = /^[a-z][a-z0-9-]{0,31}$/;\nconst TRAIL_ID = /^[a-z0-9]{20,32}$/;\n\nfunction check(ok: boolean): void {\n if (!ok) throw new ReaderCryptoError('READER_BINDING_INVALID');\n}\nconst isEpoch = (n: unknown): n is number => Number.isSafeInteger(n) && (n as number) >= 1;\nconst isNatural = (n: unknown): n is number => Number.isSafeInteger(n) && (n as number) >= 0;\n\n/** `link-key:<handle>:<epoch>`, a link key's wraps. */\nexport function linkKeyBindingV1(handle: string, epoch: number): string {\n check(HANDLE.test(handle) && isEpoch(epoch));\n return `link-key:${handle}:${epoch}`;\n}\n\n/** `reveal:<handle>:<epoch>:<recordKey>`, a reveal's envelope. */\nexport function revealBindingV1(handle: string, epoch: number, recordKey: string): string {\n check(HANDLE.test(handle) && isEpoch(epoch) && PART.test(recordKey));\n return `reveal:${handle}:${epoch}:${recordKey}`;\n}\n\n/** `answer:<handle>:<requestRef>`, an answer key's wraps. */\nexport function answerKeyBindingV1(handle: string, requestRef: string): string {\n check(HANDLE.test(handle) && PART.test(requestRef));\n return `answer:${handle}:${requestRef}`;\n}\n\n/** `answer:<handle>:<requestRef>:<number>:<seq>`, one shown entry's envelope. */\nexport function answerEntryBindingV1(handle: string, requestRef: string, number: number, seq: number): string {\n check(HANDLE.test(handle) && PART.test(requestRef) && isEpoch(number) && isNatural(seq));\n return `answer:${handle}:${requestRef}:${number}:${seq}`;\n}\n\n/** Where a note belongs: a link's handle, or a trail's rule (`trail-rule:<trailId>`, which never reads as a handle). */\nexport type NoteScopeV1 = { handle: string } | { trailRuleOf: string };\n\nexport interface NoteNameV1 {\n scope: NoteScopeV1;\n kind: string;\n ref: string;\n n: number;\n}\n\nfunction scopeText(scope: NoteScopeV1): string {\n if (scope && 'handle' in scope) {\n check(HANDLE.test(scope.handle));\n return scope.handle;\n }\n check(!!scope && typeof scope.trailRuleOf === 'string' && TRAIL_ID.test(scope.trailRuleOf));\n return `trail-rule:${scope.trailRuleOf}`;\n}\n\nfunction noteParts(name: NoteNameV1): string {\n check(!!name && KIND.test(name.kind) && PART.test(name.ref) && isEpoch(name.n));\n return `${scopeText(name.scope)}:${name.kind}:${name.ref}:${name.n}`;\n}\n\n/** `note:<handle or trail-rule:<trailId>>:<kind>:<ref>:<n>`, a sealed note key's wraps. */\nexport function noteKeyBindingV1(name: NoteNameV1): string {\n return `note:${noteParts(name)}`;\n}\n\n/** `pacspace:sealed-note:v1:<handle or trail binding>:<kind>:<ref>:<n>`, a sealed note's additional data. */\nexport function noteAdditionalDataV1(name: NoteNameV1): string {\n return `${READER_CRYPTO_LABELS_V1.sealedNote}:${noteParts(name)}`;\n}\n\n/**\n * An acknowledgment's flag notes (R7; David, 2026-10-26): one fresh key per acknowledgment, wrapped under\n * `note:<handle>:ack-flags:<checkRef>:1`, and each flagged entry's note sealed under it with the additional data\n * `pacspace:sealed-note:v1:<handle>:ack-flag:<checkRef>.<record>.<entry>:1`, so a note opens only as its own entry's.\n */\nexport function ackFlagNotesKeyNameV1(handle: string, checkRef: string): NoteNameV1 {\n return { scope: { handle }, kind: 'ack-flags', ref: checkRef, n: 1 };\n}\n\nexport function ackFlagNoteNameV1(handle: string, checkRef: string, record: number, entry: number): NoteNameV1 {\n check(isEpoch(record) && isEpoch(entry));\n return { scope: { handle }, kind: 'ack-flag', ref: `${checkRef}.${record}.${entry}`, n: 1 };\n}\n\n/** The acknowledgment's own note, under the same key: `pacspace:sealed-note:v1:<handle>:ack-note:<checkRef>:1`. */\nexport function ackNoteNameV1(handle: string, checkRef: string): NoteNameV1 {\n return { scope: { handle }, kind: 'ack-note', ref: checkRef, n: 1 };\n}\n\n// ------------------------------------------------------------------ the device id and its code (D-1)\n\nexport interface DevicePublicKeysV1 {\n xwingPublicKey: Uint8Array;\n p256Jwk: SigningPublicKeyJwkV1;\n mldsaPublicKey: Uint8Array;\n}\n\n/** A P-256 public JWK as its 91-byte SubjectPublicKeyInfo, once WebCrypto has taken the point as one on the curve. */\nexport async function p256SpkiOfJwkV1(jwk: SigningPublicKeyJwkV1): Promise<Uint8Array> {\n const point = es256PublicPointV1(jwk);\n if (!point) throw new ReaderCryptoError('READER_DEVICE_KEYS_INVALID');\n const { subtle } = await platformCrypto();\n let spki: Uint8Array;\n try {\n const key = await subtle.importKey('jwk', { kty: 'EC', crv: 'P-256', x: jwk.x, y: jwk.y, ext: true }, { name: 'ECDSA', namedCurve: 'P-256' }, true, ['verify']);\n spki = new Uint8Array(await subtle.exportKey('spki', key));\n } catch {\n throw new ReaderCryptoError('READER_DEVICE_KEYS_INVALID');\n }\n const expected = concatBytes(P256_SPKI_PREFIX, point);\n if (spki.length !== DEVICE_P256_SPKI_BYTES_V1 || spki.some((b, i) => b !== expected[i])) throw new ReaderCryptoError('READER_DEVICE_KEYS_INVALID');\n return spki;\n}\n\n/**\n * `SHA-256(\"pacspace:reader-device:v1\" || 0x00 || xwingPublicKey || 0x00 || p256Spki || 0x00 || mldsaPublicKey)`,\n * 64 lowercase hex: one id over all three public keys, so a key swapped anywhere changes it.\n */\nexport async function deviceIdV1(keys: DevicePublicKeysV1): Promise<string> {\n if (!(keys?.xwingPublicKey instanceof Uint8Array) || keys.xwingPublicKey.length !== DEVICE_XWING_PUBLIC_KEY_BYTES_V1) {\n throw new ReaderCryptoError('READER_DEVICE_KEYS_INVALID');\n }\n if (!(keys.mldsaPublicKey instanceof Uint8Array) || keys.mldsaPublicKey.length !== MLDSA65_PUBLIC_KEY_BYTES) {\n throw new ReaderCryptoError('READER_DEVICE_KEYS_INVALID');\n }\n const spki = await p256SpkiOfJwkV1(keys.p256Jwk);\n return hex(await sha256(concatBytes(utf8(READER_CRYPTO_LABELS_V1.deviceId), SEP, keys.xwingPublicKey, SEP, spki, SEP, keys.mldsaPublicKey)));\n}\n\n/**\n * The device's code: the device id in the key holder code's format, the first 17 bytes as an unsigned big-endian\n * integer modulo 10^40, 40 digits with leading zeros in eight groups of five.\n */\nexport function deviceCodeV1(deviceId: string): string {\n check(typeof deviceId === 'string' && HEX64.test(deviceId));\n let n = 0n;\n for (let i = 0; i < 17; i += 1) n = (n << 8n) | BigInt(parseInt(deviceId.slice(i * 2, i * 2 + 2), 16));\n const digits = (n % 10n ** 40n).toString().padStart(DEVICE_CODE_DIGITS_V1, '0');\n return digits.match(/.{5}/g)!.join(' ');\n}\n\n// ------------------------------------------------------------------ the proof key, proofs, tags and approvals (D-16)\n\nfunction assertKey(key: Uint8Array): void {\n if (!(key instanceof Uint8Array) || key.length !== LINK_KEY_BYTES_V1) throw new ReaderCryptoError('READER_KEY_INVALID');\n}\n\n/** `HKDF-SHA-256(linkKey, salt empty, info \"pacspace:device-proof-key:v1\", 32 bytes)`; proofs and tags never use the link key itself. */\nexport async function proofKeyV1(linkKey: Uint8Array): Promise<Uint8Array> {\n assertKey(linkKey);\n const { subtle } = await platformCrypto();\n const base = await subtle.importKey('raw', Uint8Array.from(linkKey), 'HKDF', false, ['deriveBits']);\n const bits = await subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(0), info: utf8(READER_CRYPTO_LABELS_V1.proofKey) as BufferSource }, base, 256);\n return new Uint8Array(bits);\n}\n\nfunction deviceMessage(label: string, handle: string, epoch: number, deviceId: string): string {\n check(HANDLE.test(handle) && isEpoch(epoch) && typeof deviceId === 'string' && HEX64.test(deviceId));\n return `${label}:${handle}:${epoch}:${deviceId}`;\n}\n\n/** A proof key a browser keeps as a CryptoKey: HMAC with SHA-256 over 32 bytes, usable to sign. */\nfunction isProofKey(key: unknown): key is CryptoKey {\n if (typeof CryptoKey === 'undefined' || !(key instanceof CryptoKey) || key.type !== 'secret' || !key.usages.includes('sign')) return false;\n const algorithm = key.algorithm as HmacKeyAlgorithm;\n return algorithm.name === 'HMAC' && algorithm.hash?.name === 'SHA-256' && algorithm.length === LINK_KEY_BYTES_V1 * 8;\n}\n\nasync function proofHmac(proofKey: Uint8Array | CryptoKey, message: string): Promise<string> {\n if (isProofKey(proofKey)) {\n const { subtle } = await platformCrypto();\n return hex(new Uint8Array(await subtle.sign('HMAC', proofKey, utf8(message) as BufferSource)));\n }\n assertKey(proofKey as Uint8Array);\n return hex(await hmacSha256(proofKey as Uint8Array, utf8(message)));\n}\n\n/** `HMAC-SHA-256(proofKey, \"pacspace:device-proof:v1:<handle>:<epoch>:<deviceId>\")`, 64 lowercase hex: the device holds the link key. */\nexport async function deviceProofV1(proofKey: Uint8Array | CryptoKey, handle: string, epoch: number, deviceId: string): Promise<string> {\n return proofHmac(proofKey, deviceMessage(READER_CRYPTO_LABELS_V1.deviceProof, handle, epoch, deviceId));\n}\n\n/** `HMAC-SHA-256(proofKey, \"pacspace:device-confirmed:v1:<handle>:<epoch>:<deviceId>\")`, 64 lowercase hex: the lab's side confirmed it. */\nexport async function confirmationTagV1(proofKey: Uint8Array | CryptoKey, handle: string, epoch: number, deviceId: string): Promise<string> {\n return proofHmac(proofKey, deviceMessage(READER_CRYPTO_LABELS_V1.deviceConfirmed, handle, epoch, deviceId));\n}\n\n/** What a browser keeps of a code link's key (plan conflict 2, D-26): two keys it can use and never export. */\nexport interface ReaderLinkKeysV1 {\n /** AES-256-GCM, decrypt only: opens the link's reveals. */\n revealKey: CryptoKey;\n /** HMAC-SHA-256 over proofKeyV1's bytes, sign only: proofs and confirmation tags. */\n proofKey: CryptoKey;\n}\n\n/**\n * The link key as the two non-extractable keys a browser keeps in its place. The caller's bytes are neither kept nor\n * changed; the caller zeroes them once these are made. The proof key's bytes are zeroed here.\n */\nexport async function readerLinkKeysV1(linkKey: Uint8Array): Promise<ReaderLinkKeysV1> {\n assertKey(linkKey);\n const { subtle } = await platformCrypto();\n const copy = Uint8Array.from(linkKey);\n const proofBytes = await proofKeyV1(copy);\n try {\n const [revealKey, proofKey] = await Promise.all([\n subtle.importKey('raw', copy as BufferSource, { name: 'AES-GCM' }, false, ['decrypt']),\n subtle.importKey('raw', proofBytes as BufferSource, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']),\n ]);\n return { revealKey, proofKey };\n } finally {\n copy.fill(0);\n proofBytes.fill(0);\n }\n}\n\n/**\n * `HMAC-SHA-256(proofKey, \"pacspace:workspace-key:v1:<handle>:<epoch>:<keyId>\")`, 64 lowercase hex: the lab's browser\n * names the workspace identity a reader seals to (David, 2026-10-26). `keyId` is `workspacePublicKeyIdV1` of the\n * identity's X-Wing key. PacSpace never holds the proof key in an encrypted workspace, so it cannot tag a key of its own.\n * A reader's browser on a code link checks the tag with the proof key it keeps as a CryptoKey it can use and never\n * export (U5), as it works out confirmation tags.\n */\nexport async function workspaceKeyTagV1(proofKey: Uint8Array | CryptoKey, handle: string, epoch: number, keyId: string): Promise<string> {\n return proofHmac(proofKey, deviceMessage(READER_CRYPTO_LABELS_V1.workspaceKey, handle, epoch, keyId));\n}\n\n/**\n * Whether a served workspace key is the one the lab's browser tagged for this link and epoch: its key id worked out\n * from the key's own bytes, never read from the response, and the tag compared in constant time. A reader's browser\n * seals nothing to the workspace unless this holds. Never throws.\n */\nexport async function servedWorkspaceKeyV1(input: {\n proofKey: Uint8Array | CryptoKey;\n handle: string;\n epoch: number;\n publicKey: Uint8Array;\n tag: unknown;\n}): Promise<{ ok: true; keyId: string } | { ok: false; code: 'WORKSPACE_KEY_NOT_TAGGED' }> {\n const refused = { ok: false as const, code: 'WORKSPACE_KEY_NOT_TAGGED' as const };\n try {\n const keyId = await workspacePublicKeyIdV1(input.publicKey);\n if (!keyId || typeof input.tag !== 'string') return refused;\n return sameHex64V1(await workspaceKeyTagV1(input.proofKey, input.handle, input.epoch, keyId), input.tag) ? { ok: true, keyId } : refused;\n } catch {\n return refused;\n }\n}\n\n/**\n * Whether every device `GET /seal-to` serves is one the lab's side confirmed on this link and epoch: each device id\n * worked out from the device's three public keys, never read from the response, so a sealing key PacSpace swapped in\n * changes the id and fails its confirmation tag. One device that fails refuses them all. A reader's browser seals\n * nothing to a device unless this holds. Never throws.\n */\nexport async function servedDevicesV1(input: {\n proofKey: Uint8Array | CryptoKey;\n handle: string;\n epoch: number;\n devices: unknown;\n}): Promise<{ ok: true; devices: Array<{ deviceId: string; xwingPublicKey: Uint8Array }> } | { ok: false; code: 'DEVICE_NOT_TAGGED' }> {\n const refused = { ok: false as const, code: 'DEVICE_NOT_TAGGED' as const };\n try {\n if (!Array.isArray(input.devices) || input.devices.length === 0) return refused;\n const checked: Array<{ deviceId: string; xwingPublicKey: Uint8Array }> = [];\n for (const served of input.devices as Array<Record<string, unknown>>) {\n if (served?.confirmedEpoch !== input.epoch || typeof served.xwingPublicKey !== 'string' || typeof served.mldsaPublicKey !== 'string') return refused;\n const xwingPublicKey = fromBase64Url(served.xwingPublicKey);\n const mldsaPublicKey = fromBase64Url(served.mldsaPublicKey);\n if (!xwingPublicKey || !mldsaPublicKey) return refused;\n const deviceId = await deviceIdV1({ xwingPublicKey, p256Jwk: served.p256Jwk as SigningPublicKeyJwkV1, mldsaPublicKey });\n if (!sameHex64V1(deviceId, served.deviceId)) return refused;\n if (!sameHex64V1(await confirmationTagV1(input.proofKey, input.handle, input.epoch, deviceId), served.confirmationTag)) return refused;\n checked.push({ deviceId, xwingPublicKey });\n }\n return new Set(checked.map((d) => d.deviceId)).size === checked.length ? { ok: true, devices: checked } : refused;\n } catch {\n return refused;\n }\n}\n\n/** `pacspace:device-approval:v1:<handle>:<epoch>:<new deviceId>`, the message a confirmed device signs with its v2 pair. */\nexport function approvalMessageV1(handle: string, epoch: number, newDeviceId: string): string {\n return deviceMessage(READER_CRYPTO_LABELS_V1.deviceApproval, handle, epoch, newDeviceId);\n}\n\n/**\n * ADR 0019's signed request (vector RQ-01): SHA-256, as 64 lowercase hex, of the JCS of the request's body as sent,\n * without `signedBy` (`{clientRequestId, items, sample, question}`), so every pick, the sample and the question are bound.\n */\nexport async function signedRequestDigestV1(body: Readonly<Record<string, unknown>>): Promise<string> {\n check(!!body && typeof body === 'object' && !Array.isArray(body));\n const rest: Record<string, unknown> = { ...body };\n delete rest.signedBy;\n return hex(await sha256(utf8(canonicalizeJcs(rest))));\n}\n\n/** `pacspace:signed-request:v1:<handle>:<epoch>:<deviceId>:<requestDigest>`, what the sending device signs with its v2 pair. */\nexport function signedRequestMessageV1(handle: string, epoch: number, deviceId: string, requestDigest: string): string {\n check(typeof requestDigest === 'string' && HEX64.test(requestDigest));\n return `${deviceMessage(READER_CRYPTO_LABELS_V1.signedRequest, handle, epoch, deviceId)}:${requestDigest}`;\n}\n\n/** `pacspace:device-disconnect:v1:<handle>:<epoch>:<agent deviceId>` (vector RQ-02), signed by the agent or its person's confirmed browser. */\nexport function disconnectMessageV1(handle: string, epoch: number, deviceId: string): string {\n return deviceMessage(READER_CRYPTO_LABELS_V1.deviceDisconnect, handle, epoch, deviceId);\n}\n\n/** Two 64-hex values compared in time that does not depend on where they differ. */\nexport function sameHex64V1(a: unknown, b: unknown): boolean {\n if (typeof a !== 'string' || typeof b !== 'string' || !HEX64.test(a) || !HEX64.test(b)) return false;\n let diff = 0;\n for (let i = 0; i < 64; i += 1) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);\n return diff === 0;\n}\n\n// ------------------------------------------------------------------ reveals and answers (record-disclosure under typed bindings)\n\n/** A record's reveal, `record-disclosure` under the link key for its epoch and record. */\nexport function revealRecordV1(input: { disclosure: RecordDisclosure; linkKey: Uint8Array; handle: string; epoch: number; recordKey: string }): Promise<string> {\n assertKey(input.linkKey);\n return encryptDisclosureV1({ disclosure: input.disclosure, key: input.linkKey, handle: revealBindingV1(input.handle, input.epoch, input.recordKey) });\n}\n\n/** Opens a reveal with the link key's bytes, or with the reveal key a browser keeps (readerLinkKeysV1). */\nexport function openRevealV1(input: { envelope: string; linkKey: Uint8Array | CryptoKey; handle: string; epoch: number; recordKey: string }) {\n return decryptDisclosureV1({ envelope: input.envelope, key: input.linkKey, handle: revealBindingV1(input.handle, input.epoch, input.recordKey) });\n}\n\n/** One shown entry's disclosure under the answer key. */\nexport function sealAnswerEntryV1(input: { disclosure: RecordDisclosure; answerKey: Uint8Array; handle: string; requestRef: string; number: number; seq: number }): Promise<string> {\n assertKey(input.answerKey);\n return encryptDisclosureV1({\n disclosure: input.disclosure,\n key: input.answerKey,\n handle: answerEntryBindingV1(input.handle, input.requestRef, input.number, input.seq),\n });\n}\n\n/**\n * Opens one shown entry and checks its form against the record's hash version: `record-disclosure/v1` for a\n * record on record hash v2 (or v1), `record-disclosure/v2` for one on v3. The caller then checks it against the\n * entry's committed seal with `verifyRecordDisclosureV1` and its fields with `shownFieldsMatchV1`.\n */\nexport async function openAnswerEntryV1(input: {\n envelope: string;\n answerKey: Uint8Array;\n handle: string;\n requestRef: string;\n number: number;\n seq: number;\n recordHashVersion: 1 | 2 | 3;\n}): Promise<{ ok: true; disclosure: RecordDisclosure } | { ok: false; code: string }> {\n const opened = await decryptDisclosureV1({\n envelope: input.envelope,\n key: input.answerKey,\n handle: answerEntryBindingV1(input.handle, input.requestRef, input.number, input.seq),\n });\n if (!opened.ok) return { ok: false, code: opened.code };\n const d = opened.disclosure as { schema?: unknown; recordHashVersion?: unknown };\n const wanted = input.recordHashVersion === 3 ? RECORD_DISCLOSURE_SCHEMA_V2 : RECORD_DISCLOSURE_SCHEMA_V1;\n if (d?.schema !== wanted || (input.recordHashVersion === 3) !== (d.recordHashVersion === 3)) return { ok: false, code: 'RECORD_HASH_VERSION_UNKNOWN' };\n return { ok: true, disclosure: opened.disclosure as RecordDisclosure };\n}\n\n/**\n * The fields a disclosure shows, per entry, sorted, each named as an answer declares it: by its top-level pointer,\n * so a list field's leaves (`/payloads/0`, `/payloads/1`) are the one field `/payloads`.\n */\nexport function shownFieldsV1(disclosure: RecordDisclosure): Map<number, string[]> {\n const out = new Map<number, string[]>();\n const top = (pointer: string) => `/${pointer.split('/')[1] ?? ''}`;\n for (const e of disclosure.entries as Array<{ seq: number; revealed?: Array<{ pointer: string }>; recordContent?: Record<string, unknown> }>) {\n const pointers = e.revealed ? e.revealed.map((l) => top(l.pointer)) : Object.keys(e.recordContent ?? {}).map((k) => `/${k}`);\n out.set(e.seq, [...new Set(pointers)].sort());\n }\n return out;\n}\n\n/**\n * Whether the entry shows exactly the declared fields (D-22): \"This answer shows fields it did not declare.\" otherwise.\n * An answer declares field names (`/tags`) while an array field shows one leaf per element (`/tags/0`), so each shown\n * pointer is read as its field's name.\n */\nexport function shownFieldsMatchV1(disclosure: RecordDisclosure, seq: number, declared: readonly string[]): boolean {\n const pointers = shownFieldsV1(disclosure).get(seq);\n const shown = pointers && [...new Set(pointers.map((p) => `/${p.split('/')[1] ?? ''}`))].sort();\n const want = [...new Set(declared)].sort();\n return !!shown && shown.length === want.length && shown.every((p, i) => p === want[i]);\n}\n\n/** SHA-256 of an envelope's text, 64 lowercase hex: what a manifest commits for each disclosure. */\nexport async function disclosureDigestV1(envelope: string): Promise<string> {\n return hex(await sha256(utf8(envelope)));\n}\n\n// ------------------------------------------------------------------ sealed-note/v1\n\nexport interface SealedNoteV1 {\n schema: typeof SEALED_NOTE_SCHEMA_V1;\n iv: string;\n ct: string;\n}\n\nconst NOTE_MEMBERS = ['schema', 'iv', 'ct'];\n\n/** The keyless checks: exactly the three members, a 12-byte IV, and a ciphertext with its tag, all canonical base64url. */\nexport function readSealedNoteShapeV1(value: unknown): { ok: true; iv: Uint8Array; ct: Uint8Array } | { ok: false; code: 'SEALED_NOTE_MALFORMED' } {\n const bad = { ok: false as const, code: 'SEALED_NOTE_MALFORMED' as const };\n if (!value || typeof value !== 'object' || Array.isArray(value)) return bad;\n const v = value as Record<string, unknown>;\n if (Object.keys(v).length !== NOTE_MEMBERS.length || !NOTE_MEMBERS.every((k) => Object.prototype.hasOwnProperty.call(v, k))) return bad;\n if (v.schema !== SEALED_NOTE_SCHEMA_V1 || typeof v.iv !== 'string' || typeof v.ct !== 'string' || v.ct.length > SEALED_NOTE_MAX_CHARS_V1) return bad;\n const iv = fromBase64Url(v.iv);\n const ct = fromBase64Url(v.ct);\n if (!iv || iv.length !== 12 || toBase64Url(iv) !== v.iv || !ct || ct.length <= 16 || toBase64Url(ct) !== v.ct) return bad;\n return { ok: true, iv, ct };\n}\n\nasync function noteCipher(key: Uint8Array, usage: 'encrypt' | 'decrypt'): Promise<CryptoKey> {\n const { subtle } = await platformCrypto();\n return subtle.importKey('raw', Uint8Array.from(key), { name: 'AES-GCM' }, false, [usage]);\n}\n\n/**\n * @internal Seals under a given key and IV: the published vectors, and an acknowledgment's flag notes, which share\n * one fresh key with a random IV each (`sealAckFlagNotesV1`). Any other note takes `sealNoteV1`.\n */\nexport async function sealNoteWithV1(text: string, name: NoteNameV1, key: Uint8Array, iv: Uint8Array): Promise<SealedNoteV1> {\n assertKey(key);\n if (typeof text !== 'string' || !(iv instanceof Uint8Array) || iv.length !== 12) throw new ReaderCryptoError('SEALED_NOTE_MALFORMED');\n const aad = utf8(noteAdditionalDataV1(name)) as BufferSource;\n const { subtle } = await platformCrypto();\n const ct = new Uint8Array(\n await subtle.encrypt({ name: 'AES-GCM', iv: Uint8Array.from(iv), additionalData: aad, tagLength: 128 }, await noteCipher(key, 'encrypt'), utf8(text) as BufferSource),\n );\n const note: SealedNoteV1 = { schema: SEALED_NOTE_SCHEMA_V1, iv: toBase64Url(iv), ct: toBase64Url(ct) };\n if (note.ct.length > SEALED_NOTE_MAX_CHARS_V1) throw new ReaderCryptoError('SEALED_NOTE_MALFORMED');\n return note;\n}\n\n/** A note sealed under a fresh 32-byte key and a random IV; the caller wraps `key` and then lets it go. */\nexport async function sealNoteV1(text: string, name: NoteNameV1): Promise<{ note: SealedNoteV1; key: Uint8Array }> {\n const key = randomBytes(LINK_KEY_BYTES_V1);\n return { note: await sealNoteWithV1(text, name, key, randomBytes(12)), key };\n}\n\n/** Opens a note under its own name; any other scope, kind, reference or number fails. Never throws. */\nexport async function openNoteV1(input: { note: unknown; key: Uint8Array; name: NoteNameV1 }): Promise<{ ok: true; text: string } | { ok: false; code: 'SEALED_NOTE_MALFORMED' | 'SEALED_NOTE_AUTH_FAILED' }> {\n const shape = readSealedNoteShapeV1(input?.note);\n if (!shape.ok) return shape;\n try {\n assertKey(input.key);\n const aad = utf8(noteAdditionalDataV1(input.name)) as BufferSource;\n const { subtle } = await platformCrypto();\n const plain = await subtle.decrypt({ name: 'AES-GCM', iv: shape.iv as BufferSource, additionalData: aad, tagLength: 128 }, await noteCipher(input.key, 'decrypt'), shape.ct as BufferSource);\n return { ok: true, text: new TextDecoder('utf-8', { fatal: true }).decode(plain) };\n } catch {\n return { ok: false, code: 'SEALED_NOTE_AUTH_FAILED' };\n }\n}\n\n/** SHA-256 of a note's JCS, 64 lowercase hex: what an answer's manifest commits for its reply. */\nexport async function sealedNoteDigestV1(note: SealedNoteV1): Promise<string> {\n return hex(await sha256(utf8(canonicalizeJcs(note))));\n}\n\n// ------------------------------------------------------------------ pacspace-sample/v1 (D-14)\n\n/** The seed as the draw reads it: 32 bytes from `crypto.getRandomValues`, as 64 lowercase hex. */\nexport function newSampleSeedV1(): string {\n return hex(randomBytes(32));\n}\n\n/**\n * The draw: each call takes the next k, from 0, and reads the first 4 bytes of `SHA-256(\"<seed>:<k>\")` as an\n * unsigned big-endian integer, drawing again at or above the largest multiple of `size` below 2^32; otherwise its\n * remainder by `size`. `rejected` lists every k drawn again.\n */\nexport function sampleDrawerV1(seed: string): { next(size: number): Promise<number>; rejected: number[] } {\n check(typeof seed === 'string' && SAMPLE_SEED_HEX_V1.test(seed));\n let k = 0;\n const rejected: number[] = [];\n return {\n rejected,\n async next(size: number) {\n check(Number.isSafeInteger(size) && size >= 1 && size <= 0x1_0000_0000);\n const limit = Math.floor(0x1_0000_0000 / size) * size;\n for (;;) {\n const at = k;\n k += 1;\n const h = await sha256(utf8(`${seed}:${at}`));\n const x = ((h[0] << 24) >>> 0) + (h[1] << 16) + (h[2] << 8) + h[3];\n if (x < limit) return x % size;\n rejected.push(at);\n }\n },\n };\n}\n\nexport type SampleSpreadV1 = 'any' | 'records' | 'days';\n\nexport interface SamplePoolRecordV1 {\n /** The member's number on the link. */\n number: number;\n /** How many entries it has: seqs 0 to entries - 1. */\n entries: number;\n /** The day it opened, `YYYY-MM-DD` (UTC), which a spread across days groups by. */\n openedOn: string;\n}\n\nexport interface SamplePickV1 {\n number: number;\n seq: number;\n}\n\nconst pickKey = (p: SamplePickV1) => `${p.number}:${p.seq}`;\nconst DAY = /^\\d{4}-\\d{2}-\\d{2}$/;\n\n/** The pool in its committed order, record by record and entry by entry, less what was left out. */\nexport function samplePoolV1(records: readonly SamplePoolRecordV1[], leftOut: readonly SamplePickV1[]): Array<SamplePickV1 & { openedOn: string }> {\n const skip = new Set(leftOut.map(pickKey));\n const out: Array<SamplePickV1 & { openedOn: string }> = [];\n for (const r of records) {\n check(isEpoch(r?.number) && isNatural(r.entries) && typeof r.openedOn === 'string' && DAY.test(r.openedOn));\n for (let seq = 0; seq < r.entries; seq += 1) if (!skip.has(`${r.number}:${seq}`)) out.push({ number: r.number, seq, openedOn: r.openedOn });\n }\n return out;\n}\n\n/** SHA-256 of the JCS of the pool's records as `[number, entries, openedOn]`, 64 lowercase hex. */\nexport async function samplePoolDigestV1(records: readonly SamplePoolRecordV1[]): Promise<string> {\n return hex(await sha256(utf8(canonicalizeJcs(records.map((r) => [r.number, r.entries, r.openedOn])))));\n}\n\n/**\n * The picks a seed gives (`pacspace-sample/v1`), the same in every browser, the API and the checker: with no\n * spread, draw from what is left, each pick leaving the pool; with a spread, put the groups (in the order the pool\n * first meets them) in order by the same draws from the last down, then take one pick from each group in turn.\n */\nexport async function drawSampleV1(input: {\n seed: string;\n records: readonly SamplePoolRecordV1[];\n leftOut: readonly SamplePickV1[];\n n: number;\n spread: SampleSpreadV1;\n}): Promise<SamplePickV1[]> {\n check(isNatural(input.n) && (input.spread === 'any' || input.spread === 'records' || input.spread === 'days'));\n const draw = sampleDrawerV1(input.seed);\n const left = samplePoolV1(input.records, input.leftOut);\n const out: SamplePickV1[] = [];\n const take = (from: Array<SamplePickV1 & { openedOn: string }>, i: number) => {\n const [p] = from.splice(i, 1);\n out.push({ number: p.number, seq: p.seq });\n };\n if (input.spread === 'any') {\n while (out.length < input.n && left.length) take(left, await draw.next(left.length));\n return out;\n }\n const groups = new Map<string, Array<SamplePickV1 & { openedOn: string }>>();\n const order: string[] = [];\n for (const p of left) {\n const g = input.spread === 'records' ? String(p.number) : p.openedOn;\n if (!groups.has(g)) {\n groups.set(g, []);\n order.push(g);\n }\n groups.get(g)!.push(p);\n }\n for (let i = order.length - 1; i > 0; i -= 1) {\n const j = await draw.next(i + 1);\n [order[i], order[j]] = [order[j], order[i]];\n }\n let turn = order;\n while (out.length < input.n && turn.length) {\n turn = turn.filter((g) => groups.get(g)!.length);\n for (const g of turn) {\n if (out.length >= input.n) break;\n const group = groups.get(g)!;\n take(group, await draw.next(group.length));\n }\n }\n return out;\n}\n", "/**\n * `reader-crypto-v1`'s wraps (ADR 0019; records prototype build, R6, D-1, D-16): a trail link's device keys, and the\n * link, answer and note keys wrapped to them with BF's `wrapDisclosureKeyV1` under a typed binding, never a bare\n * handle. The keyless half is `records/reader-crypto-v1.ts`. Reached only through the asymmetric subpath, as BF's\n * layer is, so the libraries it loads stay out of everything shared's index reaches.\n *\n * Wraps are `KeyWrapV1`: each binding names the link's handle, which is unique across every workspace, so a wrap\n * made for one link, epoch, request or note opens for no other.\n */\nimport { platformCrypto, utf8 } from '../platform-crypto';\nimport { fromBase64Url, toBase64Url } from '../base64url';\nimport {\n approvalMessageV1,\n answerKeyBindingV1,\n deviceCodeV1,\n deviceIdV1,\n linkKeyBindingV1,\n noteKeyBindingV1,\n type NoteNameV1,\n} from '../../records/reader-crypto-v1';\nimport type { SigningPublicKeyJwkV1 } from '../../records/signed-acknowledgment-v1';\nimport {\n MldsaSigningKeyV1,\n WorkspaceSeedV1,\n mldsaSigningKeyFromSeedV1,\n signMldsa65V1,\n verifyMldsa65V1,\n unwrapDisclosureKeyV1,\n workspaceSeedFromBytesV1,\n wrapDisclosureKeyV1,\n type KeyWrapV1,\n} from './records-asymmetric-v1';\n\n/** A device's keys: the X-Wing pair from its 32-byte seed, the ML-DSA-65 key from its own seed, and the browser's P-256 public key. */\nexport interface DeviceKeysV1 {\n xwing: WorkspaceSeedV1;\n mldsa: MldsaSigningKeyV1;\n p256Jwk: SigningPublicKeyJwkV1;\n deviceId: string;\n code: string;\n}\n\n/**\n * Makes a device's keys from its two 32-byte seeds (the X-Wing pair through `workspaceSeedFromBytesV1`, the ML-DSA-65\n * key through `mldsaSigningKeyFromSeedV1`) and the P-256 public key `browser-key-v2.ts` holds, with its id and code.\n */\nexport async function makeDeviceKeysV1(input: { xwingSeed: Uint8Array; mldsaSeed: Uint8Array; p256Jwk: SigningPublicKeyJwkV1 }): Promise<DeviceKeysV1> {\n const xwing = await workspaceSeedFromBytesV1(input.xwingSeed);\n const mldsa = await mldsaSigningKeyFromSeedV1(input.mldsaSeed);\n const deviceId = await deviceIdV1({ xwingPublicKey: xwing.publicKey, p256Jwk: input.p256Jwk, mldsaPublicKey: mldsa.publicKey });\n return { xwing, mldsa, p256Jwk: input.p256Jwk, deviceId, code: deviceCodeV1(deviceId) };\n}\n\n/** What a device registers with: its three public keys, the X-Wing and ML-DSA-65 keys in base64url. */\nexport function devicePublicV1(keys: DeviceKeysV1): { xwingPublicKey: string; p256Jwk: SigningPublicKeyJwkV1; mldsaPublicKey: string } {\n return { xwingPublicKey: toBase64Url(keys.xwing.publicKey), p256Jwk: keys.p256Jwk, mldsaPublicKey: toBase64Url(keys.mldsa.publicKey) };\n}\n\n/** The link key for one epoch, wrapped to a confirmed device's or the workspace identity's X-Wing public key. */\nexport function wrapLinkKeyV1(publicKey: Uint8Array, linkKey: Uint8Array, handle: string, epoch: number): Promise<KeyWrapV1> {\n return wrapDisclosureKeyV1(publicKey, linkKey, linkKeyBindingV1(handle, epoch));\n}\n\nexport function unwrapLinkKeyV1(input: { seed: WorkspaceSeedV1; wrap: unknown; handle: string; epoch: number }) {\n return unwrapDisclosureKeyV1({ seed: input.seed, wrap: input.wrap, handle: linkKeyBindingV1(input.handle, input.epoch) });\n}\n\n/** An answer's key, wrapped to one confirmed device. */\nexport function wrapAnswerKeyV1(publicKey: Uint8Array, answerKey: Uint8Array, handle: string, requestRef: string): Promise<KeyWrapV1> {\n return wrapDisclosureKeyV1(publicKey, answerKey, answerKeyBindingV1(handle, requestRef));\n}\n\nexport function unwrapAnswerKeyV1(input: { seed: WorkspaceSeedV1; wrap: unknown; handle: string; requestRef: string }) {\n return unwrapDisclosureKeyV1({ seed: input.seed, wrap: input.wrap, handle: answerKeyBindingV1(input.handle, input.requestRef) });\n}\n\n/** A sealed note's key, wrapped to a confirmed device or, for a rule's label text, to the workspace identity. */\nexport function wrapNoteKeyV1(publicKey: Uint8Array, noteKey: Uint8Array, name: NoteNameV1): Promise<KeyWrapV1> {\n return wrapDisclosureKeyV1(publicKey, noteKey, noteKeyBindingV1(name));\n}\n\nexport function unwrapNoteKeyV1(input: { seed: WorkspaceSeedV1; wrap: unknown; name: NoteNameV1 }) {\n return unwrapDisclosureKeyV1({ seed: input.seed, wrap: input.wrap, handle: noteKeyBindingV1(input.name) });\n}\n\n/**\n * A confirmed device's approval of a later device: ES256 (WebCrypto, IEEE P1363) and ML-DSA-65 over the UTF-8 of\n * `approvalMessageV1`, both required, in the members BF's v2 envelope names them. The API checks both with the\n * verifier it already runs for v2 acknowledgments.\n */\nexport function signApprovalV1(input: {\n p256PrivateKey: CryptoKey;\n mldsa: MldsaSigningKeyV1;\n handle: string;\n epoch: number;\n newDeviceId: string;\n}): Promise<{ signature: string; mldsaSignature: string }> {\n return signDeviceMessageV1({ p256PrivateKey: input.p256PrivateKey, mldsa: input.mldsa, message: approvalMessageV1(input.handle, input.epoch, input.newDeviceId) });\n}\n\n/**\n * A device's v2 pair over one message (R7: an approval, an acknowledgment, an evidence file): ES256 (WebCrypto, IEEE\n * P1363) and ML-DSA-65 over its UTF-8, both required, as base64url.\n */\nexport async function signDeviceMessageV1(input: { p256PrivateKey: CryptoKey; mldsa: MldsaSigningKeyV1; message: string }): Promise<{ signature: string; mldsaSignature: string }> {\n const message = new Uint8Array(utf8(input.message));\n const { subtle } = await platformCrypto();\n const es256 = new Uint8Array(await subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, input.p256PrivateKey, message as BufferSource));\n const mldsa = await signMldsa65V1(input.mldsa, message);\n return { signature: toBase64Url(es256), mldsaSignature: toBase64Url(mldsa) };\n}\n\n/**\n * Both of a device's signatures over one message, checked against its P-256 JWK and ML-DSA-65 public key: true only\n * when both verify. Shapes first; never throws.\n */\nexport async function verifyDeviceMessageV1(input: {\n p256Jwk: SigningPublicKeyJwkV1;\n mldsaPublicKey: Uint8Array;\n message: string;\n signature: unknown;\n mldsaSignature: unknown;\n}): Promise<boolean> {\n try {\n if (typeof input.signature !== 'string' || typeof input.mldsaSignature !== 'string') return false;\n const es256 = fromBase64Url(input.signature);\n const mldsa = fromBase64Url(input.mldsaSignature);\n const jwk = input.p256Jwk;\n if (!es256 || es256.length !== 64 || !mldsa || !jwk || jwk.kty !== 'EC' || jwk.crv !== 'P-256') return false;\n const message = new Uint8Array(utf8(input.message));\n const { subtle } = await platformCrypto();\n const key = await subtle.importKey('jwk', { kty: 'EC', crv: 'P-256', x: jwk.x, y: jwk.y, ext: true }, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['verify']);\n const first = await subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, key, es256 as BufferSource, message as BufferSource);\n return first && (await verifyMldsa65V1(input.mldsaPublicKey, message, mldsa));\n } catch {\n return false;\n }\n}\n", "/**\n * `shared-record-ack/v2` (records prototype build, R7; HANDOFF \"Read this first\", fact 4; D-5, D-22, D-45): a trail\n * link reader's acknowledgment of a check, signed like BF's `signed-acknowledgment/v2`: ES256 and ML-DSA-65 over the\n * same message, both required, by a confirmed device's v2 pair, with the pair's key id\n * (`acknowledgmentKeyIdV2`, `SHA-256(\"pacspace:ack-key-id:v1\" || both public keys)`) carried as `keyId`, the\n * acknowledgment's `actorId`.\n *\n * The body names the seal history digest and the disclosure digest the reader checked, and holds the check's\n * reference and day, its counts, the seeded samples (seed, method and picks), how many answered entries were shown and\n * declined, the entries that did not match their seals, the flags (`{record, entry, result, note}`), each opened\n * answer's declared-field result, and the note. A mismatch is carried, never refused. Records are numbered as on the\n * link and entries from 1, as the reader reads them. Nothing here names the reader, a person, or the workspace's own\n * name for what is shared.\n *\n * Each note (every flag's, and the acknowledgment's own) is the reader's words in a plaintext workspace, and in an\n * encrypted one a `sealed-note/v1` made in the reader's browser (David, 2026-10-26): every note of one body under one\n * fresh key, wrapped to the link's confirmed devices and the workspace identity beside the body, never in it\n * (`ackFlagNoteNameV1`, `ackNoteNameV1`). Both signatures cover the sealed form, so PacSpace keeps and commits what it\n * cannot read. One body never mixes the two forms.\n *\n * Like v2 this module holds only what every side must agree on byte for byte, and loads no signing library: the\n * message is the label, a line break and the body's JCS, so two writers that order members differently sign the same\n * bytes, and no other message PacSpace signs starts with this label.\n */\nimport { canonicalizeJcs } from '../proof/jcs';\nimport { readSealedNoteShapeV1, type SealedNoteV1 } from './reader-crypto-v1';\n\nexport const SHARED_RECORD_ACK_SCHEMA_V2 = 'shared-record-ack/v2' as const;\nexport const SHARED_RECORD_ACK_SIGNING_LABEL_V2 = 'pacspace:shared-record-ack:v2';\n/** The body as JSON, with every flag's note sealed. */\nexport const SHARED_RECORD_ACK_MAX_CHARS_V2 = 256 * 1024;\nexport const SHARED_RECORD_ACK_NOTE_MAX_V2 = 2000;\nexport const SHARED_RECORD_ACK_FLAG_NOTE_MAX_V2 = 500;\n/** A sealed flag note's ciphertext as base64url: 500 UTF-16 units are at most 1,500 bytes of UTF-8, and the tag 16. */\nexport const SHARED_RECORD_ACK_SEALED_FLAG_NOTE_MAX_CHARS_V2 = Math.ceil(((SHARED_RECORD_ACK_FLAG_NOTE_MAX_V2 * 3 + 16) * 4) / 3);\n/** The acknowledgment's own note sealed, by the same count at its 2,000-unit bound. */\nexport const SHARED_RECORD_ACK_SEALED_NOTE_MAX_CHARS_V2 = Math.ceil(((SHARED_RECORD_ACK_NOTE_MAX_V2 * 3 + 16) * 4) / 3);\nexport const SHARED_RECORD_ACK_LIST_MAX_V2 = 100;\nexport const SHARED_RECORD_ACK_SAMPLES_MAX_V2 = 20;\n\n/** A flagged entry's result as the reader's check found it: matches its seal, does not, or an export's copy differs. */\nexport const SHARED_RECORD_ACK_FLAG_RESULTS_V2 = ['matches', 'does-not-match', 'copy-differs'] as const;\nexport type SharedRecordAckFlagResultV2 = (typeof SHARED_RECORD_ACK_FLAG_RESULTS_V2)[number];\n\nexport interface SharedRecordAckEntryV2 {\n record: number;\n entry: number;\n}\n\nexport interface SharedRecordAckBodyV2 {\n schema: typeof SHARED_RECORD_ACK_SCHEMA_V2;\n /** The link's reference (`SR-` and 8 characters, unique across workspaces), so the signature speaks for this link only, never naming its handle. */\n reference: string;\n /** D-1's device id of the signing device, 64 lowercase hex. */\n deviceId: string;\n /** `acknowledgmentKeyIdV2` of the device's P-256 and ML-DSA-65 keys, 64 lowercase hex: the actorId. */\n keyId: string;\n check: { ref: string; on: string };\n /** The digest of the seal histories the check read, and of the disclosures it opened (null when none). */\n sealHistoryDigest: string;\n disclosureDigest: string | null;\n counts: { records: number; entries: number; matched: number; notMatched: number };\n sample: Array<{ request: string; method: 'pacspace-sample/v1'; seed: string; picks: SharedRecordAckEntryV2[] }>;\n answers: { shown: number; declined: number };\n mismatches: SharedRecordAckEntryV2[];\n /** Each note: the words (plaintext workspace), a `sealed-note/v1` (encrypted workspace), or null. */\n flags: Array<SharedRecordAckEntryV2 & { result: SharedRecordAckFlagResultV2; note: string | SealedNoteV1 | null }>;\n /** D-22: per opened answer, whether it showed exactly the fields it declared. */\n declaredFields: Array<{ request: string; asDeclared: boolean }>;\n /** The acknowledgment's own note, in the same form as the flags' notes. */\n note: string | SealedNoteV1 | null;\n signedAt: string;\n}\n\n/** What `POST /api/v1/s/:handle/acknowledgments` takes: the body and both signatures over its message, base64url. */\nexport interface SharedRecordAckEnvelopeV2 {\n body: SharedRecordAckBodyV2;\n signature: string;\n mldsaSignature: string;\n}\n\nconst MEMBERS = ['schema', 'reference', 'deviceId', 'keyId', 'check', 'sealHistoryDigest', 'disclosureDigest', 'counts', 'sample', 'answers', 'mismatches', 'flags', 'declaredFields', 'note', 'signedAt'] as const;\nconst HEX64 = /^[0-9a-f]{64}$/;\nconst DIGEST = /^(0x)?[0-9a-f]{64}$/;\nconst REFERENCE = /^SR-[0-9A-Za-z]{8}$/;\nconst CHECK_REF = /^CHK-\\d{4,8}$/;\nconst REQUEST_REF = /^Q-\\d{4,8}$/;\nconst DAY = /^\\d{4}-\\d{2}-\\d{2}$/;\nconst RFC3339_UTC = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,3})?Z$/;\n/** Free text: no control characters but the line break and tab. */\n// eslint-disable-next-line no-control-regex\nconst CONTROL = /[\\u0000-\\u0008\\u000b-\\u001f\\u007f]/;\n\nclass Problem extends Error {}\n\nconst isPlain = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);\n\nfunction exact(value: unknown, members: readonly string[], path: string): Record<string, unknown> {\n if (!isPlain(value)) throw new Problem(path || 'body');\n const at = (k: string) => (path ? `${path}.${k}` : k);\n for (const key of Object.keys(value)) if (!members.includes(key)) throw new Problem(`${at(key)}: not allowed`);\n for (const key of members) if (value[key] === undefined) throw new Problem(`${at(key)}: missing`);\n return value;\n}\n\nfunction natural(value: unknown, path: string, min = 0): number {\n if (!Number.isSafeInteger(value) || (value as number) < min) throw new Problem(path);\n return value as number;\n}\n\nfunction text(value: unknown, path: string, pattern: RegExp): string {\n if (typeof value !== 'string' || !pattern.test(value)) throw new Problem(path);\n return value;\n}\n\nfunction note(value: unknown, path: string, max: number): string | null {\n if (value === null) return null;\n if (typeof value !== 'string' || value.length === 0 || value.length > max || CONTROL.test(value) || value.trim() !== value) throw new Problem(path);\n return value;\n}\n\nfunction wordsOrSealed(value: unknown, path: string, max: number, sealedMax: number): string | SealedNoteV1 | null {\n if (value === null || typeof value === 'string') return note(value, path, max);\n const shape = readSealedNoteShapeV1(value);\n const v = value as SealedNoteV1;\n if (!shape.ok || v.ct.length > sealedMax) throw new Problem(path);\n return { schema: v.schema, iv: v.iv, ct: v.ct };\n}\n\n/** A flag note's words as a plaintext body carries them, or null when they are not (empty, too long, untrimmed, control characters). */\nexport function readSharedRecordAckFlagTextV2(value: unknown): string | null {\n try {\n return typeof value === 'string' ? note(value, 'note', SHARED_RECORD_ACK_FLAG_NOTE_MAX_V2) : null;\n } catch {\n return null;\n }\n}\n\n/** The acknowledgment's own note's words, read by the same rules at its own bound, or null. */\nexport function readSharedRecordAckNoteTextV2(value: unknown): string | null {\n try {\n return typeof value === 'string' ? note(value, 'note', SHARED_RECORD_ACK_NOTE_MAX_V2) : null;\n } catch {\n return null;\n }\n}\n\n/** Whether a note (a flag's, or the acknowledgment's own) is sealed. */\nexport const isSealedFlagNoteV2 = (n: string | SealedNoteV1 | null): n is SealedNoteV1 => n !== null && typeof n === 'object';\n\n/** Every note a body carries, the acknowledgment's own first, then each flag's. */\nexport const ackNotesV2 = (body: Pick<SharedRecordAckBodyV2, 'note' | 'flags'>): Array<string | SealedNoteV1 | null> => [body.note, ...body.flags.map((f) => f.note)];\n\nfunction list<T>(value: unknown, path: string, max: number, item: (v: unknown, p: string) => T): T[] {\n if (!Array.isArray(value) || value.length > max) throw new Problem(path);\n return value.map((v, i) => item(v, `${path}[${i}]`));\n}\n\nfunction entry(value: unknown, path: string, members: readonly string[] = ['record', 'entry']): SharedRecordAckEntryV2 & Record<string, unknown> {\n const v = exact(value, members, path);\n return { ...v, record: natural(v.record, `${path}.record`, 1), entry: natural(v.entry, `${path}.entry`, 1) };\n}\n\nfunction unique(items: SharedRecordAckEntryV2[], path: string): void {\n if (new Set(items.map((i) => `${i.record}:${i.entry}`)).size !== items.length) throw new Problem(path);\n}\n\nfunction parse(value: unknown): SharedRecordAckBodyV2 {\n if (!isPlain(value)) throw new Problem('body');\n let json: string;\n try {\n json = JSON.stringify(value);\n } catch {\n throw new Problem('body');\n }\n if (json.length > SHARED_RECORD_ACK_MAX_CHARS_V2) throw new Problem('too large');\n const v = exact(value, MEMBERS, '');\n if (v.schema !== SHARED_RECORD_ACK_SCHEMA_V2) throw new Problem('schema');\n const check = exact(v.check, ['ref', 'on'], 'check');\n const counts = exact(v.counts, ['records', 'entries', 'matched', 'notMatched'], 'counts');\n const answers = exact(v.answers, ['shown', 'declined'], 'answers');\n const mismatches = list(v.mismatches, 'mismatches', SHARED_RECORD_ACK_LIST_MAX_V2, (x, p) => {\n const e = entry(x, p);\n return { record: e.record, entry: e.entry };\n });\n unique(mismatches, 'mismatches');\n const flags = list(v.flags, 'flags', SHARED_RECORD_ACK_LIST_MAX_V2, (x, p) => {\n const e = entry(x, p, ['record', 'entry', 'result', 'note']);\n if (!SHARED_RECORD_ACK_FLAG_RESULTS_V2.includes(e.result as SharedRecordAckFlagResultV2)) throw new Problem(`${p}.result`);\n return { record: e.record, entry: e.entry, result: e.result as SharedRecordAckFlagResultV2, note: wordsOrSealed(e.note, `${p}.note`, SHARED_RECORD_ACK_FLAG_NOTE_MAX_V2, SHARED_RECORD_ACK_SEALED_FLAG_NOTE_MAX_CHARS_V2) };\n });\n unique(flags, 'flags');\n const ownNote = wordsOrSealed(v.note, 'note', SHARED_RECORD_ACK_NOTE_MAX_V2, SHARED_RECORD_ACK_SEALED_NOTE_MAX_CHARS_V2);\n const notes = [ownNote, ...flags.map((f) => f.note)];\n if (notes.some(isSealedFlagNoteV2) && notes.some((n) => typeof n === 'string')) throw new Problem('notes: sealed and plain notes together');\n const sample = list(v.sample, 'sample', SHARED_RECORD_ACK_SAMPLES_MAX_V2, (x, p) => {\n const s = exact(x, ['request', 'method', 'seed', 'picks'], p);\n if (s.method !== 'pacspace-sample/v1') throw new Problem(`${p}.method`);\n const picks = list(s.picks, `${p}.picks`, SHARED_RECORD_ACK_LIST_MAX_V2, (y, q) => {\n const e = entry(y, q);\n return { record: e.record, entry: e.entry };\n });\n unique(picks, `${p}.picks`);\n return { request: text(s.request, `${p}.request`, REQUEST_REF), method: 'pacspace-sample/v1' as const, seed: text(s.seed, `${p}.seed`, HEX64), picks };\n });\n const declaredFields = list(v.declaredFields, 'declaredFields', SHARED_RECORD_ACK_LIST_MAX_V2, (x, p) => {\n const d = exact(x, ['request', 'asDeclared'], p);\n if (typeof d.asDeclared !== 'boolean') throw new Problem(`${p}.asDeclared`);\n return { request: text(d.request, `${p}.request`, REQUEST_REF), asDeclared: d.asDeclared };\n });\n if (v.disclosureDigest !== null && (typeof v.disclosureDigest !== 'string' || !DIGEST.test(v.disclosureDigest))) throw new Problem('disclosureDigest');\n return {\n schema: SHARED_RECORD_ACK_SCHEMA_V2,\n reference: text(v.reference, 'reference', REFERENCE),\n deviceId: text(v.deviceId, 'deviceId', HEX64),\n keyId: text(v.keyId, 'keyId', HEX64),\n check: { ref: text(check.ref, 'check.ref', CHECK_REF), on: text(check.on, 'check.on', DAY) },\n sealHistoryDigest: text(v.sealHistoryDigest, 'sealHistoryDigest', DIGEST),\n disclosureDigest: v.disclosureDigest as string | null,\n counts: {\n records: natural(counts.records, 'counts.records'),\n entries: natural(counts.entries, 'counts.entries'),\n matched: natural(counts.matched, 'counts.matched'),\n notMatched: natural(counts.notMatched, 'counts.notMatched'),\n },\n sample,\n answers: { shown: natural(answers.shown, 'answers.shown'), declined: natural(answers.declined, 'answers.declined') },\n mismatches,\n flags,\n declaredFields,\n note: ownNote,\n signedAt: text(v.signedAt, 'signedAt', RFC3339_UTC),\n };\n}\n\n/** The body read member by member into a fresh object, or the first problem by its path. Never throws. */\nexport function readSharedRecordAckV2(value: unknown): { ok: true; body: SharedRecordAckBodyV2 } | { ok: false; problem: string } {\n try {\n return { ok: true, body: parse(value) };\n } catch (error) {\n if (error instanceof Problem) return { ok: false, problem: error.message };\n return { ok: false, problem: 'body' };\n }\n}\n\n/** The exact text both signatures cover: the label, a line break, and the body's JCS. */\nexport function sharedRecordAckMessageV2(body: SharedRecordAckBodyV2): string {\n return `${SHARED_RECORD_ACK_SIGNING_LABEL_V2}\\n${canonicalizeJcs(body)}`;\n}\n", "/**\n * An acknowledgment's notes, its flags' and its own, sealed in the reader's browser (records prototype build, R7; David,\n * 2026-10-26; ADR 0019's R7 addendum): one fresh key for every note in the body, each note a `sealed-note/v1` under it\n * with its own additional data and a random IV, and the key wrapped with BF's `wrapDisclosureKeyV1` to each of the\n * link's confirmed devices and to the workspace identity, then zeroed. The wraps travel beside the signed body, never\n * in it. Reached through the asymmetric subpath only, as BF's layer is.\n */\nimport { readSharedRecordAckFlagTextV2, readSharedRecordAckNoteTextV2 } from '../../records/shared-record-ack-v2';\nimport {\n ReaderCryptoError,\n ackFlagNoteNameV1,\n ackFlagNotesKeyNameV1,\n ackNoteNameV1,\n openNoteV1,\n sealNoteWithV1,\n LINK_KEY_BYTES_V1,\n type NoteNameV1,\n type SealedNoteV1,\n} from '../../records/reader-crypto-v1';\nimport { randomBytes } from '../platform-crypto';\nimport { unwrapNoteKeyV1, wrapNoteKeyV1 } from './reader-wraps-v1';\nimport type { KeyWrapV1, WorkspaceSeedV1 } from './records-asymmetric-v1';\n\n/** A confirmed device the notes are sealed to: its D-1 id and its X-Wing public key. */\nexport interface AckFlagNoteDeviceV1 {\n deviceId: string;\n xwingPublicKey: Uint8Array;\n}\n\n/** What `POST /acknowledgments` carries beside the body when its flag notes are sealed. */\nexport interface AckFlagNoteKeysV1 {\n devices: Array<{ deviceId: string; wrap: KeyWrapV1 }>;\n workspace: KeyWrapV1;\n}\n\n/**\n * Seals each flag's words, and the acknowledgment's own note when given, to every device given and to the workspace\n * identity's X-Wing key, which the caller has checked against the link's tag (`servedWorkspaceKeyV1` and\n * `workspaceKeyTagCommittedV1`). Returns the flags' notes in the order given, and the own note or null.\n */\nexport async function sealAckFlagNotesV1(input: {\n handle: string;\n checkRef: string;\n flags: ReadonlyArray<{ record: number; entry: number; text: string }>;\n note?: string | null;\n devices: readonly AckFlagNoteDeviceV1[];\n workspace: Uint8Array;\n}): Promise<{ notes: SealedNoteV1[]; note: SealedNoteV1 | null; keys: AckFlagNoteKeysV1 }> {\n const devices = input?.devices;\n if (!Array.isArray(devices) || devices.length === 0 || new Set(devices.map((d) => d?.deviceId)).size !== devices.length || !(input.workspace instanceof Uint8Array)) {\n throw new ReaderCryptoError('READER_DEVICE_KEYS_INVALID');\n }\n const own = input.note ?? null;\n if (!Array.isArray(input.flags) || input.flags.some((f) => readSharedRecordAckFlagTextV2(f?.text) === null)) throw new ReaderCryptoError('SEALED_NOTE_MALFORMED');\n if (own !== null && readSharedRecordAckNoteTextV2(own) === null) throw new ReaderCryptoError('SEALED_NOTE_MALFORMED');\n if (input.flags.length === 0 && own === null) throw new ReaderCryptoError('SEALED_NOTE_MALFORMED');\n const keyName = ackFlagNotesKeyNameV1(input.handle, input.checkRef);\n const key = randomBytes(LINK_KEY_BYTES_V1);\n try {\n const notes: SealedNoteV1[] = [];\n for (const f of input.flags) notes.push(await sealNoteWithV1(f.text, ackFlagNoteNameV1(input.handle, input.checkRef, f.record, f.entry), key, randomBytes(12)));\n const note = own === null ? null : await sealNoteWithV1(own, ackNoteNameV1(input.handle, input.checkRef), key, randomBytes(12));\n const wraps: AckFlagNoteKeysV1['devices'] = [];\n for (const d of devices) wraps.push({ deviceId: d.deviceId, wrap: await wrapNoteKeyV1(d.xwingPublicKey, key, keyName) });\n return { notes, note, keys: { devices: wraps, workspace: await wrapNoteKeyV1(input.workspace, key, keyName) } };\n } finally {\n key.fill(0);\n }\n}\n\n/** Opens the acknowledgment's own note with the wrap sealed to `seed`. Never throws. */\nexport async function openAckNoteV1(input: { note: unknown; wrap: unknown; seed: WorkspaceSeedV1; handle: string; checkRef: string }): Promise<{ ok: true; text: string } | { ok: false; code: string }> {\n return openUnder(input, () => ackNoteNameV1(input.handle, input.checkRef));\n}\n\nasync function openUnder(input: { note: unknown; wrap: unknown; seed: WorkspaceSeedV1; handle: string; checkRef: string }, name: () => NoteNameV1): Promise<{ ok: true; text: string } | { ok: false; code: string }> {\n try {\n const unwrapped = await unwrapNoteKeyV1({ seed: input.seed, wrap: input.wrap, name: ackFlagNotesKeyNameV1(input.handle, input.checkRef) });\n if (!unwrapped.ok) return { ok: false, code: unwrapped.code };\n try {\n return await openNoteV1({ note: input.note, key: unwrapped.disclosureKey, name: name() });\n } finally {\n unwrapped.disclosureKey.fill(0);\n }\n } catch {\n return { ok: false, code: 'SEALED_NOTE_AUTH_FAILED' };\n }\n}\n\n/** Opens one flagged entry's note with the wrap sealed to `seed`, under that entry's name only. Never throws. */\nexport async function openAckFlagNoteV1(input: {\n note: unknown;\n wrap: unknown;\n seed: WorkspaceSeedV1;\n handle: string;\n checkRef: string;\n record: number;\n entry: number;\n}): Promise<{ ok: true; text: string } | { ok: false; code: string }> {\n return openUnder(input, () => ackFlagNoteNameV1(input.handle, input.checkRef, input.record, input.entry));\n}\n", "/**\n * The trail index record (records prototype build, R4; \"Cryptography and proof\"; D-4, D-7, D-17): the entries\n * PacSpace writes, through the records system writer, on `machine-action-record/v1` under entity id\n * `trail-<trailId>` (never served) with origin `TRAIL_INDEX`.\n *\n * Every entry uses the content forms `record-content-v1.ts` accepts: a payload is `{alg, digest, byteLength}`\n * over the JCS bytes hashed, and a reference is `{recordKey, seq}`. No field holds the word for the thing\n * itself, a reader's name, a source's name, a label or an environment (the neutrality rules): readers receive\n * these entries. The scope and the reasons are the operator's own words for readers, the only free text. A\n * rule's labels are committed only inside the salted digest.\n */\nimport { ethers } from 'ethers';\nimport { canonicalizeJcs } from '../proof/jcs';\nimport type { TrailRuleV1 } from './trail-rule';\n\nexport const TRAIL_INDEX_RECORD_TYPE = 'machine-action-record';\nexport const TRAIL_INDEX_ACTOR = 'pacspace';\nexport const TRAIL_RULE_SALT_BYTES = 32;\n\nexport type TrailIndexKind =\n | 'rule-committed'\n | 'rule-changed'\n | 'scope-reworded'\n | 'record-joined'\n | 'record-removed'\n | 'entry-erased'\n | 'legal-hold-placed'\n | 'legal-hold-released';\n\nexport interface PayloadDigestV1 {\n alg: 'sha-256';\n digest: string;\n byteLength: string;\n}\n\nexport interface TrailIndexContentV1 {\n title: string;\n kind: TrailIndexKind;\n occurredAt: string;\n actorId: string;\n payloads: PayloadDigestV1[];\n description?: string;\n note?: string;\n references?: Array<{ recordKey: string; seq: number }>;\n}\n\n/** The record's entity id. */\nexport function trailIndexEntityId(trailId: string): string {\n return `trail-${trailId}`;\n}\n\n/** The idempotency key of a trail event's index entry. */\nexport function trailEventIdempotencyKey(trailId: string, seq: number): string {\n return `trail:${trailId}:event:${seq}`;\n}\n\nfunction base64url(bytes: Uint8Array): string {\n return ethers.encodeBase64(bytes).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\n/** The payload form over the JCS of a value: SHA-256 of its UTF-8 bytes, and their length. */\nexport function payloadDigestV1(value: unknown): PayloadDigestV1 {\n const bytes = ethers.toUtf8Bytes(canonicalizeJcs(value));\n return { alg: 'sha-256', digest: ethers.sha256(bytes).slice(2), byteLength: String(bytes.length) };\n}\n\n/** What a rule's digest commits: the rule and its salt, so equal rules on two trails commit different digests. */\nexport function trailRuleDigestInput(rule: TrailRuleV1, salt: Uint8Array): { v: 1; rule: TrailRuleV1; salt: string } {\n if (salt.length !== TRAIL_RULE_SALT_BYTES) throw new Error(`A rule's salt is ${TRAIL_RULE_SALT_BYTES} bytes.`);\n return { v: 1, rule, salt: base64url(salt) };\n}\n\n/** The close's facts a join commits (D-7). */\nexport interface TrailJoinFactsV1 {\n recordKey: string;\n lastSeq: number;\n lastSeal: string;\n closedBy: 'code' | 'timeout';\n number: number;\n ruleVersion: number;\n}\n\n/** UTC to the second, as entries carry it. */\nexport function trailIndexTime(at: Date): string {\n return at.toISOString().replace(/\\.\\d{3}Z$/, 'Z');\n}\n\nconst base = (title: string, kind: TrailIndexKind, at: Date, payload: PayloadDigestV1) => ({\n title,\n kind,\n occurredAt: trailIndexTime(at),\n actorId: TRAIL_INDEX_ACTOR,\n payloads: [payload],\n});\n\n/** \"Rule committed\": the scope as the description, and the salted rule's digest. */\nexport function ruleCommittedContentV1(input: { scope: string; rule: TrailRuleV1; salt: Uint8Array; at: Date }): TrailIndexContentV1 {\n return { ...base('Rule committed', 'rule-committed', input.at, payloadDigestV1(trailRuleDigestInput(input.rule, input.salt))), description: input.scope };\n}\n\n/** \"Rule changed\": the new salted rule's digest, and the reason. */\nexport function ruleChangedContentV1(input: { rule: TrailRuleV1; salt: Uint8Array; reason: string; at: Date }): TrailIndexContentV1 {\n return { ...base('Rule changed', 'rule-changed', input.at, payloadDigestV1(trailRuleDigestInput(input.rule, input.salt))), note: input.reason };\n}\n\n/** \"Scope reworded\": the new scope and the reason; the payload is the digest of both. */\nexport function scopeRewordedContentV1(input: { scope: string; reason: string; at: Date }): TrailIndexContentV1 {\n return {\n ...base('Scope reworded', 'scope-reworded', input.at, payloadDigestV1({ scope: input.scope, reason: input.reason })),\n description: input.scope,\n note: input.reason,\n };\n}\n\n/** \"Record {n} joined\": the member's last entry at its close, and the digest of the close's facts. */\nexport function recordJoinedContentV1(input: TrailJoinFactsV1 & { at: Date }): TrailIndexContentV1 {\n const facts: TrailJoinFactsV1 = {\n recordKey: input.recordKey.toLowerCase(),\n lastSeq: input.lastSeq,\n lastSeal: input.lastSeal.toLowerCase(),\n closedBy: input.closedBy,\n number: input.number,\n ruleVersion: input.ruleVersion,\n };\n return {\n ...base(`Record ${input.number} joined`, 'record-joined', input.at, payloadDigestV1(facts)),\n references: [{ recordKey: facts.recordKey, seq: facts.lastSeq }],\n };\n}\n\n/**\n * \"Record {n} removed\": the member's last entry at its close, and the reason. `n` is the member's number, the same\n * `n` its \"Record {n} joined\" entry committed; the payload's digest also names that join's event number on the\n * trail (`joinedEvent`), so the removal is bound to the one join it takes back.\n */\nexport function recordRemovedContentV1(input: { number: number; joinedEvent: number; recordKey: string; lastSeq: number; reason: string; at: Date }): TrailIndexContentV1 {\n const recordKey = input.recordKey.toLowerCase();\n const facts = { recordKey, lastSeq: input.lastSeq, number: input.number, joinedEvent: input.joinedEvent, reason: input.reason };\n return {\n ...base(`Record ${input.number} removed`, 'record-removed', input.at, payloadDigestV1(facts)),\n references: [{ recordKey, seq: input.lastSeq }],\n note: input.reason,\n };\n}\n\n/**\n * G3 (D-33): \"Record {n} entry {seq} erased\", with the reason the operator chose. It references the entry, whose leaf,\n * seal and number stay committed, so every check of it is unchanged.\n */\nexport function entryErasedContentV1(input: { number: number; recordKey: string; seq: number; reason: string; at: Date }): TrailIndexContentV1 {\n const recordKey = input.recordKey.toLowerCase();\n const facts = { number: input.number, recordKey, seq: input.seq, reason: input.reason };\n return {\n ...base(`Record ${input.number} entry ${input.seq} erased`, 'entry-erased', input.at, payloadDigestV1(facts)),\n references: [{ recordKey, seq: input.seq }],\n note: input.reason,\n };\n}\n\n/**\n * G3 (D-33): a legal hold on the whole of what the index record covers, or on one of its records by number. Never\n * served to readers, and it names no person: the hold's id binds its release to it.\n */\nexport function legalHoldPlacedContentV1(input: {\n holdId: string;\n on: 'whole' | { number: number; recordKey: string };\n reason: string;\n at: Date;\n}): TrailIndexContentV1 {\n const on = input.on === 'whole' ? 'whole' : { number: input.on.number, recordKey: input.on.recordKey.toLowerCase() };\n return { ...base('Legal hold placed', 'legal-hold-placed', input.at, payloadDigestV1({ holdId: input.holdId, on, reason: input.reason })), note: input.reason };\n}\n\n/** G3 (D-33): the release of the hold whose id it names, with its reason. */\nexport function legalHoldReleasedContentV1(input: { holdId: string; reason: string; at: Date }): TrailIndexContentV1 {\n return { ...base('Legal hold released', 'legal-hold-released', input.at, payloadDigestV1({ holdId: input.holdId, reason: input.reason })), note: input.reason };\n}\n", "/**\n * The link's reader record (records prototype build, R5; \"Cryptography and proof\"; D-3, D-17, D-21, D-24): the\n * entries PacSpace writes, through the records system writer, on `machine-action-record/v1` under entity id\n * `share-<shareId>` (never served) with origin `READER_LINK`.\n *\n * Every entry uses the content forms `record-content-v1.ts` accepts, as the trail index record's do. No field\n * holds a person's name or address, the reader's organisation, the word for the thing shared, a source, a label\n * or an environment: readers receive these entries. People are committed by count and epoch only.\n */\nimport { payloadDigestV1, trailIndexTime, TRAIL_INDEX_ACTOR, TRAIL_INDEX_RECORD_TYPE, type PayloadDigestV1 } from './trail-index-v1';\nimport type { SharedRecordAckBodyV2 } from './shared-record-ack-v2';\n\nexport const READER_LINK_RECORD_TYPE = TRAIL_INDEX_RECORD_TYPE;\n\n/** The reader's citable reference: `SR-` plus 8 base62 characters, drawn apart from the handle (D-3). */\nexport const SHARE_REFERENCE_PATTERN = /^SR-[0-9A-Za-z]{8}$/;\nexport const SHARE_REFERENCE_ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';\n\n/** A link's access code: two groups of four from the prototype's alphabet (no I, O, 0 or 1). */\nexport const SHARE_CODE_PATTERN = /^[A-Z2-9]{4}-[A-Z2-9]{4}$/;\nexport const SHARE_CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';\n\n/** Wrong codes in a row before a link's code stops (E-15). */\nexport const SHARE_CODE_TRIES = 5;\n\nexport type ReaderLinkKind =\n | 'link-made'\n | 'allowance-changed'\n | 'link-extended'\n | 'person-added'\n | 'person-removed'\n | 'link-key-changed'\n | 'workspace-key-changed'\n | 'record-revealed'\n | 'link-turned-off'\n | 'device-added'\n | 'device-confirmed'\n | 'device-removed'\n | 'request'\n | 'answer'\n | 'acknowledgment'\n | 'flag'\n | 'flag-message';\n\nexport interface ReaderLinkContentV1 {\n title: string;\n kind: ReaderLinkKind;\n occurredAt: string;\n actorId: string;\n payloads: PayloadDigestV1[];\n references?: Array<{ recordKey: string; seq: number }>;\n}\n\nexport type RevealModeV1 = 'seals' | 'fields' | 'all';\nexport type AnswersByV1 = 'people' | 'agent';\n\n/** What a link commits about what it reveals, who answers and when (D-21, D-22, D-38). */\nexport interface ReaderLinkTermsV1 {\n reference: string;\n allowance: number | null;\n endsOn: string;\n reveal: { mode: RevealModeV1; fields: string[]; time: boolean };\n answers: { by: AnswersByV1; fields: string[] };\n responseDays: number | null;\n}\n\n/** The record's entity id. */\nexport function readerLinkEntityId(shareId: string): string {\n return `share-${shareId}`;\n}\n\n/** The idempotency key of a link event's reader record entry. */\nexport function shareEventIdempotencyKey(shareId: string, seq: number): string {\n return `share:${shareId}:event:${seq}`;\n}\n\nconst base = (title: string, kind: ReaderLinkKind, at: Date, payload: PayloadDigestV1): ReaderLinkContentV1 => ({\n title,\n kind,\n occurredAt: trailIndexTime(at),\n actorId: TRAIL_INDEX_ACTOR,\n payloads: [payload],\n});\n\nconst sorted = (values: readonly string[]) => [...values].sort();\n\n/**\n * \"Link made\": the digest of the link's terms, never a person's name or address; in an encrypted workspace, a second\n * payload commits the lab's tag of the workspace key for epoch 1.\n */\nexport function linkMadeContentV1(input: ReaderLinkTermsV1 & { workspaceKeyTag?: string | null; at: Date }): ReaderLinkContentV1 {\n const terms: ReaderLinkTermsV1 = {\n reference: input.reference,\n allowance: input.allowance,\n endsOn: input.endsOn,\n reveal: { mode: input.reveal.mode, fields: sorted(input.reveal.fields), time: input.reveal.time },\n answers: { by: input.answers.by, fields: sorted(input.answers.fields) },\n responseDays: input.responseDays,\n };\n return withKeyTag(base('Link made', 'link-made', input.at, payloadDigestV1(terms)), 1, input.workspaceKeyTag);\n}\n\n/**\n * The payload that commits the lab's tag of the workspace key for an epoch (R7; David, 2026-10-26), on \"Link made\"\n * (epoch 1) and \"Link key changed\": a reader's browser checks the tag it is served against this, on the link's own\n * record, as well as under its proof key, so a tag PacSpace serves later than the one committed does not hold.\n */\nexport function workspaceKeyTagPayloadV1(epoch: number, workspaceKeyTag: string): PayloadDigestV1 {\n return payloadDigestV1({ epoch, workspaceKeyTag });\n}\n\nconst withKeyTag = (content: ReaderLinkContentV1, epoch: number, tag: string | null | undefined): ReaderLinkContentV1 =>\n typeof tag === 'string' ? { ...content, payloads: [...content.payloads, workspaceKeyTagPayloadV1(epoch, tag)] } : content;\n\n/** \"Allowance changed\": the new allowance and the one before it. */\nexport function allowanceChangedContentV1(input: { allowance: number | null; from: number | null; at: Date }): ReaderLinkContentV1 {\n return base('Allowance changed', 'allowance-changed', input.at, payloadDigestV1({ allowance: input.allowance, from: input.from }));\n}\n\n/** \"Link extended\": the new last day. */\nexport function linkExtendedContentV1(input: { endsOn: string; at: Date }): ReaderLinkContentV1 {\n return base('Link extended', 'link-extended', input.at, payloadDigestV1({ endsOn: input.endsOn }));\n}\n\n/** \"Person added\" and \"Person removed\": how many people the link has after, and the link key's epoch. */\nexport function personChangedContentV1(input: { change: 'added' | 'removed'; count: number; epoch: number; at: Date }): ReaderLinkContentV1 {\n const added = input.change === 'added';\n return base(added ? 'Person added' : 'Person removed', added ? 'person-added' : 'person-removed', input.at, payloadDigestV1({ count: input.count, epoch: input.epoch }));\n}\n\n/** \"Link key changed\": the new epoch (a person removed), and in an encrypted workspace the tag for it. */\nexport function linkKeyChangedContentV1(input: { epoch: number; workspaceKeyTag?: string | null; at: Date }): ReaderLinkContentV1 {\n return withKeyTag(base('Link key changed', 'link-key-changed', input.at, payloadDigestV1({ epoch: input.epoch })), input.epoch, input.workspaceKeyTag);\n}\n\n/**\n * \"Workspace key changed\" (R7; David, 2026-10-26): after the workspace identity is rotated, the lab's tag of the new key\n * for the link's current epoch, which takes the place of the epoch's earlier tag. The link key and its epoch stay.\n */\nexport function workspaceKeyChangedContentV1(input: { epoch: number; workspaceKeyTag: string; at: Date }): ReaderLinkContentV1 {\n return withKeyTag(base('Workspace key changed', 'workspace-key-changed', input.at, payloadDigestV1({ epoch: input.epoch })), input.epoch, input.workspaceKeyTag);\n}\n\n/**\n * Whether `tag` is the tag the link's own record committed last for `epoch` (R7; ADR 0019's R7 addendum): the reader's\n * browser calls this before it seals anything to the workspace, after `servedWorkspaceKeyV1`. `entries` is the content\n * of every entry of the link's record, seq 0 upward with none left out, each read from a receipt the browser has\n * checked against the chain (`GET /api/v1/s/:handle/link-record`), and `committedEntries` the number of entries the\n * record's seal history holds once it, too, is checked against the chain's current word. Anything less holds nothing,\n * since a left-out entry, the last included, could be the one that replaced the tag. The tag of an epoch is the last\n * of \"Link made\" (epoch 1), \"Link key changed\" and \"Workspace key changed\" for it; a later entry for the epoch with no\n * tag leaves it untagged.\n */\nexport function workspaceKeyTagCommittedV1(entries: ReadonlyArray<{ seq: number; content: unknown }>, committedEntries: number, epoch: number, tag: string): boolean {\n if (typeof tag !== 'string' || !/^[0-9a-f]{64}$/.test(tag)) return false;\n const latest = lastWorkspaceKeyTagDigestV1(entries, committedEntries, epoch);\n return latest !== null && latest === workspaceKeyTagPayloadV1(epoch, tag).digest;\n}\n\n/**\n * The digest of the tag the link's own record committed last for `epoch`, read as `workspaceKeyTagCommittedV1` reads\n * it, or null where the record commits none for the epoch or is read short. Null is how a link that keeps no key reads\n * on its own record: one made while the workspace was plaintext commits no tag, and a key PacSpace served of its own\n * cannot be told from it by the served flag alone (U3r security review; David, 2026-11-03).\n */\nexport function lastWorkspaceKeyTagDigestV1(entries: ReadonlyArray<{ seq: number; content: unknown }>, committedEntries: number, epoch: number): string | null {\n if (!Array.isArray(entries) || !Number.isSafeInteger(epoch) || epoch < 1) return null;\n if (!Number.isSafeInteger(committedEntries) || entries.length !== committedEntries) return null;\n const sorted = [...entries].sort((a, b) => a.seq - b.seq);\n if (sorted.some((e, i) => e.seq !== i)) return null;\n const epochDigest = payloadDigestV1({ epoch }).digest;\n let latest: string | null = null;\n for (const { content } of sorted) {\n const c = content as { kind?: unknown; payloads?: unknown } | null;\n if (!c || typeof c !== 'object' || !Array.isArray(c.payloads)) continue;\n const payloads = c.payloads as Array<{ digest?: unknown } | null>;\n const forEpoch =\n c.kind === 'link-made' ? epoch === 1 : (c.kind === 'link-key-changed' || c.kind === 'workspace-key-changed') && payloads[0]?.digest === epochDigest;\n if (!forEpoch) continue;\n const tagged = payloads[1]?.digest;\n latest = typeof tagged === 'string' ? tagged : null;\n }\n return latest;\n}\n\n/** \"Record {n} revealed\": the member's last entry, and the digest of the reveal's ciphertext as uploaded. */\nexport function recordRevealedContentV1(input: { number: number; recordKey: string; lastSeq: number; envelope: string; at: Date }): ReaderLinkContentV1 {\n return {\n ...base(`Record ${input.number} revealed`, 'record-revealed', input.at, payloadDigestV1({ envelope: input.envelope })),\n references: [{ recordKey: input.recordKey.toLowerCase(), seq: input.lastSeq }],\n };\n}\n\n/** \"Link turned off\". */\nexport function linkTurnedOffContentV1(input: { at: Date }): ReaderLinkContentV1 {\n return base('Link turned off', 'link-turned-off', input.at, payloadDigestV1({ turnedOffOn: trailIndexTime(input.at).slice(0, 10) }));\n}\n\n/** How a device was confirmed (D-16): its code read back, a proof of the link key, or another confirmed device. */\nexport type DeviceConfirmedByV1 = 'code' | 'proof' | 'device';\nexport type DeviceKindV1 = 'browser' | 'agent';\n\n/** \"Device added\", \"Device confirmed\" and \"Device removed\": the device's code, its kind and how it was confirmed. */\nexport function deviceChangedContentV1(input: {\n change: 'added' | 'confirmed' | 'removed';\n code: string;\n kind: DeviceKindV1;\n confirmedBy: DeviceConfirmedByV1 | null;\n at: Date;\n}): ReaderLinkContentV1 {\n const titles = { added: 'Device added', confirmed: 'Device confirmed', removed: 'Device removed' } as const;\n return base(titles[input.change], `device-${input.change}`, input.at, payloadDigestV1({ code: input.code, kind: input.kind, confirmedBy: input.confirmedBy }));\n}\n\n/** A request's pick as committed: the member's number, the entry, the seal served for it, and how it was picked. */\nexport interface RequestItemV1 {\n number: number;\n seq: number;\n seal: string;\n picked: 'random' | 'chosen' | 'mismatch';\n}\n\n/** `pacspace-sample/v1` as a request commits it (D-14). */\nexport interface RequestSampleV1 {\n method: 'pacspace-sample/v1';\n seed: string;\n poolDigest: string;\n poolSize: number;\n leftOut: Array<{ number: number; seq: number }>;\n spread: 'any' | 'records' | 'days';\n removed: Array<{ number: number; seq: number }>;\n}\n\n/** What a request's entry commits: its picks, the sample, the question, and what the server worked out. */\nexport interface RequestManifestV1 {\n ref: string;\n items: RequestItemV1[];\n sample: RequestSampleV1 | null;\n question: string | null;\n beyond: number;\n dueOn: string | null;\n}\n\n/** \"Request {Q-ref}\": references each asked entry; the payload is the digest of the request manifest, the sample included. */\nexport function requestContentV1(input: { manifest: RequestManifestV1; recordKeys: ReadonlyMap<number, string>; at: Date }): ReaderLinkContentV1 {\n const references = input.manifest.items.map((i) => {\n const recordKey = input.recordKeys.get(i.number);\n if (!recordKey) throw new Error('every asked entry names its record');\n return { recordKey: recordKey.toLowerCase(), seq: i.seq };\n });\n return { ...base(`Request ${input.manifest.ref}`, 'request', input.at, payloadDigestV1(input.manifest)), references };\n}\n\n/** Why an entry was declined, in the answer form's reasons, or Other with its sentence. */\nexport type AnswerDeclineV1 = { kind: 'legal_hold' | 'personal_data' | 'beyond_sample' | 'past_retention' } | { kind: 'other'; note: string };\n\n/** One item of an answer: shown with its declared fields and its disclosure's digest, or declined with its reason. Never a value. */\nexport type AnswerItemV1 =\n | { number: number; seq: number; outcome: 'shown'; declaredFields: string[]; disclosureDigest: string }\n | { number: number; seq: number; outcome: 'declined'; reason: AnswerDeclineV1 };\n\n/** What an answer's entry commits (D-22): the outcomes, the declared field names, the reasons, who sent it, each disclosure's digest, and the reply's. */\nexport interface AnswerManifestV1 {\n ref: string;\n items: AnswerItemV1[];\n replyDigest: string | null;\n sentBy: 'person' | 'agent';\n}\n\n/** \"Answer to {Q-ref}\": the digest of the answer manifest. */\nexport function answerContentV1(input: { manifest: AnswerManifestV1; at: Date }): ReaderLinkContentV1 {\n return base(`Answer to ${input.manifest.ref}`, 'answer', input.at, payloadDigestV1(input.manifest));\n}\n\n/** A reader's acknowledgment on a link, ACK-0001 and up. */\nexport const ACKNOWLEDGMENT_REF_PATTERN = /^ACK-\\d{4,6}$/;\n\n/** \"Acknowledgment {ACK-ref}\" (R7): the digest of the `shared-record-ack/v2` body both signatures cover. */\nexport function acknowledgmentContentV1(input: { ref: string; body: SharedRecordAckBodyV2; at: Date }): ReaderLinkContentV1 {\n if (!ACKNOWLEDGMENT_REF_PATTERN.test(input.ref)) throw new Error('an acknowledgment is numbered ACK-0001 and up');\n return base(`Acknowledgment ${input.ref}`, 'acknowledgment', input.at, payloadDigestV1(input.body));\n}\n", "/**\n * Flag threads (records prototype build, FL1; HANDOFF \"Flags\"; ADR 0019; D-1): what the reader, the lab's side and\n * PacSpace agree on for a thread `FL-0001` and up on a trail link, and for the team's flags not sent yet.\n *\n * A thread's notes are sealed in the browser that writes them with `sealed-note/v1` under `flagNoteNameV1`: the lab's\n * answer to every confirmed device of the link and to the workspace identity, the reader's reply to the workspace\n * identity and the link's confirmed devices, so both sides read the whole thread and PacSpace reads neither. In a\n * plaintext workspace PacSpace keeps the entries' words itself, so a thread's notes are kept as `plain-note/v1`, each\n * with a salt of its own so the digest the reader record commits can't be matched against guessed words.\n *\n * The team's flags not sent yet (`flag-drafts/v1`) are sealed to the link's confirmed devices only, never to the\n * workspace identity: the lab never sees a flag before the team sends it.\n *\n * Nothing here logs, and no refusal carries a note.\n */\nimport { canonicalizeJcs } from '../proof/jcs';\nimport { fromBase64Url, toBase64Url } from '../records-crypto/base64url';\nimport { randomBytes, sha256, utf8 } from '../records-crypto/platform-crypto';\nimport { ReaderCryptoError, readSealedNoteShapeV1, type NoteNameV1, type SealedNoteV1 } from './reader-crypto-v1';\nimport { SHARE_REFERENCE_PATTERN } from './reader-link-v1';\n\n/** A thread's reference on its link. */\nexport const FLAG_REF_PATTERN_V1 = /^FL-\\d{4,6}$/;\n/** A flagged entry's result as the reader's check found it (R7's `shared-record-ack/v2` flags carry the same three). */\nexport const FLAG_RESULTS_V1 = ['matches', 'does-not-match', 'copy-differs'] as const;\nexport type FlagResultV1 = (typeof FLAG_RESULTS_V1)[number];\nexport type FlagStatusV1 = 'open' | 'answered' | 'closed';\n\n/** An answer's or a reply's words, before they are sealed. */\nexport const FLAG_TEXT_MAX_V1 = 2000;\n/** A sealed answer or reply at most this long as text: 2000 characters of four UTF-8 bytes, with the tag. */\nexport const FLAG_SEALED_NOTE_MAX_CHARS_V1 = Math.ceil(((FLAG_TEXT_MAX_V1 * 4 + 16) * 4) / 3);\n/** As many flags as one acknowledgment carries, each note as long as one there. */\nexport const FLAG_DRAFTS_MAX_V1 = 100;\nexport const FLAG_DRAFT_NOTE_MAX_V1 = 500;\n\nexport const PLAIN_NOTE_SCHEMA_V1 = 'plain-note/v1' as const;\nexport const FLAG_DRAFTS_SCHEMA_V1 = 'flag-drafts/v1' as const;\nconst PLAIN_NOTE_SALT_BYTES = 16;\n\nconst HEX = (bytes: Uint8Array) => Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\n/** Free text: no control characters but the line break and tab. */\n// eslint-disable-next-line no-control-regex\nconst CONTROL = /[\\u0000-\\u0008\\u000b-\\u001f\\u007f]/;\nconst isPlain = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);\nconst exactly = (v: Record<string, unknown>, keys: readonly string[]) => Object.keys(v).length === keys.length && keys.every((k) => Object.prototype.hasOwnProperty.call(v, k));\nconst counting = (n: unknown, min: number): n is number => Number.isSafeInteger(n) && (n as number) >= min;\n\n/** `FL-0001` for the first thread on a link. */\nexport function flagRefV1(n: number): string {\n if (!counting(n, 1) || n > 999_999) throw new ReaderCryptoError('READER_BINDING_INVALID');\n return `FL-${String(n).padStart(4, '0')}`;\n}\n\n/**\n * A thread note's name: `{handle}:flag-answer:{FL-ref}:{n}` or `{handle}:flag-reply:{FL-ref}:{n}`, `n` the message's\n * number on its thread, so a note opens under its own link, thread, kind and place, and no other.\n */\nexport function flagNoteNameV1(input: { handle: string; kind: 'answer' | 'reply'; ref: string; n: number }): NoteNameV1 {\n if ((input?.kind !== 'answer' && input?.kind !== 'reply') || typeof input.ref !== 'string' || !FLAG_REF_PATTERN_V1.test(input.ref) || !counting(input.n, 1)) {\n throw new ReaderCryptoError('READER_BINDING_INVALID');\n }\n const name: NoteNameV1 = { scope: { handle: input.handle }, kind: `flag-${input.kind}`, ref: input.ref, n: input.n };\n assertHandle(input.handle);\n return name;\n}\n\n/** The team's drafts' name: `{handle}:flag-drafts:{SR-reference}:{version}`, the version they are saved as. */\nexport function flagDraftsNoteNameV1(input: { handle: string; reference: string; version: number }): NoteNameV1 {\n if (typeof input?.reference !== 'string' || !SHARE_REFERENCE_PATTERN.test(input.reference) || !counting(input.version, 1)) {\n throw new ReaderCryptoError('READER_BINDING_INVALID');\n }\n assertHandle(input.handle);\n return { scope: { handle: input.handle }, kind: 'flag-drafts', ref: input.reference, n: input.version };\n}\n\nfunction assertHandle(handle: unknown): void {\n if (typeof handle !== 'string' || !/^csh1_[A-Za-z0-9_-]{1,80}$/.test(handle)) throw new ReaderCryptoError('READER_BINDING_INVALID');\n}\n\n/** An answer's or reply's words as they are sent: trimmed, not empty, at most 2000 characters; null otherwise. */\nexport function readFlagTextV1(value: unknown): string | null {\n if (typeof value !== 'string') return null;\n const text = value.trim();\n if (!text || text.length > FLAG_TEXT_MAX_V1 || CONTROL.test(text)) return null;\n return text;\n}\n\n// ------------------------------------------------------------------ plain-note/v1 (a plaintext workspace)\n\nexport interface PlainNoteV1 {\n schema: typeof PLAIN_NOTE_SCHEMA_V1;\n text: string;\n salt: string;\n}\n\n/** A plaintext workspace's note, with a fresh 16-byte salt; refuses words `readFlagTextV1` refuses. */\nexport function plainNoteV1(value: string): PlainNoteV1 {\n const text = readFlagTextV1(value);\n if (text === null) throw new ReaderCryptoError('SEALED_NOTE_MALFORMED');\n return { schema: PLAIN_NOTE_SCHEMA_V1, text, salt: toBase64Url(randomBytes(PLAIN_NOTE_SALT_BYTES)) };\n}\n\n/** The keyless checks of a plain note: its three members, its words, and a 16-byte salt. Never throws. */\nexport function readPlainNoteV1(value: unknown): { ok: true; text: string } | { ok: false } {\n if (!isPlain(value) || !exactly(value, ['schema', 'text', 'salt']) || value.schema !== PLAIN_NOTE_SCHEMA_V1) return { ok: false };\n const text = readFlagTextV1(value.text);\n const salt = typeof value.salt === 'string' ? fromBase64Url(value.salt) : null;\n if (text === null || text !== value.text || !salt || salt.length !== PLAIN_NOTE_SALT_BYTES || toBase64Url(salt) !== value.salt) return { ok: false };\n return { ok: true, text };\n}\n\n/** A sealed answer or reply's keyless checks, within the size its words allow. */\nexport function readFlagSealedNoteV1(value: unknown): SealedNoteV1 | null {\n if (!readSealedNoteShapeV1(value).ok) return null;\n const v = value as SealedNoteV1;\n if (v.ct.length > FLAG_SEALED_NOTE_MAX_CHARS_V1) return null;\n return { schema: v.schema, iv: v.iv, ct: v.ct };\n}\n\n/** SHA-256 of a thread note's JCS, 64 lowercase hex: what the reader record commits for it. */\nexport async function flagNoteDigestV1(note: SealedNoteV1 | PlainNoteV1): Promise<string> {\n return HEX(await sha256(utf8(canonicalizeJcs(note))));\n}\n\n// ------------------------------------------------------------------ flag-drafts/v1 (the team's, sealed to its devices)\n\nexport interface FlagDraftV1 {\n /** The record's number on the link. */\n record: number;\n /** The entry, from 1, as the reader reads it. */\n entry: number;\n note: string | null;\n}\n\nexport interface FlagDraftsV1 {\n schema: typeof FLAG_DRAFTS_SCHEMA_V1;\n flags: FlagDraftV1[];\n}\n\n/** The drafts read member by member into a fresh object; each entry flagged once. Never throws. */\nexport function readFlagDraftsV1(value: unknown): { ok: true; drafts: FlagDraftsV1 } | { ok: false } {\n const bad = { ok: false as const };\n if (!isPlain(value) || !exactly(value, ['schema', 'flags']) || value.schema !== FLAG_DRAFTS_SCHEMA_V1) return bad;\n if (!Array.isArray(value.flags) || value.flags.length > FLAG_DRAFTS_MAX_V1) return bad;\n const seen = new Set<string>();\n const flags: FlagDraftV1[] = [];\n for (const raw of value.flags) {\n if (!isPlain(raw) || !exactly(raw, ['record', 'entry', 'note']) || !counting(raw.record, 1) || !counting(raw.entry, 1)) return bad;\n const key = `${raw.record}:${raw.entry}`;\n if (seen.has(key)) return bad;\n seen.add(key);\n let note: string | null = null;\n if (raw.note !== null) {\n if (typeof raw.note !== 'string' || !raw.note || raw.note.length > FLAG_DRAFT_NOTE_MAX_V1 || CONTROL.test(raw.note)) return bad;\n note = raw.note;\n }\n flags.push({ record: raw.record as number, entry: raw.entry as number, note });\n }\n return { ok: true, drafts: { schema: FLAG_DRAFTS_SCHEMA_V1, flags } };\n}\n", "/**\n * Flag notes and the team's drafts, sealed where they are written (records prototype build, FL1; ADR 0019; D-1):\n * `sealed-note/v1` under a fresh key, the key wrapped with BF's `wrapDisclosureKeyV1` under the note's own typed\n * binding (`wrapNoteKeyV1`), then zeroed. A thread's answer or reply is wrapped to the link's confirmed devices and,\n * in an encrypted workspace, to the workspace identity; the team's drafts to the link's confirmed devices only, and\n * this module offers no way to wrap them to anything else. Reached through the asymmetric subpath only, as BF's layer is.\n */\nimport { flagDraftsNoteNameV1, readFlagDraftsV1, readFlagTextV1, type FlagDraftsV1 } from '../../records/flag-threads-v1';\nimport { ReaderCryptoError, openNoteV1, sealNoteV1, type NoteNameV1, type SealedNoteV1 } from '../../records/reader-crypto-v1';\nimport { unwrapNoteKeyV1, wrapNoteKeyV1 } from './reader-wraps-v1';\nimport type { KeyWrapV1, WorkspaceSeedV1 } from './records-asymmetric-v1';\n\n/** A confirmed device a note is sealed to: its D-1 id and its X-Wing public key. */\nexport interface FlagNoteDeviceV1 {\n deviceId: string;\n xwingPublicKey: Uint8Array;\n}\n\nexport interface SealedFlagNoteV1 {\n note: SealedNoteV1;\n wraps: Array<{ deviceId: string; wrap: KeyWrapV1 }>;\n}\n\nasync function sealTo(text: string, name: NoteNameV1, devices: readonly FlagNoteDeviceV1[], workspace: Uint8Array | null) {\n if (!Array.isArray(devices) || new Set(devices.map((d) => d?.deviceId)).size !== devices.length || (devices.length === 0 && workspace === null)) {\n throw new ReaderCryptoError('READER_DEVICE_KEYS_INVALID');\n }\n const { note, key } = await sealNoteV1(text, name);\n try {\n const wraps: SealedFlagNoteV1['wraps'] = [];\n for (const d of devices) wraps.push({ deviceId: d.deviceId, wrap: await wrapNoteKeyV1(d.xwingPublicKey, key, name) });\n return { note, wraps, workspace: workspace ? await wrapNoteKeyV1(workspace, key, name) : null };\n } finally {\n key.fill(0);\n }\n}\n\n/** An answer or a reply, sealed to each device given and, when given, the workspace identity's X-Wing key. */\nexport async function sealFlagNoteV1(input: { text: string; name: NoteNameV1; devices: readonly FlagNoteDeviceV1[]; workspace: Uint8Array | null }): Promise<SealedFlagNoteV1 & { workspace: KeyWrapV1 | null }> {\n const text = readFlagTextV1(input?.text);\n if (text === null) throw new ReaderCryptoError('SEALED_NOTE_MALFORMED');\n return sealTo(text, input.name, input.devices, input.workspace ?? null);\n}\n\n/** Opens a thread note with the wrap sealed to `seed`, under the note's own name. Never throws. */\nexport async function openFlagNoteV1(input: { note: unknown; wrap: unknown; seed: WorkspaceSeedV1; name: NoteNameV1 }): Promise<{ ok: true; text: string } | { ok: false; code: string }> {\n try {\n const unwrapped = await unwrapNoteKeyV1({ seed: input.seed, wrap: input.wrap, name: input.name });\n if (!unwrapped.ok) return { ok: false, code: unwrapped.code };\n try {\n return await openNoteV1({ note: input.note, key: unwrapped.disclosureKey, name: input.name });\n } finally {\n unwrapped.disclosureKey.fill(0);\n }\n } catch {\n return { ok: false, code: 'SEALED_NOTE_AUTH_FAILED' };\n }\n}\n\n/** The team's drafts, as `flag-drafts/v1` JSON, sealed to each of the link's confirmed devices and to nothing else. */\nexport async function sealFlagDraftsV1(input: { drafts: FlagDraftsV1; handle: string; reference: string; version: number; devices: readonly FlagNoteDeviceV1[] }): Promise<SealedFlagNoteV1> {\n const read = readFlagDraftsV1(input?.drafts);\n if (!read.ok || !Array.isArray(input.devices) || input.devices.length === 0) throw new ReaderCryptoError('SEALED_NOTE_MALFORMED');\n const name = flagDraftsNoteNameV1({ handle: input.handle, reference: input.reference, version: input.version });\n const { note, wraps } = await sealTo(JSON.stringify(read.drafts), name, input.devices, null);\n return { note, wraps };\n}\n\n/** Opens the team's drafts as saved at `version`, and reads them member by member. Never throws. */\nexport async function openFlagDraftsV1(input: { note: unknown; wrap: unknown; seed: WorkspaceSeedV1; handle: string; reference: string; version: number }): Promise<{ ok: true; drafts: FlagDraftsV1 } | { ok: false; code: string }> {\n let name: NoteNameV1;\n try {\n name = flagDraftsNoteNameV1({ handle: input.handle, reference: input.reference, version: input.version });\n } catch {\n return { ok: false, code: 'READER_BINDING_INVALID' };\n }\n const opened = await openFlagNoteV1({ note: input.note, wrap: input.wrap, seed: input.seed, name });\n if (!opened.ok) return opened;\n try {\n const read = readFlagDraftsV1(JSON.parse(opened.text));\n return read.ok ? read : { ok: false, code: 'SEALED_NOTE_MALFORMED' };\n } catch {\n return { ok: false, code: 'SEALED_NOTE_MALFORMED' };\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA6CA,SAAS,aAAa,YAAwB,KAAa,IAAwB;AAIjF,QAAM,QAAQ,IAAI,WAAW,EAAE;AAC/B,QAAM,IAAI,UAAU;AACpB,MAAI,IAAI;AACR,WAAS,IAAI,KAAK,GAAG,KAAK,KAAK,IAAI,GAAG,KAAK;AACzC,UAAM,CAAC,IAAI,MAAM,CAA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MAAM,MAAM,MAAM,MAAM,MAAM,MAAM,MAAM,MAAM,KAAK,CAAC;AAClG,MAAI,CAAC,OAAO,GAAI,QAAO;AACvB,MAAI;AACF,UAAM,OAAO,iBAAiB,KAAK,MAAM,OAAO,IAAI,CAAC;AACrD,WAAO,KAAK,KAAK,OAAO,EAAE,IAAI,OAAO,MAAM,wBAAwB;AAAA,EACrE,QAAQ;AACN,WAAO,EAAE,IAAI,OAAO,MAAM,wBAAwB;AAAA,EACpD;AACF;",
|
|
6
|
+
"names": ["L", "bytes", "exporter_secret", "N", "toBase64Url", "Fn", "jwk", "privateKey", "x", "d", "id", "N2", "AEAD_ChaCha20Poly1305", "bytes", "opts", "isLE", "opts", "ZEROS16", "ZEROS32", "bytes", "mul2", "POLY", "sbox", "sbox2", "t0", "t1", "t2", "t3", "isLE", "BLOCK_SIZE", "computeTag", "split", "isLE", "isBytes", "anumber", "atitle", "abool", "abytes", "bytes", "aexists", "aoutput", "u32", "clean", "createView", "byteSwap", "byteSwap32", "hex", "concatBytes", "checkOpts", "opts", "randomBytes", "aobject", "isLE", "swap32IfBE", "init_utils", "anumber", "clean", "init_utils", "split", "abool", "u32", "swap32IfBE", "aexists", "abytes", "bytes", "aoutput", "opts", "checkOpts", "opts", "checkOpts", "init_utils", "D", "init_utils", "abytes", "clean", "aexists", "aoutput", "anumber", "abytes", "clean", "init_utils", "init_utils", "isLE", "createView", "aexists", "abytes", "aoutput", "sha256", "init_utils", "B", "D", "F", "clean", "split", "fromBig", "U32_MASK64", "_32n", "split", "setU64FromNum", "isLE", "fromNumH", "fromNumL", "add", "shrSH", "shrSL", "rotrSH", "rotrSL", "rotrBH", "rotrBL", "add3L", "add3H", "add4L", "add4H", "add5L", "add5H", "init_u64", "isBytes", "anumber", "atitle", "abool", "abytes", "bytes", "ahash", "aexists", "aoutput", "u32", "clean", "createView", "rotr", "byteSwap", "byteSwap32", "bytesToHex", "hasHexBuiltin", "hex", "hexes", "asciiToBase16", "hexToBytes", "concatBytes", "checkOpts", "opts", "aopts", "createHasher", "randomBytes", "aobject", "isLE", "swap32IfBE", "oidNist", "init_utils", "keccakP", "anumber", "B", "rotlH", "rotlL", "SHA3_ROTL", "SHA3_PI", "SHA3_IOTA_H", "SHA3_IOTA_L", "clean", "_0n", "_1n", "_2n", "_7n", "_256n", "_0x71n", "_SHA3_IOTA", "IOTAS", "rotlSH", "rotlSL", "rotlBH", "rotlBL", "Keccak", "genShake", "shake128", "shake256", "init_sha3", "init_u64", "init_utils", "split", "abool", "u32", "swap32IfBE", "aexists", "abytes", "bytes", "aoutput", "createHasher", "oidNist", "opts", "checkOpts", "aobject", "abool", "atitle", "anumber", "hex", "_0n", "bytes", "bytesToHex", "copyBytes", "abytes", "hexToBytes", "concatBytes", "isBytes", "randomBytes", "_1n", "init_utils", "_0n", "_1n", "p", "_2n", "Fp", "F", "_7n", "Q", "aobject", "abool", "anumber", "opts", "isLE", "abytes", "init_utils", "bytes", "init_utils", "F", "N", "aarray", "aobject", "equalBytes", "abytes", "copyBytes", "bytes", "opts", "isBytes", "anumber", "concatBytes", "ahash", "bytesToHex", "astring", "randomBytes", "init_utils", "init_sha3", "init_utils", "opts", "newPoly", "N", "Q", "F", "ROOT_OF_UNITY", "mod", "bytes", "shake128", "shake256", "opts", "copyBytes", "equalBytes", "randomBytes", "shake256", "init_sha3", "init_utils", "u32", "swap32IfBE", "aobject", "bytes", "randomBytes", "isBytes", "_0n", "_1n", "abool", "_4n", "isLE", "Fp", "Fn", "getPublicKey", "init_utils", "Fp", "opts", "Fn", "randomBytes", "_2n", "_1n", "uvRatio", "_0n", "bytes", "copyBytes", "abytes", "abool", "hex", "hexToBytes", "B", "D", "F", "_8n", "_4n", "bytesToHex", "init_utils", "_1n", "validateOpts", "adjustScalarBytes", "randomBytes", "_2n", "copyBytes", "abytes", "_0n", "getPublicKey", "mask", "B", "D", "init_utils", "_HMAC", "hmac", "init_hmac", "init_utils", "ahash", "abytes", "clean", "aexists", "aoutput", "_0n", "init_utils", "abytes", "hex", "bytes", "_0n", "_1n", "validateSigOpts", "opts", "abool", "Fp", "Fn", "randomBytes", "concatBytes", "bytes", "abytes", "L", "_3n", "_4n", "hex", "hexToBytes", "bytesToHex", "getPublicKey", "isBytes", "ahash", "hmac", "_2n", "r", "s", "Q", "init_hmac", "init_utils", "Chi", "Maj", "HashMD", "SHA256_IV", "SHA384_IV", "init_md", "init_u64", "init_utils", "isLE", "createView", "aexists", "abytes", "aoutput", "setU64FromNum", "SHA256_K", "SHA256_W", "SHA2_32B", "_SHA256", "K512", "SHA512_Kh", "SHA512_Kl", "SHA512_W_H", "SHA512_W_L", "SHA2_64B", "_SHA384", "sha256", "sha384", "init_sha2", "init_md", "init_u64", "init_utils", "HashMD", "B", "D", "F", "rotr", "Chi", "Maj", "clean", "SHA256_IV", "split", "rotrSH", "shrSH", "rotrSL", "shrSL", "rotrBH", "rotrBL", "add4L", "add4H", "add5L", "add5H", "add", "add3L", "add3H", "SHA384_IV", "createHasher", "oidNist", "_2n", "_1n", "_5n", "bytes", "pow", "_0n", "_3n", "_8n", "init_sha2", "sha256", "sha384", "extract", "ahash", "hmac", "expand", "anumber", "abytes", "EMPTY_BUFFER", "clean", "HKDF_COUNTER", "init_hkdf", "init_hmac", "init_utils", "aobject", "abool", "Fn", "randomBytes", "abytes", "copyBytes", "opts", "anumber", "isBytes", "astring", "ahash", "concatBytes", "extract", "expand", "shake256", "init_utils", "init_hkdf", "init_sha2", "init_sha3", "sha256", "aarray", "astring", "aobject", "afunction", "abool", "atitle", "abignumber", "isPosBig", "anumber", "asafenumber", "numberToHexUnpadded", "hex", "hexToNumber", "_0n", "bytesToNumberBE", "bytes", "bytesToNumberLE", "copyBytes", "abytes", "numberToBytesBE", "numberToBytesLE", "inRange", "aInRange", "bitLen", "createHmacDrbg", "concatBytes", "validateObject", "bytesToHex", "hexToBytes", "isBytes", "randomBytes", "_1n", "bitMask", "init_utils", "mod", "_0n", "pow", "_1n", "POW_WINDOWED_MIN", "p", "_15n", "_4n", "pow2", "invert", "invertCt", "_2n", "assertIsSquare", "Fp", "F", "aoddModulus", "sqrt3mod4", "sqrt5mod8", "_5n", "_8n", "sqrt9mod16", "Field", "tonelliShanks", "_7n", "_16n", "_3n", "Q", "FpLegendre", "FpSqrt", "_9n", "validateField", "aobject", "asafenumber", "FIELD_FIELDS", "afunction", "FpInvertBatch", "aarray", "abool", "nLength", "anumber", "bitLen", "opts", "_Field", "getFieldBytesLength", "getMinHashLength", "mapHashToField", "isLE", "abytes", "bytesToNumberLE", "bytesToNumberBE", "numberToBytesLE", "numberToBytesBE", "isNegativeLE", "FIELD_SQRT", "init_modular", "init_utils", "bytes", "validatePointCons", "afunction", "aobject", "validateField", "normalizeZ", "validateMSMPoints", "FpInvertBatch", "validateW", "validateTableBytes", "bytes", "TABLE_BYTES_MAX", "probeRandomBytes", "randomBytes", "isBytes", "aarray", "validateMSMScalars", "isPosBig", "getWindowSize", "pointWindowSizes", "oddMultiples", "wnafDigits", "_0n", "_1n", "signedWindowDigits", "wnafWalk", "mulAddUnsafe", "abool", "_4n", "createField", "isLE", "Field", "createCurveFields", "validateObject", "Fp", "Fn", "createKeygen", "getPublicKey", "BLIND_BYTES", "BLIND_BITS", "FW_WINDOW", "ScalarMultiplier", "init_curve", "init_utils", "init_modular", "inRange", "bytesToNumberBE", "bitMask", "isEdValidXY", "Fp", "edwards", "validateObject", "opts", "createCurveFields", "Fn", "FpLegendre", "randomBytes", "_2n", "_1n", "uvRatio", "_0n", "aInRange", "bytes", "copyBytes", "abytes", "abool", "bytesToNumberLE", "hex", "hexToBytes", "B", "D", "F", "_8n", "_4n", "bytesToHex", "normalizeZ", "ScalarMultiplier", "init_edwards", "init_utils", "init_curve", "init_modular", "cmask", "_1n", "cswap", "validateOpts", "validateObject", "montgomery", "adjustScalarBytes", "randomBytes", "_2n", "mod", "numberToBytesLE", "copyBytes", "abytes", "bytesToNumberLE", "_0n", "aInRange", "getPublicKey", "mask", "B", "D", "createKeygen", "init_montgomery", "init_utils", "init_curve", "init_modular", "ed25519_pow_2_252_3", "ed25519_CURVE_p", "pow2", "_2n", "_1n", "_5n", "adjustScalarBytes", "bytes", "uvRatio", "mod", "pow", "ED25519_SQRT_M1", "isNegativeLE", "_0n", "_3n", "_8n", "ed25519_CURVE", "ed25519_Point", "x25519", "init_ed25519", "init_edwards", "init_modular", "init_montgomery", "edwards", "montgomery", "pow2", "_3n", "_2n", "_1n", "adjustScalarBytes", "bytes", "uvRatio", "mod", "_0n", "init_edwards", "init_modular", "init_montgomery", "Field", "edwards", "montgomery", "_0n", "DERErr", "_DER", "DER", "init_der", "init_utils", "asafenumber", "astring", "numberToHexUnpadded", "abytes", "abignumber", "hex", "bytesToNumberBE", "bytes", "validateObject", "_splitEndoScalar", "aInRange", "_0n", "divNearest", "bitMask", "bitLen", "_1n", "validateSigFormat", "validateSigOpts", "opts", "validateObject", "abool", "weierstrass", "createCurveFields", "Fp", "Fn", "randomBytes", "getWLengths", "concatBytes", "pprefix", "bytes", "abytes", "L", "_3n", "_4n", "hex", "hexToBytes", "mulAddUnsafe", "bytesToHex", "normalizeZ", "ScalarMultiplier", "ecdh", "validatePointCons", "getMinHashLength", "mapHashToField", "getPublicKey", "isBytes", "createKeygen", "ecdsa", "hmac", "probeRandomBytes", "_2n", "DER", "r", "s", "Q", "bytesToNumberBE", "invertCt", "createHmacDrbg", "init_weierstrass", "init_utils", "init_curve", "init_der", "init_modular", "p256_CURVE", "p384_CURVE", "p256_Point", "p256", "p384_Point", "p384", "init_nist", "init_weierstrass", "weierstrass", "ecdsa", "sha256", "AEAD_AES_128_GCM", "AEAD_AES_256_GCM", "AEAD_ChaCha20Poly1305", "KDF_HKDF_SHA256", "KDF_HKDF_SHA384", "KDF_HKDF_SHA512", "KDF_SHAKE128", "KDF_SHAKE256", "KDF_TurboSHAKE128", "KDF_TurboSHAKE256", "KEM_DHKEM_P256_HKDF_SHA256", "KEM_DHKEM_P384_HKDF_SHA384", "KEM_DHKEM_P521_HKDF_SHA512", "KEM_DHKEM_X25519_HKDF_SHA256", "KEM_DHKEM_X448_HKDF_SHA512", "KEM_MLKEM1024_P384", "KEM_MLKEM768_P256", "KEM_MLKEM768_X25519", "KEM_ML_KEM_1024", "KEM_ML_KEM_512", "KEM_ML_KEM_768", "id", "L", "D", "ikm", "priv", "slice", "bytes", "AES_GCM_P_MAX", "CHACHA20_POLY1305_P_MAX", "InvalidInvocation", "init_ed25519", "init_nist", "sha256", "p256", "p384", "x25519", "PARAMS", "opts", "abool", "N", "Q", "L", "XOF128", "XOF256", "crystals", "polyCoder", "shake256", "randomBytes", "polyAdd", "MultiplyNTTs", "polySub", "equalBytes", "ROOT_OF_UNITY", "F", "init_utils", "init_sha3", "compress", "B", "bytes", "subtle", "bytes", "bytes", "subtle", "LABEL_SALT", "LABEL_LEAF", "LABEL_RECORD", "SEP", "NOT_CANONICAL", "SHOWN_FIELD_MISMATCH", "LONE_SURROGATE", "CANONICAL_INDEX", "FIRST_SEGMENT", "escapeSegment", "unescapeSegment", "isPlainObject", "hasLoneSurrogate", "import_ethers", "import_ethers", "bytes", "import_ethers", "import_ethers", "import_ethers", "SEP", "utf8", "utf8", "SEP", "utf8", "SEP", "utf8", "SEP", "LONE_SURROGATE", "hasLoneSurrogate", "isPlainObject", "split", "bytes", "REASONS", "refuse", "bytes", "subtle", "SEP", "IV_BYTES", "refuse", "bytes", "refuse", "KEY_BYTES", "IV_BYTES", "TAG_BYTES", "SPACE", "SEP", "HEX64", "bytes", "id", "bytesOf", "subtle", "hex", "aadOf", "aesKey", "refuse", "SEP", "HEX64", "WIRE_ID", "IV_BYTES", "INSPECT", "L", "HiddenKey", "bytes", "INSPECT", "L", "SEP", "aesKey", "subtle", "IV_BYTES", "HEX64", "refuse", "WIRE_ID", "hex", "SEP", "HEX64", "hex", "bytes", "subtle", "hex", "SEP", "HEX64", "HEX64", "subtle", "note", "subtle", "note", "import_ethers", "CONTROL", "CONTROL", "note", "CONTROL", "note"]
|
|
7
|
+
}
|